Programs & Examples On #Autoproxy

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

Here is what I do. All of these instructions are based on my minimal experiences with working PACs, so YMMV.

Download your pac file via your pac URL. It's plain text and should be easy to open in a text editor.

Near the bottom, there's probably a section that says something like: return "PROXY w.x.y.z:a" where "w.x.y.z" is an ip address or username and "a" is a port number.

Write these down.

In a recent version of eclipse :

  • Go to Window -> Preferences -> General -> Network Connections=
  • Change the provider to "Manual"
  • Select the "HTTP" line and click the edit button
  • Add the IP address and port number above to the http line
  • If you have to authenticate to use the proxy,
    • select "Requires Authentication"
    • type in your username. Note that if your authentication is on a Windows domain, you might have to prepend the domain name and a backslash (\) like: MYDOMAIN\MYUSERID
    • Type in your password
  • Click OK
  • Click Apply
  • Click OK

At this point, you should be able to browse using the internal web browser (at least on http URLs).

Good luck.

Edit: Just so you know, it's WAY easier to use Nexus, one set of <mirror> tags and a single proxy setup (inside Nexus) to manage the proxy issues of Maven inside a firewall.

React.js: How to append a component on click?

Don't use jQuery to manipulate the DOM when you're using React. React components should render a representation of what they should look like given a certain state; what DOM that translates to is taken care of by React itself.

What you want to do is store the "state which determines what gets rendered" higher up the chain, and pass it down. If you are rendering n children, that state should be "owned" by whatever contains your component. eg:

class AppComponent extends React.Component {
  state = {
    numChildren: 0
  }

  render () {
    const children = [];

    for (var i = 0; i < this.state.numChildren; i += 1) {
      children.push(<ChildComponent key={i} number={i} />);
    };

    return (
      <ParentComponent addChild={this.onAddChild}>
        {children}
      </ParentComponent>
    );
  }

  onAddChild = () => {
    this.setState({
      numChildren: this.state.numChildren + 1
    });
  }
}

const ParentComponent = props => (
  <div className="card calculator">
    <p><a href="#" onClick={props.addChild}>Add Another Child Component</a></p>
    <div id="children-pane">
      {props.children}
    </div>
  </div>
);

const ChildComponent = props => <div>{"I am child " + props.number}</div>;

Save plot to image file instead of displaying it using Matplotlib

Just found this link on the MatPlotLib documentation addressing exactly this issue: http://matplotlib.org/faq/howto_faq.html#generate-images-without-having-a-window-appear

They say that the easiest way to prevent the figure from popping up is to use a non-interactive backend (eg. Agg), via matplotib.use(<backend>), eg:

import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
plt.plot([1,2,3])
plt.savefig('myfig')

I still personally prefer using plt.close( fig ), since then you have the option to hide certain figures (during a loop), but still display figures for post-loop data processing. It is probably slower than choosing a non-interactive backend though - would be interesting if someone tested that.

UPDATE: for Spyder, you usually can't set the backend in this way (Because Spyder usually loads matplotlib early, preventing you from using matplotlib.use()).

Instead, use plt.switch_backend('Agg'), or Turn off "enable support" in the Spyder prefs and run the matplotlib.use('Agg') command yourself.

From these two hints: one, two

Difference between 2 dates in SQLite

Both answers provide solutions a bit more complex, as they need to be. Say the payment was created on January 6, 2013. And we want to know the difference between this date and today.

sqlite> SELECT julianday() - julianday('2013-01-06');
34.7978485878557 

The difference is 34 days. We can use julianday('now') for better clarity. In other words, we do not need to put date() or datetime() functions as parameters to julianday() function.

Maven: repository element was not specified in the POM inside distributionManagement?

Review the pom.xml file inside of target/checkout/. Chances are, the pom.xml in your trunk or master branch does not have the distributionManagement tag.

How to connect to MongoDB in Windows?

If you are getting these type of errors when running mongod from command line or running mongodb server, enter image description here
then follow these steps,

  1. Create db and log directories in C: drive
    C:/data/db and C:data/log
  2. Create an empty log file in log dir named mongo.log
  3. Run mongod from command line to run the mongodb server or create a batch file on desktop which can run the mongod.exe file from your mongodb installation direction. That way you just have to click the batch file from your desktop and mongodb will start.
  4. If you have 32-bit system, try using --journal with mongod command.

Tracking the script execution time in PHP

If all you need is the wall-clock time, rather than the CPU execution time, then it is simple to calculate:

//place this before any script you want to calculate time
$time_start = microtime(true); 

//sample script
for($i=0; $i<1000; $i++){
 //do anything
}

$time_end = microtime(true);

//dividing with 60 will give the execution time in minutes otherwise seconds
$execution_time = ($time_end - $time_start)/60;

//execution time of the script
echo '<b>Total Execution Time:</b> '.$execution_time.' Mins';
// if you get weird results, use number_format((float) $execution_time, 10) 

Note that this will include time that PHP is sat waiting for external resources such as disks or databases, which is not used for max_execution_time.

sql use statement with variable

I case that someone need a solution for this, this is one:

if you use a dynamic USE statement all your query need to be dynamic, because it need to be everything in the same context.

You can try with SYNONYM, is basically an ALIAS to a specific Table, this SYNONYM is inserted into the sys.synonyms table so you have access to it from any context

Look this static statement:

CREATE SYNONYM MASTER_SCHEMACOLUMNS FOR Master.INFORMATION_SCHEMA.COLUMNS
SELECT * FROM MASTER_SCHEMACOLUMNS

Now dynamic:

DECLARE @SQL VARCHAR(200)
DECLARE @CATALOG VARCHAR(200) = 'Master'

IF EXISTS(SELECT * FROM  sys.synonyms s WHERE s.name = 'CURRENT_SCHEMACOLUMNS')
BEGIN
DROP SYNONYM CURRENT_SCHEMACOLUMNS
END

SELECT @SQL = 'CREATE SYNONYM CURRENT_SCHEMACOLUMNS FOR '+ @CATALOG +'.INFORMATION_SCHEMA.COLUMNS';
EXEC sp_sqlexec @SQL

--Your not dynamic Code
SELECT * FROM CURRENT_SCHEMACOLUMNS

Now just change the value of @CATALOG and you will be able to list the same table but from different catalog.

Moving Average Pandas

A moving average can also be calculated and visualized directly in a line chart by using the following code:

Example using stock price data:

import pandas_datareader.data as web
import matplotlib.pyplot as plt
import datetime
plt.style.use('ggplot')

# Input variables
start = datetime.datetime(2016, 1, 01)
end = datetime.datetime(2018, 3, 29)
stock = 'WFC'

# Extrating data
df = web.DataReader(stock,'morningstar', start, end)
df = df['Close']

print df 

plt.plot(df['WFC'],label= 'Close')
plt.plot(df['WFC'].rolling(9).mean(),label= 'MA 9 days')
plt.plot(df['WFC'].rolling(21).mean(),label= 'MA 21 days')
plt.legend(loc='best')
plt.title('Wells Fargo\nClose and Moving Averages')
plt.show()

Tutorial on how to do this: https://youtu.be/XWAPpyF62Vg

Row names & column names in R

And another expansion:

# create dummy matrix
set.seed(10)
m <- matrix(round(runif(25, 1, 5)), 5)
d <- as.data.frame(m)

If you want to assign new column names you can do following on data.frame:

# an identical effect can be achieved with colnames()   
names(d) <- LETTERS[1:5]
> d
  A B C D E
1 3 2 4 3 4
2 2 2 3 1 3
3 3 2 1 2 4
4 4 3 3 3 2
5 1 3 2 4 3

If you, however run previous command on matrix, you'll mess things up:

names(m) <- LETTERS[1:5]
> m
     [,1] [,2] [,3] [,4] [,5]
[1,]    3    2    4    3    4
[2,]    2    2    3    1    3
[3,]    3    2    1    2    4
[4,]    4    3    3    3    2
[5,]    1    3    2    4    3
attr(,"names")
 [1] "A" "B" "C" "D" "E" NA  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA 
[20] NA  NA  NA  NA  NA  NA 

Since matrix can be regarded as two-dimensional vector, you'll assign names only to first five values (you don't want to do that, do you?). In this case, you should stick with colnames().

So there...

Where's the DateTime 'Z' format specifier?

Label1.Text = dt.ToString("dd MMM yyyy | hh:mm | ff | zzz | zz | z");

will output:

07 Mai 2009 | 08:16 | 13 | +02:00 | +02 | +2

I'm in Denmark, my Offset from GMT is +2 hours, witch is correct.

if you need to get the CLIENT Offset, I recommend that you check a little trick that I did. The Page is in a Server in UK where GMT is +00:00 and, as you can see you will get your local GMT Offset.


Regarding you comment, I did:

DateTime dt1 = DateTime.Now;
DateTime dt2 = dt1.ToUniversalTime();

Label1.Text = dt1.ToString("dd MMM yyyy | hh:mm | ff | zzz | zz | z");
Label2.Text = dt2.ToString("dd MMM yyyy | hh:mm | FF | ZZZ | ZZ | Z");

and I get this:

07 Mai 2009 | 08:24 | 14 | +02:00 | +02 | +2
07 Mai 2009 | 06:24 | 14 | ZZZ | ZZ | Z 

I get no Exception, just ... it does nothing with capital Z :(

I'm sorry, but am I missing something?


Reading carefully the MSDN on Custom Date and Time Format Strings

there is no support for uppercase 'Z'.

bash: pip: command not found

It solved my problem by using

sudo easy_install pip

How to set proxy for wget?

wget uses environment variables somthing like this at command line can work:

export http_proxy=http://your_ip_proxy:port/
export https_proxy=$http_proxy
export ftp_proxy=$http_proxy
export dns_proxy=$http_proxy
export rsync_proxy=$http_proxy
export no_proxy="localhost,127.0.0.1,localaddress,.localdomain.com"

Html- how to disable <a href>?

You can use CSS to accomplish this:

_x000D_
_x000D_
.disabled {
  pointer-events: none;
  cursor: default;
}
_x000D_
<a href="somelink.html" class="disabled">Some link</a>
_x000D_
_x000D_
_x000D_

Or you can use JavaScript to prevent the default action like this:

$('.disabled').click(function(e){
    e.preventDefault();
})

How to access host port from docker container

When you have two docker images "already" created and you want to put two containers to communicate with one-another.

For that, you can conveniently run each container with its own --name and use the --link flag to enable communication between them. You do not get this during docker build though.

When you are in a scenario like myself, and it is your

docker build -t "centos7/someApp" someApp/ 

That breaks when you try to

curl http://172.17.0.1:localPort/fileIWouldLikeToDownload.tar.gz > dump.tar.gz

and you get stuck on "curl/wget" returning no "route to host".

The reason is security that is set in place by docker that by default is banning communication from a container towards the host or other containers running on your host. This was quite surprising to me, I must say, you would expect the echosystem of docker machines running on a local machine just flawlessly can access each other without too much hurdle.

The explanation for this is described in detail in the following documentation.

http://www.dedoimedo.com/computers/docker-networking.html

Two quick workarounds are given that help you get moving by lowering down the network security.

The simplest alternative is just to turn the firewall off - or allow all. This means running the necessary command, which could be systemctl stop firewalld, iptables -F or equivalent.

Hope this information helps you.

Use multiple custom fonts using @font-face?

If you are having a problem with the font working I have also had this in the past and the issue I found was down to the font-family: name. This had to match what font name was actually given.

The easiest way I found to find this out was to install the font and see what display name is given.

For example, I was using Gill Sans on one project, but the actual font was called Gill Sans MT. Spacing and capitlisation was also important to get right.

Hope that helps.

Usage of sys.stdout.flush() method

Python's standard out is buffered (meaning that it collects some of the data "written" to standard out before it writes it to the terminal). Calling sys.stdout.flush() forces it to "flush" the buffer, meaning that it will write everything in the buffer to the terminal, even if normally it would wait before doing so.

Here's some good information about (un)buffered I/O and why it's useful:
http://en.wikipedia.org/wiki/Data_buffer
Buffered vs unbuffered IO

JPA Query.getResultList() - use in a generic way

If you need a more convenient way to access the results, it's possible to transform the result of an arbitrarily complex SQL query to a Java class with minimal hassle:

Query query = em.createNativeQuery("select 42 as age, 'Bob' as name from dual", 
        MyTest.class);
MyTest myTest = (MyTest) query.getResultList().get(0);
assertEquals("Bob", myTest.name);

The class needs to be declared an @Entity, which means you must ensure it has an unique @Id.

@Entity
class MyTest {
    @Id String name;
    int age;
}

Bash script to check running process

I use this one to check every 10 seconds process is running and start if not and allows multiple arguments:

#!/bin/sh

PROCESS="$1"
PROCANDARGS=$*

while :
do
    RESULT=`pgrep ${PROCESS}`

    if [ "${RESULT:-null}" = null ]; then
            echo "${PROCESS} not running, starting "$PROCANDARGS
            $PROCANDARGS &
    else
            echo "running"
    fi
    sleep 10
done    

How to make a simple rounded button in Storyboard?

  1. Create a Cocoa Touch class.

enter image description here

  1. Insert the code in RoundButton class.

    import UIKit
    
    @IBDesignable
    class RoundButton: UIButton {
    
        @IBInspectable var cornerRadius: CGFloat = 0{
            didSet{
            self.layer.cornerRadius = cornerRadius
            }
        }
    
        @IBInspectable var borderWidth: CGFloat = 0{
            didSet{
                self.layer.borderWidth = borderWidth
            }
        }
    
        @IBInspectable var borderColor: UIColor = UIColor.clear{
            didSet{
                self.layer.borderColor = borderColor.cgColor
            }
        }
    }
    
  2. Refer the image.

enter image description here

java.io.FileNotFoundException: (Access is denied)

Here's a gotcha that I just discovered - perhaps it might help someone else. If using windows the classes folder must not have encryption enabled! Tomcat doesn't seem to like that. Right click on the classes folder, select "Properties" and then click the "Advanced..." button. Make sure the "Encrypt contents to secure data" checkbox is cleared. Restart Tomcat.

It worked for me so here's hoping it helps someone else, too.

How to build a 2 Column (Fixed - Fluid) Layout with Twitter Bootstrap?

Update 2018

Bootstrap 4

Now that BS4 is flexbox, the fixed-fluid is simple. Just set the width of the fixed column, and use the .col class on the fluid column.

.sidebar {
    width: 180px;
    min-height: 100vh;
}

<div class="row">
    <div class="sidebar p-2">Fixed width</div>
    <div class="col bg-dark text-white pt-2">
        Content
    </div>
</div>

http://www.codeply.com/go/7LzXiPxo6a

Bootstrap 3..

One approach to a fixed-fluid layout is using media queries that align with Bootstrap's breakpoints so that you only use the fixed width columns are larger screens and then let the layout stack responsively on smaller screens...

@media (min-width:768px) {
  #sidebar {
      min-width: 300px;
      max-width: 300px;
  }
  #main {
      width:calc(100% - 300px);
  }
}

Working Bootstrap 3 Fixed-Fluid Demo

Related Q&A:
Fixed width column with a container-fluid in bootstrap
How to left column fixed and right scrollable in Bootstrap 4, responsive?

How to execute .sql file using powershell?

with 2008 Server 2008 and 2008 R2

Add-PSSnapin -Name SqlServerCmdletSnapin100, SqlServerProviderSnapin100

with 2012 and 2014

Push-Location
Import-Module -Name SQLPS -DisableNameChecking
Pop-Location

Angular 2: Passing Data to Routes?

1. Set up your routes to accept data

{
    path: 'some-route',
    loadChildren: 
      () => import(
        './some-component/some-component.module'
      ).then(
        m => m.SomeComponentModule
      ),
    data: {
      key: 'value',
      ...
    },
}

2. Navigate to route:

From HTML:

<a [routerLink]=['/some-component', { key: 'value', ... }> ... </a>

Or from Typescript:

import {Router} from '@angular/router';

...

 this.router.navigate(
    [
       '/some-component',
       {
          key: 'value',
          ...
       }
    ]
 );

3. Get data from route

import {ActivatedRoute} from '@angular/router';

...

this.value = this.route.snapshot.params['key'];

How to display an image stored as byte array in HTML/JavaScript?

Try putting this HTML snippet into your served document:

<img id="ItemPreview" src="">

Then, on JavaScript side, you can dynamically modify image's src attribute with so-called Data URL.

document.getElementById("ItemPreview").src = "data:image/png;base64," + yourByteArrayAsBase64;

Alternatively, using jQuery:

$('#ItemPreview').attr('src', `data:image/png;base64,${yourByteArrayAsBase64}`);

This assumes that your image is stored in PNG format, which is quite popular. If you use some other image format (e.g. JPEG), modify the MIME type ("image/..." part) in the URL accordingly.

Similar Questions:

powershell is missing the terminator: "

This can also occur when the path ends in a '' followed by the closing quotation mark. e.g. The following line is passed as one of the arguments and this is not right:

"c:\users\abc\"

instead pass that argument as shown below so that the last backslash is escaped instead of escaping the quotation mark.

"c:\users\abc\\"

OnChange event handler for radio button (INPUT type="radio") doesn't work as one value

this works for me

<input ID="TIPO_INST-0" Name="TIPO_INST" Type="Radio" value="UNAM" onchange="convenio_unam();">UNAM

<script type="text/javascript">
            function convenio_unam(){
                if(this.document.getElementById('TIPO_INST-0').checked){
                    $("#convenio_unam").hide();
                }else{
                    $("#convenio_unam").show(); 
                }                               
            }
</script>

run main class of Maven project

Although maven exec does the trick here, I found it pretty poor for a real test. While waiting for maven shell, and hoping this could help others, I finally came out to this repo mvnexec

Clone it, and symlink the script somewhere in your path. I use ~/bin/mvnexec, as I have ~/bin in my path. I think mvnexec is a good name for the script, but is up to you to change the symlink...

Launch it from the root of your project, where you can see src and target dirs.

The script search for classes with main method, offering a select to choose one (Example with mavenized JMeld project)

$ mvnexec 
 1) org.jmeld.ui.JMeldComponent
 2) org.jmeld.ui.text.FileDocument
 3) org.jmeld.JMeld
 4) org.jmeld.util.UIDefaultsPrint
 5) org.jmeld.util.PrintProperties
 6) org.jmeld.util.file.DirectoryDiff
 7) org.jmeld.util.file.VersionControlDiff
 8) org.jmeld.vc.svn.InfoCmd
 9) org.jmeld.vc.svn.DiffCmd
10) org.jmeld.vc.svn.BlameCmd
11) org.jmeld.vc.svn.LogCmd
12) org.jmeld.vc.svn.CatCmd
13) org.jmeld.vc.svn.StatusCmd
14) org.jmeld.vc.git.StatusCmd
15) org.jmeld.vc.hg.StatusCmd
16) org.jmeld.vc.bzr.StatusCmd
17) org.jmeld.Main
18) org.apache.commons.jrcs.tools.JDiff
#? 

If one is selected (typing number), you are prompt for arguments (you can avoid with mvnexec -P)

By default it compiles project every run. but you can avoid that using mvnexec -B

It allows to search only in test classes -M or --no-main, or only in main classes -T or --no-test. also has a filter by name option -f <whatever>

Hope this could save you some time, for me it does.

HTTP Error 500.22 - Internal Server Error (An ASP.NET setting has been detected that does not apply in Integrated managed pipeline mode.)

This issue is caused by the pipeline mode in your Application Pool setting that your web site is set to.

Short

  • Simple way Change the Application Pool mode to one that has Classic pipeline enabled.
  • Correct way Your web.config / web app will need to be altered to support Integrated pipelines. Normally this is as simple as removing parts of your web.config.
  • Simple way (bad practice) Add the following to your web.config. See http://www.iis.net/ConfigReference/system.webServer/validation

     <system.webServer>
         <validation validateIntegratedModeConfiguration="false" />
     </system.webServer>
    

Long If possible, your best bet is to change your application to support the integrated pipelines. There are a number of changes between IIS6 and IIS7.x that will cause this error. You can find details about these changes here http://learn.iis.net/page.aspx/381/aspnet-20-breaking-changes-on-iis-70/.

If you're unable to do that, you'll need to change the App pool which may be more difficult to do depending on your availability to the web server.

  • Go to the web server
  • Open the IIS Manager
  • Navigate to your site
  • Click Advanced Settings on the right Action pane
  • Under Application Pool, change it to an app pool that has classic enabled.

Check http://technet.microsoft.com/en-us/library/cc731755(WS.10).aspx for details on changing the App Pool

If you need to create an App Pool with Classic pipelines, take a look at http://technet.microsoft.com/en-us/library/cc731784(WS.10).aspx

If you don't have access to the server to make this change, you'll need to do this through your hosting server and contact them for help.

Feel free to ask questions.

How to add elements to an empty array in PHP?

REMEMBER, this method overwrites first array, so use only when you are sure!

$arr1 = $arr1 + $arr2;

(see source)

How to set entire application in portrait mode only?

You can do it in two ways .

  1. Add android:screenOrientation="portrait" on your manifest file to the corresponding activity
  2. Add setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); to your activity in `onCreate() method

Getting Date or Time only from a DateTime Object

Sometimes you want to have your GridView as simple as:

  <asp:GridView ID="grid" runat="server" />

You don't want to specify any BoundField, you just want to bind your grid to DataReader. The following code helped me to format DateTime in this situation.

protected void Page_Load(object sender, EventArgs e)
{
  grid.RowDataBound += grid_RowDataBound;
  // Your DB access code here...
  // grid.DataSource = cmd.ExecuteReader(CommandBehavior.CloseConnection);
  // grid.DataBind();
}

void grid_RowDataBound(object sender, GridViewRowEventArgs e)
{
  if (e.Row.RowType != DataControlRowType.DataRow)
    return;
  var dt = (e.Row.DataItem as DbDataRecord).GetDateTime(4);
  e.Row.Cells[4].Text = dt.ToString("dd.MM.yyyy");
}

The results shown here. DateTime Formatting

Change the location of the ~ directory in a Windows install of Git Bash

1.Right click to Gitbash shortcut choose Properties
2.Choose "Shortcut" tab
3.Type your starting directory to "Start in" field
4.Remove "--cd-to-home" part from "Target" field

how to read a text file using scanner in Java?

This should help you..:

import java.io.*;
import static java.lang.System.*;
/**
* Write a description of class InRead here.
* 
* @author (your name) 
* @version (a version number or a date)
*/
public class InRead
{
public InRead(String Recipe)
{
    find(Recipe);
}
public void find(String Name){
    String newRecipe= Name+".txt";
    try{
        FileReader fr= new FileReader(newRecipe);
        BufferedReader br= new BufferedReader(fr);

        String str;


    while ((str=br.readLine()) != null){
            out.println(str + "\n");
        }
        br.close();

    }catch (IOException e){
        out.println("File Not Found!");
    }
}

}

Filename too long in Git for Windows

Steps to follow (Windows):

  1. Run Git Bash as administrator
  2. Run the following command:
git config --system core.longpaths true

Note: if step 2 does not work or gives any error, you can also try running this command:

git config --global core.longpaths true

Read more about git config here.

If input field is empty, disable submit button

Please try this

<!DOCTYPE html>
<html>
  <head>
    <title>Jquery</title>
    <meta charset="utf-8">       
    <script src='http://code.jquery.com/jquery-1.7.1.min.js'></script>
  </head>

  <body>

    <input type="text" id="message" value="" />
    <input type="button" id="sendButton" value="Send">

    <script>
    $(document).ready(function(){  

      var checkField;

      //checking the length of the value of message and assigning to a variable(checkField) on load
      checkField = $("input#message").val().length;  

      var enableDisableButton = function(){         
        if(checkField > 0){
          $('#sendButton').removeAttr("disabled");
        } 
        else {
          $('#sendButton').attr("disabled","disabled");
        }
      }        

      //calling enableDisableButton() function on load
      enableDisableButton();            

      $('input#message').keyup(function(){ 
        //checking the length of the value of message and assigning to the variable(checkField) on keyup
        checkField = $("input#message").val().length;
        //calling enableDisableButton() function on keyup
        enableDisableButton();
      });
    });
    </script>
  </body>
</html>

Python: Number of rows affected by cursor.execute("SELECT ...)

In my opinion, the simplest way to get the amount of selected rows is the following:

The cursor object returns a list with the results when using the fetch commands (fetchall(), fetchone(), fetchmany()). To get the selected rows just print the length of this list. But it just makes sense for fetchall(). ;-)

Example:

print len(cursor.fetchall) 

Moment.js - How to convert date string into date?

if you have a string of date, then you should try this.

const FORMAT = "YYYY ddd MMM DD HH:mm";

const theDate = moment("2019 Tue Apr 09 13:30", FORMAT);
// Tue Apr 09 2019 13:30:00 GMT+0300

const theDate1 = moment("2019 Tue Apr 09 13:30", FORMAT).format('LL')
// April 9, 2019

or try this :

const theDate1 = moment("2019 Tue Apr 09 13:30").format(FORMAT);

How to insert a picture into Excel at a specified cell position with VBA

If it's simply about inserting and resizing a picture, try the code below.

For the specific question you asked, the property TopLeftCell returns the range object related to the cell where the top left corner is parked. To place a new image at a specific place, I recommend creating an image at the "right" place and registering its top and left properties values of the dummy onto double variables.

Insert your Pic assigned to a variable to easily change its name. The Shape Object will have that same name as the Picture Object.

Sub Insert_Pic_From_File(PicPath as string, wsDestination as worksheet)
    Dim Pic As Picture, Shp as Shape
    Set Pic = wsDestination.Pictures.Insert(FilePath)
    Pic.Name = "myPicture"
    'Strongly recommend using a FileSystemObject.FileExists method to check if the path is good before executing the previous command
    Set Shp = wsDestination.Shapes("myPicture")
    With Shp
        .Height = 100
        .Width = 75
        .LockAspectRatio = msoTrue  'Put this later so that changing height doesn't change width and vice-versa)
        .Placement = 1
        .Top = 100
        .Left = 100
    End with
End Sub

Good luck!

Numeric for loop in Django templates

I've used a simple technique that works nicely for small cases with no special tags and no additional context. Sometimes this comes in handy

{% for i in '0123456789'|make_list %}
    {{ forloop.counter }}
{% endfor %}

Duplicate ID, tag null, or parent id with another fragment for com.google.android.gms.maps.MapFragment

I am a bit late to the party but Non of these answer helped me in my case. I was using Google map as SupportMapFragment and PlaceAutocompleteFragment both in my fragment. As all the answers pointed to the fact that the problem is with SupportMapFragment being the map to be recreated and redrawn.But after digging found out my problem was actually with PlaceAutocompleteFragment

So here is the working solution for those who are facing this problem because of SupportMapFragment and SupportMapFragment

 //Global SupportMapFragment mapFragment;
 mapFragment = (SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.mapFragment);
    FragmentManager fm = getChildFragmentManager();

    if (mapFragment == null) {
        mapFragment = SupportMapFragment.newInstance();
        fm.beginTransaction().replace(R.id.mapFragment, mapFragment).commit();
        fm.executePendingTransactions();
    }

    mapFragment.getMapAsync(this);

    //Global PlaceAutocompleteFragment autocompleteFragment;


    if (autocompleteFragment == null) {
        autocompleteFragment = (PlaceAutocompleteFragment) getActivity().getFragmentManager().findFragmentById(R.id.place_autoCompleteFragment);

    }

And in onDestroyView clear the SupportMapFragment and SupportMapFragment

@Override
public void onDestroyView() {
    super.onDestroyView();


    if (getActivity() != null) {
        Log.e("res","place dlted");
        android.app.FragmentManager fragmentManager = getActivity().getFragmentManager();
        android.app.FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        fragmentTransaction.remove(autocompleteFragment);
        fragmentTransaction.commit(); 
       //Use commitAllowingStateLoss() if getting exception 

        autocompleteFragment = null;
    }


}

C++ convert string to hexadecimal and vice versa

A string like "Hello World" to hex format: 48656C6C6F20576F726C64.

Ah, here you go:

#include <string>

std::string string_to_hex(const std::string& input)
{
    static const char hex_digits[] = "0123456789ABCDEF";

    std::string output;
    output.reserve(input.length() * 2);
    for (unsigned char c : input)
    {
        output.push_back(hex_digits[c >> 4]);
        output.push_back(hex_digits[c & 15]);
    }
    return output;
}

#include <stdexcept>

int hex_value(unsigned char hex_digit)
{
    static const signed char hex_values[256] = {
        -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
        -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
        -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
         0,  1,  2,  3,  4,  5,  6,  7,  8,  9, -1, -1, -1, -1, -1, -1,
        -1, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1,
        -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
        -1, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1,
        -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
        -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
        -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
        -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
        -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
        -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
        -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
        -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
        -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
    };
    int value = hex_values[hex_digit];
    if (value == -1) throw std::invalid_argument("invalid hex digit");
    return value;
}

std::string hex_to_string(const std::string& input)
{
    const auto len = input.length();
    if (len & 1) throw std::invalid_argument("odd length");

    std::string output;
    output.reserve(len / 2);
    for (auto it = input.begin(); it != input.end(); )
    {
        int hi = hex_value(*it++);
        int lo = hex_value(*it++);
        output.push_back(hi << 4 | lo);
    }
    return output;
}

(This assumes that a char has 8 bits, so it's not very portable, but you can take it from here.)

Could not find a version that satisfies the requirement <package>

I got this error while installing awscli on Windows 10 in anaconda (python 3.7). While troubleshooting, I went to the answer https://stackoverflow.com/a/49991357/6862405 and then to https://stackoverflow.com/a/54582701/6862405. Finally found that I need to install the libraries PyOpenSSL, cryptography, enum34, idna and ipaddress. After installing these (using simply pip install command), I was able to install awscli.

How to retrieve GET parameters from JavaScript

This one uses a regular expression and returns null if the parameter doesn't exist or doesn't have any value:

function getQuery(q) {
   return (window.location.search.match(new RegExp('[?&]' + q + '=([^&]+)')) || [, null])[1];
}

How to check a not-defined variable in JavaScript

I often use the simplest way:

var variable;
if (variable === undefined){
    console.log('Variable is undefined');
} else {
    console.log('Variable is defined');
}

EDIT:

Without initializing the variable, exception will be thrown "Uncaught ReferenceError: variable is not defined..."

ASP.NET Identity's default Password Hasher - How does it work and is it secure?

I understand the accepted answer, and have up-voted it but thought I'd dump my laymen's answer here...

Creating a hash

  1. The salt is randomly generated using the function Rfc2898DeriveBytes which generates a hash and a salt. Inputs to Rfc2898DeriveBytes are the password, the size of the salt to generate and the number of hashing iterations to perform. https://msdn.microsoft.com/en-us/library/h83s4e12(v=vs.110).aspx
  2. The salt and the hash are then mashed together(salt first followed by the hash) and encoded as a string (so the salt is encoded in the hash). This encoded hash (which contains the salt and hash) is then stored (typically) in the database against the user.

Checking a password against a hash

To check a password that a user inputs.

  1. The salt is extracted from the stored hashed password.
  2. The salt is used to hash the users input password using an overload of Rfc2898DeriveBytes which takes a salt instead of generating one. https://msdn.microsoft.com/en-us/library/yx129kfs(v=vs.110).aspx
  3. The stored hash and the test hash are then compared.

The Hash

Under the covers the hash is generated using the SHA1 hash function (https://en.wikipedia.org/wiki/SHA-1). This function is iteratively called 1000 times (In the default Identity implementation)

Why is this secure

  • Random salts means that an attacker can’t use a pre-generated table of hashs to try and break passwords. They would need to generate a hash table for every salt. (Assuming here that the hacker has also compromised your salt)
  • If 2 passwords are identical they will have different hashes. (meaning attackers can’t infer ‘common’ passwords)
  • Iteratively calling SHA1 1000 times means that the attacker also needs to do this. The idea being that unless they have time on a supercomputer they won’t have enough resource to brute force the password from the hash. It would massively slow down the time to generate a hash table for a given salt.

How to Update Date and Time of Raspberry Pi With out Internet

You will need to configure your Win7 PC as a Time Server, and then configure the RasPi to connect to it for NTP services.

Configure Win7 as authoritative time server. Configure RasPi time server lookup.

Android: upgrading DB version and adding new table

Handling database versions is very important part of application development. I assume that you already have class AppDbHelper extending SQLiteOpenHelper. When you extend it you will need to implement onCreate and onUpgrade method.

  1. When onCreate and onUpgrade methods called

    • onCreate called when app newly installed.
    • onUpgrade called when app updated.
  2. Organizing Database versions I manage versions in a class methods. Create implementation of interface Migration. E.g. For first version create MigrationV1 class, second version create MigrationV1ToV2 (these are my naming convention)


    public interface Migration {
        void run(SQLiteDatabase db);//create tables, alter tables
    }

Example migration:

public class MigrationV1ToV2 implements Migration{
      public void run(SQLiteDatabase db){
        //create new tables
        //alter existing tables(add column, add/remove constraint)
        //etc.
     }
   }
  1. Using Migration classes

onCreate: Since onCreate will be called when application freshly installed, we also need to execute all migrations(database version updates). So onCreate will looks like this:

public void onCreate(SQLiteDatabase db){
        Migration mV1=new MigrationV1();
       //put your first database schema in this class
        mV1.run(db);
        Migration mV1ToV2=new MigrationV1ToV2();
        mV1ToV2.run(db);
        //other migration if any
  }

onUpgrade: This method will be called when application is already installed and it is updated to new application version. If application contains any database changes then put all database changes in new Migration class and increment database version.

For example, lets say user has installed application which has database version 1, and now database version is updated to 2(all schema updates kept in MigrationV1ToV2). Now when application upgraded, we need to upgrade database by applying database schema changes in MigrationV1ToV2 like this:

public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    if (oldVersion < 2) {
        //means old version is 1
        Migration migration = new MigrationV1ToV2();
        migration.run(db);
    }
    if (oldVersion < 3) {
        //means old version is 2
    }
}

Note: All upgrades (mentioned in onUpgrade) in to database schema should be executed in onCreate

Scrollview vertical and horizontal in android

Playing with the code, you can put an HorizontalScrollView into an ScrollView. Thereby, you can have the two scroll method in the same view.

Source : http://androiddevblog.blogspot.com/2009/12/creating-two-dimensions-scroll-view.html

I hope this could help you.

Android + Pair devices via bluetooth programmatically

Edit: I have just explained logic to pair here. If anybody want to go with the complete code then see my another answer. I have answered here for logic only but I was not able to explain properly, So I have added another answer in the same thread.

Try this to do pairing:

If you are able to search the devices then this would be your next step

ArrayList<BluetoothDevice> arrayListBluetoothDevices = NEW ArrayList<BluetoothDevice>;

I am assuming that you have the list of Bluetooth devices added in the arrayListBluetoothDevices:

BluetoothDevice bdDevice;
bdDevice = arrayListBluetoothDevices.get(PASS_THE_POSITION_TO_GET_THE_BLUETOOTH_DEVICE);

Boolean isBonded = false;
try {
isBonded = createBond(bdDevice);
if(isBonded)
{
    Log.i("Log","Paired");
}
} catch (Exception e) 
{
    e.printStackTrace(); 
}

The createBond() method:

public boolean createBond(BluetoothDevice btDevice)  
    throws Exception  
    { 
        Class class1 = Class.forName("android.bluetooth.BluetoothDevice");
        Method createBondMethod = class1.getMethod("createBond");  
        Boolean returnValue = (Boolean) createBondMethod.invoke(btDevice);  
        return returnValue.booleanValue();  
    }  

Add this line into your Receiver in the ACTION_FOUND

if (device.getBondState() != BluetoothDevice.BOND_BONDED) {
                    mNewDevicesArrayAdapter.add(device.getName() + "\n" + device.getAddress());
                    arrayListBluetoothDevices.add(device);
                }

How to calculate distance between two locations using their longitude and latitude value

Here getting distance in miles (mi)

private double distance(double lat1, double lon1, double lat2, double lon2) {
    double theta = lon1 - lon2;
    double dist = Math.sin(deg2rad(lat1)) 
                    * Math.sin(deg2rad(lat2))
                    + Math.cos(deg2rad(lat1))
                    * Math.cos(deg2rad(lat2))
                    * Math.cos(deg2rad(theta));
    dist = Math.acos(dist);
    dist = rad2deg(dist);
    dist = dist * 60 * 1.1515;
    return (dist);
}

private double deg2rad(double deg) {
    return (deg * Math.PI / 180.0);
}

private double rad2deg(double rad) {
    return (rad * 180.0 / Math.PI);
}

Shell Scripting: Using a variable to define a path

Don't use spaces...

(Incorrect)

SPTH = '/home/Foo/Documents/Programs/ShellScripts/Butler'

(Correct)

SPTH='/home/Foo/Documents/Programs/ShellScripts/Butler'

How do I add a foreign key to an existing SQLite table?

You can try this:

ALTER TABLE [Child] ADD COLUMN column_name INTEGER REFERENCES parent_table_name(column_id);

How To Inject AuthenticationManager using Java Configuration in a Custom Filter

Override method authenticationManagerBean in WebSecurityConfigurerAdapter to expose the AuthenticationManager built using configure(AuthenticationManagerBuilder) as a Spring bean:

For example:

   @Bean(name = BeanIds.AUTHENTICATION_MANAGER)
   @Override
   public AuthenticationManager authenticationManagerBean() throws Exception {
       return super.authenticationManagerBean();
   }

Reload child component when variables on parent component changes. Angular2

update of @Vladimir Tolstikov's answer

Create a Child Component that use ngOnChanges.

ChildComponent.ts::

import { Component, OnChanges, Input } from '@angular/core';
import { ActivatedRoute } from '@angular/router';

@Component({
  selector: 'child',
  templateUrl: 'child.component.html',
})

export class ChildComponent implements OnChanges {
  @Input() child_id;

  constructor(private route: ActivatedRoute) { }

  ngOnChanges() {
    // create header using child_id
    console.log(this.child_id);
  }
}

now use it in MasterComponent's template and pass data to ChildComponent like:

<child [child_id]="child_id"></child>

Multiple left joins on multiple tables in one query

The JOIN statements are also part of the FROM clause, more formally a join_type is used to combine two from_item's into one from_item, multiple one of which can then form a comma-separated list after the FROM. See http://www.postgresql.org/docs/9.1/static/sql-select.html .

So the direct solution to your problem is:

SELECT something
FROM
    master as parent LEFT JOIN second as parentdata
        ON parent.secondary_id = parentdata.id,
    master as child LEFT JOIN second as childdata
        ON child.secondary_id = childdata.id
WHERE parent.id = child.parent_id AND parent.parent_id = 'rootID'

A better option would be to only use JOIN's, as it has already been suggested.

Thymeleaf: how to use conditionals to dynamically add/remove a CSS class

If you just want to append a class in case of an error you can use th:errorclass="my-error-class" mentionned in the doc.

<input type="text" th:field="*{datePlanted}" class="small" th:errorclass="fieldError" />

Applied to a form field tag (input, select, textarea…), it will read the name of the field to be examined from any existing name or th:field attributes in the same tag, and then append the specified CSS class to the tag if such field has any associated errors

jQuery - Dynamically Create Button and Attach Event Handler

Calling .html() serializes the element to a string, so all event handlers and other associated data is lost. Here's how I'd do it:

$("#myButton").click(function ()
{
    var test = $('<button/>',
    {
        text: 'Test',
        click: function () { alert('hi'); }
    });

    var parent = $('<tr><td></td></tr>').children().append(test).end();

    $("#addNodeTable tr:last").before(parent);
});

Or,

$("#myButton").click(function ()
{    
    var test = $('<button/>',
    {
        text: 'Test',
        click: function () { alert('hi'); }
    }).wrap('<tr><td></td></tr>').closest('tr');

    $("#addNodeTable tr:last").before(test);
});

If you don't like passing a map of properties to $(), you can instead use

$('<button/>')
    .text('Test')
    .click(function () { alert('hi'); });

// or

$('<button>Test</button>').click(function () { alert('hi'); });

How to use BufferedReader in Java

Try this to read a file:

BufferedReader reader = null;

try {
    File file = new File("sample-file.dat");
    reader = new BufferedReader(new FileReader(file));

    String line;
    while ((line = reader.readLine()) != null) {
        System.out.println(line);
    }

} catch (IOException e) {
    e.printStackTrace();
} finally {
    try {
        reader.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

How do I set browser width and height in Selenium WebDriver?

Try something like this:

IWebDriver _driver = new FirefoxDriver();
_driver.Manage().Window.Position = new Point(0, 0);
_driver.Manage().Window.Size = new Size(1024, 768);

Not sure if it'll resize after being launched though, so maybe it's not what you want

Docker compose, running containers in net:host

Maybe I am answering very late. But I was also having a problem configuring host network in docker compose. Then I read the documentation thoroughly and made the changes and it worked. Please note this configuration is for docker-compose version "3.7". Here einwohner_net and elk_net_net are my user-defined networks required for my application. I am using host net to get some system metrics.

Link To Documentation https://docs.docker.com/compose/compose-file/#host-or-none

version: '3.7'
services:
  app:
    image: ramansharma/einwohnertomcat:v0.0.1
    deploy:
      replicas: 1
      ports:
       - '8080:8080'
    volumes:
     - type: bind
       source: /proc
       target: /hostfs/proc
       read_only: true
     - type: bind
       source: /sys/fs/cgroup
       target: /hostfs/sys/fs/cgroup
       read_only: true
     - type: bind
       source: /
       target: /hostfs
       read_only: true
    networks:
     hostnet: {}
    networks:
     - einwohner_net
     - elk_elk_net
networks:
 einwohner_net:
 elk_elk_net:
   external: true
 hostnet:
   external: true
   name: host

How can I one hot encode in Python?

Approach 1: You can use pandas' pd.get_dummies.

Example 1:

import pandas as pd
s = pd.Series(list('abca'))
pd.get_dummies(s)
Out[]: 
     a    b    c
0  1.0  0.0  0.0
1  0.0  1.0  0.0
2  0.0  0.0  1.0
3  1.0  0.0  0.0

Example 2:

The following will transform a given column into one hot. Use prefix to have multiple dummies.

import pandas as pd
        
df = pd.DataFrame({
          'A':['a','b','a'],
          'B':['b','a','c']
        })
df
Out[]: 
   A  B
0  a  b
1  b  a
2  a  c

# Get one hot encoding of columns B
one_hot = pd.get_dummies(df['B'])
# Drop column B as it is now encoded
df = df.drop('B',axis = 1)
# Join the encoded df
df = df.join(one_hot)
df  
Out[]: 
       A  a  b  c
    0  a  0  1  0
    1  b  1  0  0
    2  a  0  0  1

Approach 2: Use Scikit-learn

Using a OneHotEncoder has the advantage of being able to fit on some training data and then transform on some other data using the same instance. We also have handle_unknown to further control what the encoder does with unseen data.

Given a dataset with three features and four samples, we let the encoder find the maximum value per feature and transform the data to a binary one-hot encoding.

>>> from sklearn.preprocessing import OneHotEncoder
>>> enc = OneHotEncoder()
>>> enc.fit([[0, 0, 3], [1, 1, 0], [0, 2, 1], [1, 0, 2]])   
OneHotEncoder(categorical_features='all', dtype=<class 'numpy.float64'>,
   handle_unknown='error', n_values='auto', sparse=True)
>>> enc.n_values_
array([2, 3, 4])
>>> enc.feature_indices_
array([0, 2, 5, 9], dtype=int32)
>>> enc.transform([[0, 1, 1]]).toarray()
array([[ 1.,  0.,  0.,  1.,  0.,  0.,  1.,  0.,  0.]])

Here is the link for this example: http://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.OneHotEncoder.html

Deserialize a json string to an object in python

If you want to save lines of code and leave the most flexible solution, we can deserialize the json string to a dynamic object:

p = lambda:None
p.__dict__ = json.loads('{"action": "print", "method": "onData", "data": "Madan Mohan"}')


>>>> p.action
output: u'print'

>>>> p.method
output: u'onData'

How can I completely uninstall nodejs, npm and node in Ubuntu

Try the following commands:

$ sudo apt-get install nodejs
$ sudo apt-get install aptitude
$ sudo aptitude install npm

Convert array into csv

I'm using the following function for that; it's an adaptation from one of the man entries in the fputscsv comments. And you'll probably want to flatten that array; not sure what happens if you pass in a multi-dimensional one.

/**
  * Formats a line (passed as a fields  array) as CSV and returns the CSV as a string.
  * Adapted from http://us3.php.net/manual/en/function.fputcsv.php#87120
  */
function arrayToCsv( array &$fields, $delimiter = ';', $enclosure = '"', $encloseAll = false, $nullToMysqlNull = false ) {
    $delimiter_esc = preg_quote($delimiter, '/');
    $enclosure_esc = preg_quote($enclosure, '/');

    $output = array();
    foreach ( $fields as $field ) {
        if ($field === null && $nullToMysqlNull) {
            $output[] = 'NULL';
            continue;
        }

        // Enclose fields containing $delimiter, $enclosure or whitespace
        if ( $encloseAll || preg_match( "/(?:${delimiter_esc}|${enclosure_esc}|\s)/", $field ) ) {
            $output[] = $enclosure . str_replace($enclosure, $enclosure . $enclosure, $field) . $enclosure;
        }
        else {
            $output[] = $field;
        }
    }

    return implode( $delimiter, $output );
}

How to display activity indicator in middle of the iphone screen?

For Swift 3 you can use the following:

 func setupSpinner(){
    spinner = UIActivityIndicatorView(frame: CGRect(x: 0, y: 0, width: 40, height:40))
    spinner.color = UIColor(Colors.Accent)
    self.spinner.center = CGPoint(x:UIScreen.main.bounds.size.width / 2, y:UIScreen.main.bounds.size.height / 2)
    self.view.addSubview(spinner)
    spinner.hidesWhenStopped = true
}

How to determine whether a given Linux is 32 bit or 64 bit?

That system is 32bit. iX86 in uname means it is a 32-bit architecture. If it was 64 bit, it would return

Linux mars 2.6.9-67.0.15.ELsmp #1 SMP Tue Apr 22 13:50:33 EDT 2008 x86_64 i686 x86_64 x86_64 GNU/Linux

How to make an embedded Youtube video automatically start playing?

Add &autoplay=1 to your syntax, like this

<iframe title="YouTube video player" width="480" height="390" src="http://www.youtube.com/embed/zGPuazETKkI&amp;autoplay=1" frameborder="0" allowfullscreen></iframe>

What is the Regular Expression For "Not Whitespace and Not a hyphen"

It can be done much easier:

\S which equals [^ \t\r\n\v\f]

How do you grep a file and get the next 5 lines

Here is a sed solution:

sed '/19:55/{
N
N
N
N
N
s/\n/ /g
}' file.txt

ActiveX component can't create object

I know this is an old thread, but has anyone checked if their Antivirus is blocking Win32API and Scripting on their systems? I have CylanceProtect installed on my office system and i found the same issues occurring as listed by others. This can be confirmed if you check the Windows Logs in Event Viewer.

jquery: how to get the value of id attribute?

You can also try this way

<option id="opt7" class='select_continent' data-value='7'>Antarctica</option>

jquery

$('.select_continent').click(function () {
alert($(this).data('value'));
});

Good luck !!!!

java.lang.ClassNotFoundException: com.mysql.jdbc.Driver in Eclipse

Trivial as it may seem in my case netbeans version maven project 7.2.1 was different. There is a folder in the project called dependencies. Right click and then it brings up a popup window where you can search for packages. In the query area put

mysql-connector

It will bring up the matches (it seems it does this against some repository). Double click then install.

How to sort an array in descending order in Ruby

It's always enlightening to do a benchmark on the various suggested answers. Here's what I found out:

#!/usr/bin/ruby

require 'benchmark'

ary = []
1000.times { 
  ary << {:bar => rand(1000)} 
}

n = 500
Benchmark.bm(20) do |x|
  x.report("sort")               { n.times { ary.sort{ |a,b| b[:bar] <=> a[:bar] } } }
  x.report("sort reverse")       { n.times { ary.sort{ |a,b| a[:bar] <=> b[:bar] }.reverse } }
  x.report("sort_by -a[:bar]")   { n.times { ary.sort_by{ |a| -a[:bar] } } }
  x.report("sort_by a[:bar]*-1") { n.times { ary.sort_by{ |a| a[:bar]*-1 } } }
  x.report("sort_by.reverse!")   { n.times { ary.sort_by{ |a| a[:bar] }.reverse } }
end

                          user     system      total        real
sort                  3.960000   0.010000   3.970000 (  3.990886)
sort reverse          4.040000   0.000000   4.040000 (  4.038849)
sort_by -a[:bar]      0.690000   0.000000   0.690000 (  0.692080)
sort_by a[:bar]*-1    0.700000   0.000000   0.700000 (  0.699735)
sort_by.reverse!      0.650000   0.000000   0.650000 (  0.654447)

I think it's interesting that @Pablo's sort_by{...}.reverse! is fastest. Before running the test I thought it would be slower than "-a[:bar]" but negating the value turns out to take longer than it does to reverse the entire array in one pass. It's not much of a difference, but every little speed-up helps.


Please note that these results are different in Ruby 1.9

Here are results for Ruby 1.9.3p194 (2012-04-20 revision 35410) [x86_64-darwin10.8.0]:

                           user     system      total        real
sort                   1.340000   0.010000   1.350000 (  1.346331)
sort reverse           1.300000   0.000000   1.300000 (  1.310446)
sort_by -a[:bar]       0.430000   0.000000   0.430000 (  0.429606)
sort_by a[:bar]*-1     0.420000   0.000000   0.420000 (  0.414383)
sort_by.reverse!       0.400000   0.000000   0.400000 (  0.401275)

These are on an old MacBook Pro. Newer, or faster machines, will have lower values, but the relative differences will remain.


Here's a bit updated version on newer hardware and the 2.1.1 version of Ruby:

#!/usr/bin/ruby

require 'benchmark'

puts "Running Ruby #{RUBY_VERSION}"

ary = []
1000.times {
  ary << {:bar => rand(1000)}
}

n = 500

puts "n=#{n}"
Benchmark.bm(20) do |x|
  x.report("sort")               { n.times { ary.dup.sort{ |a,b| b[:bar] <=> a[:bar] } } }
  x.report("sort reverse")       { n.times { ary.dup.sort{ |a,b| a[:bar] <=> b[:bar] }.reverse } }
  x.report("sort_by -a[:bar]")   { n.times { ary.dup.sort_by{ |a| -a[:bar] } } }
  x.report("sort_by a[:bar]*-1") { n.times { ary.dup.sort_by{ |a| a[:bar]*-1 } } }
  x.report("sort_by.reverse")    { n.times { ary.dup.sort_by{ |a| a[:bar] }.reverse } }
  x.report("sort_by.reverse!")   { n.times { ary.dup.sort_by{ |a| a[:bar] }.reverse! } }
end

# >> Running Ruby 2.1.1
# >> n=500
# >>                            user     system      total        real
# >> sort                   0.670000   0.000000   0.670000 (  0.667754)
# >> sort reverse           0.650000   0.000000   0.650000 (  0.655582)
# >> sort_by -a[:bar]       0.260000   0.010000   0.270000 (  0.255919)
# >> sort_by a[:bar]*-1     0.250000   0.000000   0.250000 (  0.258924)
# >> sort_by.reverse        0.250000   0.000000   0.250000 (  0.245179)
# >> sort_by.reverse!       0.240000   0.000000   0.240000 (  0.242340)

New results running the above code using Ruby 2.2.1 on a more recent Macbook Pro. Again, the exact numbers aren't important, it's their relationships:

Running Ruby 2.2.1
n=500
                           user     system      total        real
sort                   0.650000   0.000000   0.650000 (  0.653191)
sort reverse           0.650000   0.000000   0.650000 (  0.648761)
sort_by -a[:bar]       0.240000   0.010000   0.250000 (  0.245193)
sort_by a[:bar]*-1     0.240000   0.000000   0.240000 (  0.240541)
sort_by.reverse        0.230000   0.000000   0.230000 (  0.228571)
sort_by.reverse!       0.230000   0.000000   0.230000 (  0.230040)

Updated for Ruby 2.7.1 on a Mid-2015 MacBook Pro:

Running Ruby 2.7.1
n=500     
                           user     system      total        real
sort                   0.494707   0.003662   0.498369 (  0.501064)
sort reverse           0.480181   0.005186   0.485367 (  0.487972)
sort_by -a[:bar]       0.121521   0.003781   0.125302 (  0.126557)
sort_by a[:bar]*-1     0.115097   0.003931   0.119028 (  0.122991)
sort_by.reverse        0.110459   0.003414   0.113873 (  0.114443)
sort_by.reverse!       0.108997   0.001631   0.110628 (  0.111532)

...the reverse method doesn't actually return a reversed array - it returns an enumerator that just starts at the end and works backwards.

The source for Array#reverse is:

               static VALUE
rb_ary_reverse_m(VALUE ary)
{
    long len = RARRAY_LEN(ary);
    VALUE dup = rb_ary_new2(len);

    if (len > 0) {
        const VALUE *p1 = RARRAY_CONST_PTR_TRANSIENT(ary);
        VALUE *p2 = (VALUE *)RARRAY_CONST_PTR_TRANSIENT(dup) + len - 1;
        do *p2-- = *p1++; while (--len > 0);
    }
    ARY_SET_LEN(dup, RARRAY_LEN(ary));
    return dup;
}

do *p2-- = *p1++; while (--len > 0); is copying the pointers to the elements in reverse order if I remember my C correctly, so the array is reversed.

JavaScript - Get minutes between two dates

You can do as follows:

  1. Get difference of dates(Difference will be in milliseconds)
  2. Convert milliseconds into minutes i-e ms/1000/60

The Code:

let dateOne = new Date("2020-07-10");
let dateTwo = new Date("2020-07-11");

let msDifference =  dateTwo - dateOne;
let minutes = Math.floor(msDifference/1000/60);
console.log("Minutes between two dates =",minutes);

Setting Camera Parameters in OpenCV/Python

To avoid using integer values to identify the VideoCapture properties, one can use, e.g., cv2.cv.CV_CAP_PROP_FPS in OpenCV 2.4 and cv2.CAP_PROP_FPS in OpenCV 3.0. (See also Stefan's comment below.)

Here a utility function that works for both OpenCV 2.4 and 3.0:

# returns OpenCV VideoCapture property id given, e.g., "FPS"
def capPropId(prop):
  return getattr(cv2 if OPCV3 else cv2.cv,
    ("" if OPCV3 else "CV_") + "CAP_PROP_" + prop)

OPCV3 is set earlier in my utilities code like this:

from pkg_resources import parse_version
OPCV3 = parse_version(cv2.__version__) >= parse_version('3')

Pass array to mvc Action via AJAX

If you are migrating to ASP.NET Core MVC from .Net Framework MVC like I was, things have changed slightly. The ajax call must be on the raw object using stringify so rather than passing data of { vals: arrayOfValues } it should be JSON.stringify(arrayOfValues) as follows:

$.ajax({
   url: 'controller/myaction',
   data: JSON.stringify(arrayOfValues),
   success: function(data) { /* Whatever */ }
});

The other change that has been made in ASP.NET Core is to prevent cross-site request forgery so for calls to an MVC action from an ajax method the [FromBody] atribute must be applied to the action parameter as follows:

public ActionResult MyAction([FromBody] IEnumerable<int> arrayOfValues )

ImportError: DLL load failed: %1 is not a valid Win32 application. But the DLL's are there

You can install opencv from official or unofficial sites.

Refer to this question and this issue if you are using Anaconda.

How to lock orientation of one view controller to portrait mode only in Swift

As of iOS 10 and 11, iPad supports Slide Over and Split View. To enable an app in Slide Over and Split View, Requires full screen must be unchecked. That means the accepted answer cannot be used if the app wants to support Slide Over and Split View. See more from Apple's Adopting Multitasking Enhancements on iPad here.

I have a solution that allows (1) unchecking Requires full screen, (2) just one function to be implemented in appDelegate (especially if you don't want to / can't modify the target view controllers), and (3) avoid recursive calls. No need of helper class nor extensions.

appDelegate.swift (Swift 4)

func application(_ application: UIApplication,
                 supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask {
    // Search for the visible view controller
    var vc = window?.rootViewController
    // Dig through tab bar and navigation, regardless their order 
    while (vc is UITabBarController) || (vc is UINavigationController) {
        if let c = vc as? UINavigationController {
            vc = c.topViewController
        } else if let c = vc as? UITabBarController {
            vc = c.selectedViewController
        }
    }
    // Look for model view controller
    while (vc?.presentedViewController) != nil {
        vc = vc!.presentedViewController
    }
    print("vc = " + (vc != nil ? String(describing: type(of: vc!)) : "nil"))
    // Final check if it's our target class.  Also make sure it isn't exiting.
    // Otherwise, system will mistakenly rotate the presentingViewController.
    if (vc is TargetViewController) && !(vc!.isBeingDismissed) {
        return [.portrait]
    }
    return [.all]
}

Edit

@bmjohns pointed out that this function is not called on iPad. I verified and yes it was not called. So, I did a bit more testing and found out some facts:

  1. I unchecked Requires full screen because I want to enable Slide Over and Slide View on iPad. That requires the app to support all 4 orientation for iPad, in Info.plist: Supported interface orientations (iPad).

My app works same way as Facebook: on iPhone, most of the time it is locked to portrait. When viewing image in full screen, allows users to rotate landscape for better view. On iPad, users can rotate to any orientation in any view controllers. So, the app looks nice when iPad is stand on Smart Cover (landscape left).

  1. For iPad to call application(_:supportedInterfaceOrientationsFor), in Info.plist, only keep portrait for iPad. The app will lose Slide Over + Split View ability. But you can lock or unlock the orientation for any view controller, in just one place and no need to modify ViewController class.

  2. Finally, this function get called on view controller's life cycle, when view is displayed/removed. If your app need to lock/unlock/change orientation in other time, it might not work

Is it valid to have a html form inside another html form?

HTML 4.x & HTML5 disallow nested forms, but HTML5 will allow a workaround with "form" attribute ("form owner").

As for HTML 4.x you can:

  1. Use an extra form(s) with only hidden fields & JavaScript to set its input's and submit the form.
  2. Use CSS to line up several HTML form to look like a single entity - but I think that's too hard.

Install Node.js on Ubuntu

npm is automatically installed with Node.js in the latest version of Node.js. What do you see when you type node --version and npm --version in the terminal?

You can upgrade npm using npm itself as well:

[sudo] npm install -g npm

Java how to replace 2 or more spaces with single space in string and delete leading and trailing spaces

I know replaceAll method is much easier but I wanted to post this as well.

public static String removeExtraSpace(String input) {
    input= input.trim();
    ArrayList <String> x= new ArrayList<>(Arrays.asList(input.split("")));
    for(int i=0; i<x.size()-1;i++) {
        if(x.get(i).equals(" ") && x.get(i+1).equals(" ")) { 
            x.remove(i); 
            i--; 
        }
    }
    String word="";
    for(String each: x) 
        word+=each;
    return word;
}

Converting an int or String to a char array on Arduino

None of that stuff worked. Here's a much simpler way .. the label str is the pointer to what IS an array...

String str = String(yourNumber, DEC); // Obviously .. get your int or byte into the string

str = str + '\r' + '\n'; // Add the required carriage return, optional line feed

byte str_len = str.length();

// Get the length of the whole lot .. C will kindly
// place a null at the end of the string which makes
// it by default an array[].
// The [0] element is the highest digit... so we
// have a separate place counter for the array...

byte arrayPointer = 0;

while (str_len)
{
    // I was outputting the digits to the TX buffer

    if ((UCSR0A & (1<<UDRE0))) // Is the TX buffer empty?
    {
        UDR0 = str[arrayPointer];
        --str_len;
        ++arrayPointer;
    }
}

how to generate a unique token which expires after 24 hours?

There are two possible approaches; either you create a unique value and store somewhere along with the creation time, for example in a database, or you put the creation time inside the token so that you can decode it later and see when it was created.

To create a unique token:

string token = Convert.ToBase64String(Guid.NewGuid().ToByteArray());

Basic example of creating a unique token containing a time stamp:

byte[] time = BitConverter.GetBytes(DateTime.UtcNow.ToBinary());
byte[] key = Guid.NewGuid().ToByteArray();
string token = Convert.ToBase64String(time.Concat(key).ToArray());

To decode the token to get the creation time:

byte[] data = Convert.FromBase64String(token);
DateTime when = DateTime.FromBinary(BitConverter.ToInt64(data, 0));
if (when < DateTime.UtcNow.AddHours(-24)) {
  // too old
}

Note: If you need the token with the time stamp to be secure, you need to encrypt it. Otherwise a user could figure out what it contains and create a false token.

Is there a math nCr function in python?

The following program calculates nCr in an efficient manner (compared to calculating factorials etc.)

import operator as op
from functools import reduce

def ncr(n, r):
    r = min(r, n-r)
    numer = reduce(op.mul, range(n, n-r, -1), 1)
    denom = reduce(op.mul, range(1, r+1), 1)
    return numer // denom  # or / in Python 2

As of Python 3.8, binomial coefficients are available in the standard library as math.comb:

>>> from math import comb
>>> comb(10,3)
120

detect back button click in browser

I'm assuming that you're trying to deal with Ajax navigation and not trying to prevent your users from using the back button, which violates just about every tenet of UI development ever.

Here's some possible solutions: JQuery History Salajax A Better Ajax Back Button

Clearing coverage highlighting in Eclipse

If you would like to remove active session/project/folder then you can follow

Click the "Remove Active Session" button in the toolbar of the "Coverage" view.

Java: set timeout on a certain block of code?

I can suggest two options.

  1. Within the method, assuming it is looping and not waiting for an external event, add a local field and test the time each time around the loop.

    void method() {
        long endTimeMillis = System.currentTimeMillis() + 10000;
        while (true) {
            // method logic
            if (System.currentTimeMillis() > endTimeMillis) {
                // do some clean-up
                return;
            }
        }
    }
    
  2. Run the method in a thread, and have the caller count to 10 seconds.

    Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                method();
            }
    });
    thread.start();
    long endTimeMillis = System.currentTimeMillis() + 10000;
    while (thread.isAlive()) {
        if (System.currentTimeMillis() > endTimeMillis) {
            // set an error flag
            break;
        }
        try {
            Thread.sleep(500);
        }
        catch (InterruptedException t) {}
    }
    

The drawback to this approach is that method() cannot return a value directly, it must update an instance field to return its value.

How to prevent downloading images and video files from my website?

If you are using PHP, the best way is to control it the .htaccess, you need to put your files, images and videos under consideration in a separate folder/directory, and create a new .htaccess file in this directory with the below:

RewriteEngine On
RewriteCond %{REQUEST_URI} \.(mp4|mp3|avi)$ [NC]
RewriteCond %{HTTP_REFERER} !^http://sample.com/.*$ [NC]
RewriteRule ^.* - [F,L]

The first line %{REQUEST_URI} will prevent getting the file through the web browser or through curl. The second line %{HTTP_REFERER} will prevent accessing the image/video using HTML tags <img> or <video> from any website except the exception ! you provide instead of http://sample.com/ which usually should be your website itself.

You can also have a look at my question and the accepted answer here for more tricks on the browser side.

Disable browser 'Save Password' functionality

I had been struggling with this problem a while, with a unique twist to the problem. Privileged users couldn't have the saved passwords work for them, but normal users needed it. This meant privileged users had to log in twice, the second time enforcing no saved passwords.

With this requirement, the standard autocomplete="off" method doesn't work across all browsers, because the password may have been saved from the first login. A colleague found a solution to replace the password field when it was focused with a new password field, and then focus on the new password field (then hook up the same event handler). This worked (except it caused an infinite loop in IE6). Maybe there was a way around that, but it was causing me a migraine.

Finally, I tried to just have the username and password outside of the form. To my surprise, this worked! It worked on IE6, and current versions of Firefox and Chrome on Linux. I haven't tested it further, but I suspect it works in most if not all browsers (but it wouldn't surprise me if there was a browser out there that didn't care if there was no form).

Here is some sample code, along with some jQuery to get it to work:

<input type="text" id="username" name="username"/>
<input type="password" id="password" name="password"/>

<form id="theForm" action="/your/login" method="post">
  <input type="hidden" id="hiddenUsername" name="username"/>
  <input type="hidden" id="hiddenPassword" name="password"/>
  <input type="submit" value="Login"/>
</form>

<script type="text/javascript" language="JavaScript">
  $("#theForm").submit(function() {
    $("#hiddenUsername").val($("#username").val());
    $("#hiddenPassword").val($("#password").val());
  });
  $("#username,#password").keypress(function(e) {
    if (e.which == 13) {
      $("#theForm").submit();
    }
  });
</script>

Getting results between two dates in PostgreSQL

No offense but to check for performance of sql I executed some of the above mentioned solutiona pgsql.

Let me share you Statistics of top 3 solution approaches that I come across.

1) Took : 1.58 MS Avg

2) Took : 2.87 MS Avg

3) Took : 3.95 MS Avg

Now try this :

 SELECT * FROM table WHERE DATE_TRUNC('day', date ) >= Start Date AND DATE_TRUNC('day', date ) <= End Date

Now this solution took : 1.61 Avg.

And best solution is 1st that suggested by marco-mariani

Finding last occurrence of substring in string, replacing that

I would use a regex:

import re
new_list = [re.sub(r"\.(?=[^.]*$)", r". - ", s) for s in old_list]

DataAdapter.Fill(Dataset)

DataSet ds = new DataSet();

using (OleDbConnection connection = new OleDbConnection(connectionString))
using (OleDbCommand command = new OleDbCommand(query, connection))
using (OleDbDataAdapter adapter = new OleDbDataAdapter(command))
{
    adapter.Fill(ds);
}

return ds;

How can I programmatically freeze the top row of an Excel worksheet in Excel 2007 VBA?

Rows("2:2").Select
ActiveWindow.FreezePanes = True

This is the easiest way to freeze the top row. The rule for FreezePanes is it will freeze the upper left corner from the cell you selected. For example, if you highlight C10, it will freeze between columns B and C, rows 9 and 10. So when you highlight Row 2, it actually freeze between Rows 1 and 2 which is the top row.

Also, the .SplitColumn or .SplitRow will split your window once you unfreeze it which is not the way I like.

Map over object preserving keys

I think you want a mapValues function (to map a function over the values of an object), which is easy enough to implement yourself:

mapValues = function(obj, f) {
  var k, result, v;
  result = {};
  for (k in obj) {
    v = obj[k];
    result[k] = f(v);
  }
  return result;
};

.do extension in web pages?

Using apache's rewrite_module can change your script extensions. Give this thread a good read.

MySQL the right syntax to use near '' at line 1 error

the problem is because you have got the query over multiple lines using the " " that PHP is actually sending all the white spaces in to MySQL which is causing it to error out.

Either put it on one line or append on each line :o)

Sqlyog must be trimming white spaces on each line which explains why its working.

Example:

$qr2="INSERT INTO wp_bp_activity
      (
            user_id,
 (this stuff)component,
     (is)      `type`,
    (a)        `action`,
  (problem)  content,
             primary_link,
             item_id,....

String Resource new line /n not possible?

I just faced this issue. didn't work on TextView with constraint parameters. Adding android:lines="2" seems to fix this.

What SOAP client libraries exist for Python, and where is the documentation for them?

suds is pretty good. I tried SOAPpy but didn't get it to work in quite the way I needed whereas suds worked pretty much straight away.

Best way to store chat messages in a database?

You could create a database for x conversations which contains all messages of these conversations. This would allow you to add a new Database (or server) each time x exceeds. X is the number conversations your infrastructure supports (depending on your hardware,...).

The problem is still, that there may be big conversations (with a lot of messages) on the same database. e.g. you have database A and database B an each stores e.g. 1000 conversations. It my be possible that there are far more "big" conversations on server A than on server B (since this is user created content). You could add a "master" database that contains a lookup, on which database/server the single conversations can be found (or you have a schema to assign a database from hash/modulo or something).

Maybe you can find real world architectures that deal with the same problems (you may not be the first one), and that have already been solved.

Statistics: combinations in Python

This function is very optimized.

def nCk(n,k):
    m=0
    if k==0:
        m=1
    if k==1:
        m=n
    if k>=2:
        num,dem,op1,op2=1,1,k,n
        while(op1>=1):
            num*=op2
            dem*=op1
            op1-=1
            op2-=1
        m=num//dem
    return m

How to convert a String to JsonObject using gson library

String emailData = {"to": "[email protected]","subject":"User details","body": "The user has completed his training"
}

// Java model class
public class EmailData {
    public String to;
    public String subject;
    public String body;
}

//Final Data
Gson gson = new Gson();  
EmailData emaildata = gson.fromJson(emailData, EmailData.class);

Eclipse JUnit - possible causes of seeing "initializationError" in Eclipse window

If you're using the xtend language (or some other JVM lang with type inference) and haven't explicitly defined the return type then it may be set to a non-void type because of the last expression, which will make JUnit fail.

Swift 3 URLSession.shared() Ambiguous reference to member 'dataTask(with:completionHandler:) error (bug)

In swift 3 the compiler is confused by the function signature. Specifying it will clear the error. Also convert the url string to type URL. The following code worked for me.

   let urlString = "http://bla.com?batchSize="
   let pathURL = URL(string: urlString)!
   var urlRequest = URLRequest(url:pathURL)

    let session = URLSession.shared
    let dataTask = session.dataTask(with: urlRequest as URLRequest) { (data,response,error) in

Easy way to dismiss keyboard?

To be honest, I'm not crazy about any of the solutions proposed here. I did find a nice way to use a TapGestureRecognizer that I think gets to the heart of your problem: When you click on anything besides the keyboard, dismiss the keyboard.

  1. In viewDidLoad, register to receive keyboard notifications and create a UITapGestureRecognizer:

    NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
    
    [nc addObserver:self selector:@selector(keyboardWillShow:) name:
    UIKeyboardWillShowNotification object:nil];
    
    [nc addObserver:self selector:@selector(keyboardWillHide:) name:
    UIKeyboardWillHideNotification object:nil];
    
    tapRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self
    action:@selector(didTapAnywhere:)];
    
  2. Add the keyboard show/hide responders. There you add and remove the TapGestureRecognizer to the UIView that should dismiss the keyboard when tapped. Note: You do not have to add it to all of the sub-views or controls.

    -(void) keyboardWillShow:(NSNotification *) note {
        [self.view addGestureRecognizer:tapRecognizer];
    }
    
    -(void) keyboardWillHide:(NSNotification *) note
    {
        [self.view removeGestureRecognizer:tapRecognizer];
    }
    
  3. The TapGestureRecognizer will call your function when it gets a tap and you can dismiss the keyboard like this:

    -(void)didTapAnywhere: (UITapGestureRecognizer*) recognizer {    
        [textField resignFirstResponder];
    }
    

The nice thing about this solution is that it only filters for Taps, not swipes. So if you have scrolling content above the keyboard, swipes will still scroll and leave the keyboard displayed. By removing the gesture recognizer after the keyboard is gone, future taps on your view get handled normally.

"You tried to execute a query that does not include the specified aggregate function"

The error is because fName is included in the SELECT list, but is not included in a GROUP BY clause and is not part of an aggregate function (Count(), Min(), Max(), Sum(), etc.)

You can fix that problem by including fName in a GROUP BY. But then you will face the same issue with surname. So put both in the GROUP BY:

SELECT
    fName,
    surname,
    Count(*) AS num_rows
FROM
    author
    INNER JOIN book
    ON author.aID = book.authorID;
GROUP BY
    fName,
    surname

Note I used Count(*) where you wanted SUM(orders.quantity). However, orders isn't included in the FROM section of your query, so you must include it before you can Sum() one of its fields.

If you have Access available, build the query in the query designer. It can help you understand what features are possible and apply the correct Access SQL syntax.

Process all arguments except the first one (in a bash script)

Working in bash 4 or higher version:

#!/bin/bash
echo "$0";         #"bash"
bash --version;    #"GNU bash, version 5.0.3(1)-release (x86_64-pc-linux-gnu)"

In function:

echo $@;              #"p1" "p2" "p3" "p4" "p5"
echo ${@: 0};  #"bash" "p1" "p2" "p3" "p4" "p5"
echo ${@: 1};         #"p1" "p2" "p3" "p4" "p5"
echo ${@: 2};              #"p2" "p3" "p4" "p5"
echo ${@: 2:1};            #"p2"
echo ${@: 2:2};            #"p2" "p3"
echo ${@: -2};                       #"p4" "p5"
echo ${@: -2:1};                     #"p4"

Notice the space between ':' and '-', otherwise it means different:

${var:-word} If var is null or unset,
word is substituted for var. The value of var does not change.

${var:+word} If var is set,
word is substituted for var. The value of var does not change.

Which is described in:Unix / Linux - Shell Substitution

var self = this?

Just adding to this that in ES6 because of arrow functions you shouldn't need to do this because they capture the this value.

How to remove leading and trailing spaces from a string

String.Trim

Removes all leading and trailing white-space characters from the current String object.

Usage:

txt = txt.Trim();

If this isn't working then it highly likely that the "spaces" aren't spaces but some other non printing or white space character, possibly tabs. In this case you need to use the String.Trim method which takes an array of characters:

  char[] charsToTrim = { ' ', '\t' };
  string result = txt.Trim(charsToTrim);

Source

You can add to this list as and when you come across more space like characters that are in your input data. Storing this list of characters in your database or configuration file would also mean that you don't have to rebuild your application each time you come across a new character to check for.

NOTE

As of .NET 4 .Trim() removes any character that Char.IsWhiteSpace returns true for so it should work for most cases you come across. Given this, it's probably not a good idea to replace this call with the one that takes a list of characters you have to maintain.

It would be better to call the default .Trim() and then call the method with your list of characters.

HttpServletRequest get JSON POST data

Are you posting from a different source (so different port, or hostname)? If so, this very very recent topic I just answered might be helpful.

The problem was the XHR Cross Domain Policy, and a useful tip on how to get around it by using a technique called JSONP. The big downside is that JSONP does not support POST requests.

I know in the original post there is no mention of JavaScript, however JSON is usually used for JavaScript so that's why I jumped to that conclusion

How to Convert datetime value to yyyymmddhhmmss in SQL server?

Another option I have googled, but contains several replace ...

SELECT REPLACE(REPLACE(REPLACE(CONVERT(VARCHAR(19), CONVERT(DATETIME, getdate(), 112), 126), '-', ''), 'T', ''), ':', '') 

How to switch text case in visual studio code

For those who fear to mess anything up in your vscode json settings this is pretty easy to follow.

  1. Open "File -> Preferences -> Keyboard Shortcuts" or "Code -> Preferences -> Keyboard Shortcuts" for Mac Users

  2. In the search bar type transform.

  3. By default you will not have anything under Keybinding. Now double-click on Transform to Lowercase or Transform to Uppercase.

  4. Press your desired combination of keys to set your keybinding. In this case if copying off of Sublime i will press ctrl+shift+u for uppercase or ctrl+shift+l for lowercase.

  5. Press Enter on your keyboard to save and exit. Do same for the other option.

  6. Enjoy KEYBINDING

How to get a URL parameter in Express?

Express 4.x

To get a URL parameter's value, use req.params

app.get('/p/:tagId', function(req, res) {
  res.send("tagId is set to " + req.params.tagId);
});

// GET /p/5
// tagId is set to 5

If you want to get a query parameter ?tagId=5, then use req.query

app.get('/p', function(req, res) {
  res.send("tagId is set to " + req.query.tagId);
});

// GET /p?tagId=5
// tagId is set to 5

Express 3.x

URL parameter

app.get('/p/:tagId', function(req, res) {
  res.send("tagId is set to " + req.param("tagId"));
});

// GET /p/5
// tagId is set to 5

Query parameter

app.get('/p', function(req, res) {
  res.send("tagId is set to " + req.query("tagId"));
});

// GET /p?tagId=5
// tagId is set to 5

JPA OneToMany not deleting child

You can try this:

@OneToOne(orphanRemoval=true) or @OneToMany(orphanRemoval=true).

Specify a Root Path of your HTML directory for script links?

/ means the root of the current drive;

./ means the current directory;

../ means the parent of the current directory.

1030 Got error 28 from storage engine

If you want to use the tokudb plugin This can happen if you have less than 5% (by default) of free space.

see the option: tokudb_fs_reserve_percent

Absolute position of an element on the screen using jQuery

BTW, if anyone want to get coordinates of element on screen without jQuery, please try this:

function getOffsetTop (el) {
    if (el.offsetParent) return el.offsetTop + getOffsetTop(el.offsetParent)
    return el.offsetTop || 0
}
function getOffsetLeft (el) {
    if (el.offsetParent) return el.offsetLeft + getOffsetLeft(el.offsetParent)
    return el.offsetleft || 0
}
function coordinates(el) {
    var y1 = getOffsetTop(el) - window.scrollY;
    var x1 = getOffsetLeft(el) - window.scrollX; 
    var y2 = y1 + el.offsetHeight;
    var x2 = x1 + el.offsetWidth;
    return {
        x1: x1, x2: x2, y1: y1, y2: y2
    }
}

Can I have two JavaScript onclick events in one element?

There is no need to have two functions within one element, you need just one that calls the other two!

HTML

<a href="#" onclick="my_func()" >click</a>

JavaScript

function my_func() {
    my_func_1();
    my_func_2();
}

NSPhotoLibraryUsageDescription key must be present in Info.plist to use camera roll

Thanks @rmaddy, I added this just after other key-string pairs in Info.plist and fixed the problem:

<key>NSPhotoLibraryUsageDescription</key>
<string>Photo Library Access Warning</string>

Edit:

I also ended up having similar problems on different components of my app. Ended up adding all these keys so far (after updating to Xcode8/iOS10):

<key>NSPhotoLibraryUsageDescription</key>
<string>This app requires access to the photo library.</string>
<key>NSMicrophoneUsageDescription</key>
<string>This app does not require access to the microphone.</string>
<key>NSCameraUsageDescription</key>
<string>This app requires access to the camera.</string>

Checkout this developer.apple.com link for full list of property list key references.

Full List:

Apple Music:

<key>NSAppleMusicUsageDescription</key>
<string>My description about why I need this capability</string>

Bluetooth:

<key>NSBluetoothPeripheralUsageDescription</key>  
<string>My description about why I need this capability</string>

Calendar:

<key>NSCalendarsUsageDescription</key>
<string>My description about why I need this capability</string>

Camera:

<key>NSCameraUsageDescription</key>
<string>My description about why I need this capability</string>

Contacts:

<key>NSContactsUsageDescription</key>
<string>My description about why I need this capability</string>

FaceID:

<key>NSFaceIDUsageDescription</key>
<string>My description about why I need this capability</string>

Health Share:

<key>NSHealthShareUsageDescription</key>
<string>My description about why I need this capability</string>

Health Update:

<key>NSHealthUpdateUsageDescription</key>
<string>My description about why I need this capability</string>

Home Kit:

<key>NSHomeKitUsageDescription</key>
<string>My description about why I need this capability</string>

Location:

<key>NSLocationUsageDescription</key>
<string>My description about why I need this capability</string>

Location (Always):

<key>NSLocationAlwaysUsageDescription</key>
<string>My description about why I need this capability</string>

Location (When in use):

<key>NSLocationWhenInUseUsageDescription</key>
<string>My description about why I need this capability</string>

Microphone:

<key>NSMicrophoneUsageDescription</key>
<string>My description about why I need this capability</string>

Motion (Accelerometer):

<key>NSMotionUsageDescription</key>
<string>My description about why I need this capability</string>

NFC (Near-field communication):

<key>NFCReaderUsageDescription</key>
<string>My description about why I need this capability</string>

Photo Library:

<key>NSPhotoLibraryUsageDescription</key>
<string>My description about why I need this capability</string>

Photo Library (Write-only access):

<key>NSPhotoLibraryAddUsageDescription</key>
<string>My description about why I need this capability</string>

Reminders:

<key>NSRemindersUsageDescription</key>
<string>My description about why I need this capability</string>

Siri:

<key>NSSiriUsageDescription</key>
<string>My description about why I need this capability</string>

Speech Recognition:

<key>NSSpeechRecognitionUsageDescription</key>
<string>My description about why I need this capability</string>

How to upload files to server using Putty (ssh)

Use WinSCP for file transfer over SSH, putty is only for SSH commands.

Java Generate Random Number Between Two Given Values

Use Random.nextInt(int).

In your case it would look something like this:

a[i][j] = r.nextInt(101);

Limiting the number of characters per line with CSS

A better solution would be you use in style css, the command to break lines. Works in older versions of browsers.

p {
word-wrap: break-word;
}

How to Specify "Vary: Accept-Encoding" header in .htaccess

I'm afraid Aularon didn't provide enough steps to complete the process. With a little trial and error, I was able to successfully enable Gzipping on my dedicated WHM server.

Below are the steps:

  • Run EasyApache within WHM, select Deflate within the Exhaustive Options list, and rebuild the server.

  • Once done, goto Services Configuration >> Apache Configuration >> Include Editor >> Post VirtualHost Include, select All Versions, and then paste the mod_headers.c and mod_headers.c code (listed above in Aularon's post) on top of on another within the input field.

  • Once saved, I was seeing a 75.36% data savings on average! You can run a before and after test by using this HTTP Compression tool to see your own results: http://www.whatsmyip.org/http_compression/

Hope this works for you all!

  • Matt

How print out the contents of a HashMap<String, String> in ascending order based on its values?

It's time to add some lambdas:

codes.entrySet()
    .stream()
    .sorted(Comparator.comparing(Map.Entry::getValue))
    .forEach(System.out::println);

Sending email in .NET through Gmail

You can try Mailkit. It gives you better and advance functionality for send mail. You can find more from this Here is an example

    MimeMessage message = new MimeMessage();
    message.From.Add(new MailboxAddress("FromName", "[email protected]"));
    message.To.Add(new MailboxAddress("ToName", "[email protected]"));
    message.Subject = "MyEmailSubject";

    message.Body = new TextPart("plain")
    {
        Text = @"MyEmailBodyOnlyTextPart"
    };

    using (var client = new SmtpClient())
    {
        client.Connect("SERVER", 25); // 25 is port you can change accordingly

        // Note: since we don't have an OAuth2 token, disable
        // the XOAUTH2 authentication mechanism.
        client.AuthenticationMechanisms.Remove("XOAUTH2");

        // Note: only needed if the SMTP server requires authentication
        client.Authenticate("YOUR_USER_NAME", "YOUR_PASSWORD");

        client.Send(message);
        client.Disconnect(true);
    }

Importing a CSV file into a sqlite3 database table using Python

If the CSV file must be imported as part of a python program, then for simplicity and efficiency, you could use os.system along the lines suggested by the following:

import os

cmd = """sqlite3 database.db <<< ".import input.csv mytable" """

rc = os.system(cmd)

print(rc)

The point is that by specifying the filename of the database, the data will automatically be saved, assuming there are no errors reading it.

Fit image into ImageView, keep aspect ratio and then resize ImageView to image dimensions?

This did it for my case.

             <ImageView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_centerHorizontal="true"
                android:scaleType="centerCrop"
                android:adjustViewBounds="true"
                />

CSS background-image-opacity?

You can do the faded background with CSS Generated Content

Demo at http://jsfiddle.net/gaby/WktFm/508/

Html

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

Css

.container{
    position: relative;
    z-index:1;
    overflow:hidden; /*if you want to crop the image*/
}
.container:before{
    z-index:-1;
    position:absolute;
    left:0;
    top:0;
    content: url('path/to/image.ext');
    opacity:0.4;
}

But you cannot modify the opacity as we are not allowed to modify generated content..

You could manipulate it with classes and css events though (but not sure if it fits your needs)

for example

.container:hover:before{
    opacity:1;
}

UPDATE

You can use css transitions to animate the opacity (again through classes)

demo at http://jsfiddle.net/gaby/WktFm/507/

Adding

-webkit-transition: opacity 1s linear;
-o-transition: opacity 1s linear;
-moz-transition: opacity 1s linear;
transition: opacity 1s linear;

to the .container:before rule will make the opacity animate to 1 in one second.

Compatibility

  • FF 5 (maybe 4 also, but do not have it installed.)
  • IE 9 Fails..
  • Webkit based browsers fail (Chrome supports it now v26 - maybe earlier versions too, but just checked with my current build), but they are aware and working on it ( https://bugs.webkit.org/show_bug.cgi?id=23209 )

.. so only the latest FF supports it for the moment.. but a nice idea, no ? :)

Performance of Arrays vs. Lists

Indeed, if you perform some complex calculations inside the loop, then the performance of the array indexer versus the list indexer may be so marginally small, that eventually, it doesn't matter.

SSL Connection / Connection Reset with IISExpress

Make sure to remove any previous 'localhost' certificates as those could conflict with the one generated by IIS Express. I had this same error (ERR_SSL_PROTOCOL_ERROR), and it took me many hours to finally figure it out after trying out many many "solutions". My mistake was that I had created my own 'localhost' certificate and there were two of them. I had to delete both and have IIS Express recreate it.

Here is how you can check for and remove 'localhost' certificate:

  • On Start, type ? mmc.exe
  • File ? Add/Remove Snap-in...
  • Select Certificates ? Add> ? Computer account ? Local computer
  • Check under Certificates > Personal > Certificates
  • Make sure the localhost certificate that exist has a friendly name "IIS Express Development Certificate". If not, delete it. Or if multiple, delete all.

On Visual Studio, select project and under property tab, enable SSL=true. Save, Build and Run. IIS Express will generate a new 'localhost' certificate.

Note: If it doesn't work, try these: make sure to disable IIS Express on VS project and stopping all running app on it prior to removing 'localhost' certificate. Also, you can go to 'control panel > programs' and Repair IIS Express.

Speech input for visually impaired users without the need to tap the screen

The only way to get the iOS dictation is to sign up yourself through Nuance: http://dragonmobile.nuancemobiledeveloper.com/ - it's expensive, because it's the best. Presumably, Apple's contract prevents them from exposing an API.

The built in iOS accessibility features allow immobilized users to access dictation (and other keyboard buttons) through tools like VoiceOver and Assistive Touch. It may not be worth reinventing this if your users might be familiar with these tools.

How to include (source) R script in other scripts

Here is a function I wrote. It wraps the base::source function to store a list of sourced files in a global environment list named sourced. It will only re-source a file if you provide a .force=TRUE argument to the call to source. Its argument signature is otherwise identical to the real source() so you don't need to rewrite your scripts to use this.

warning("overriding source with my own function FYI")
source <- function(path, .force=FALSE, ...) {
  library(tools)
  path <- tryCatch(normalizePath(path), error=function(e) path)
  m<-md5sum(path)

  go<-TRUE
  if (!is.vector(.GlobalEnv$sourced)) {
    .GlobalEnv$sourced <- list()
  }
  if(! is.null(.GlobalEnv$sourced[[path]])) {
    if(m == .GlobalEnv$sourced[[path]]) {
      message(sprintf("Not re-sourcing %s. Override with:\n  source('%s', .force=TRUE)", path, path))
      go<-FALSE
    }
    else {
      message(sprintf('re-sourcing %s as it has changed from: %s to: %s', path, .GlobalEnv$sourced[[path]], m))
      go<-TRUE
    }
  } 
  if(.force) {
    go<-TRUE
    message("  ...forcing.")
  }
  if(go) {
    message(sprintf("sourcing %s", path))
    .GlobalEnv$sourced[path] <- m
    base::source(path, ...)
  }
}

It's pretty chatty (lots of calls to message()) so you can take those lines out if you care. Any advice from veteran R users is appreciated; I'm pretty new to R.

What are the differences between json and simplejson Python modules?

simplejson module is simply 1,5 times faster than json (On my computer, with simplejson 2.1.1 and Python 2.7 x86).

If you want, you can try the benchmark: http://abral.altervista.org/jsonpickle-bench.zip On my PC simplejson is faster than cPickle. I would like to know also your benchmarks!

Probably, as said Coady, the difference between simplejson and json is that simplejson includes _speedups.c. So, why don't python developers use simplejson?

How to fix a header on scroll

Glorious, Pure-HTML/CSS Solution

In 2019 with CSS3 you can do this without Javascript at all. I frequently make sticky headers like this:

_x000D_
_x000D_
body {_x000D_
  overflow-y: auto;_x000D_
  margin: 0;_x000D_
}_x000D_
_x000D_
header {_x000D_
  position: sticky; /* Allocates space for the element, but moves it with you when you scroll */_x000D_
  top: 0; /* specifies the start position for the sticky behavior - 0 is pretty common */_x000D_
  width: 100%;_x000D_
  padding: 5px 0 5px 15px;_x000D_
  color: white;_x000D_
  background-color: #337AB7;_x000D_
  margin: 0;_x000D_
}_x000D_
_x000D_
h1 {_x000D_
  margin: 0;_x000D_
}_x000D_
_x000D_
div.big {_x000D_
  width: 100%;_x000D_
  min-height: 150vh;_x000D_
  background-color: #1ABB9C;_x000D_
  padding: 10px;_x000D_
}
_x000D_
<body>_x000D_
<header><h1>Testquest</h1></header>_x000D_
<div class="big">Just something big enough to scroll on</div>_x000D_
</body>
_x000D_
_x000D_
_x000D_

Reading local text file into a JavaScript array

Using Node.js

sync mode:

var fs = require("fs");
var text = fs.readFileSync("./mytext.txt");
var textByLine = text.split("\n")

async mode:

var fs = require("fs");
fs.readFile("./mytext.txt", function(text){
    var textByLine = text.split("\n")
});

UPDATE

As of at least Node 6, readFileSync returns a Buffer, so it must first be converted to a string in order for split to work:

var text = fs.readFileSync("./mytext.txt").toString('utf-8');

Or

var text = fs.readFileSync("./mytext.txt", "utf-8");

Vertical Tabs with JQuery?

I've created a vertical menu and tabs changing in the middle of the page. I changed two words on the code source and I set apart two different divs

menu:

<div class="arrowgreen">
  <ul class="tabNavigation"> 
    <li> <a href="#first" title="Home">Tab 1</a></li>
    <li> <a href="#secund" title="Home">Tab 2</a></li>
  </ul>
</div> 

content:

<div class="pages">
  <div id="first">
    CONTENT 1
  </div>
  <div id="secund">
    CONTENT 2
  </div>
</div>

the code works with the div apart

$(function () {
    var tabContainers = $('div.pages > div');

    $('div.arrowgreen ul.tabNavigation a').click(function () {
        tabContainers.hide().filter(this.hash).show();

        $('div.arrowgreen ul.tabNavigation a').removeClass('selected');
        $(this).addClass('selected');

        return false;
    }).filter(':first').click();
});

Error Code: 1290. The MySQL server is running with the --secure-file-priv option so it cannot execute this statement

A quick answer, that doesn't require you to edit any configuration files (and works on other operating systems as well as Windows), is to just find the directory that you are allowed to save to using:

mysql> SHOW VARIABLES LIKE "secure_file_priv";
+------------------+-----------------------+
| Variable_name    | Value                 |
+------------------+-----------------------+
| secure_file_priv | /var/lib/mysql-files/ |
+------------------+-----------------------+
1 row in set (0.06 sec)

And then make sure you use that directory in your SELECT statement's INTO OUTFILE clause:

SELECT *
FROM xxxx
WHERE XXX
INTO OUTFILE '/var/lib/mysql-files/report.csv'
    FIELDS TERMINATED BY '#'
    ENCLOSED BY '"'
    LINES TERMINATED BY '\n'

Original answer

I've had the same problem since upgrading from MySQL 5.6.25 to 5.6.26.

In my case (on Windows), looking at the MySQL56 Windows service shows me that the options/settings file that is being used when the service starts is C:\ProgramData\MySQL\MySQL Server 5.6\my.ini

On linux the two most common locations are /etc/my.cnf or /etc/mysql/my.cnf.

MySQL56 Service

Opening this file I can see that the secure-file-priv option has been added under the [mysqld] group in this new version of MySQL Server with a default value:

secure-file-priv="C:/ProgramData/MySQL/MySQL Server 5.6/Uploads"

You could comment this (if you're in a non-production environment), or experiment with changing the setting (recently I had to set secure-file-priv = "" in order to disable the default). Don't forget to restart the service after making changes.

Alternatively, you could try saving your output into the permitted folder (the location may vary depending on your installation):

SELECT *
FROM xxxx
WHERE XXX
INTO OUTFILE 'C:/ProgramData/MySQL/MySQL Server 5.6/Uploads/report.csv'
    FIELDS TERMINATED BY '#'
    ENCLOSED BY '"'
    LINES TERMINATED BY '\n'

It's more common to have comma seperate values using FIELDS TERMINATED BY ','. See below for an example (also showing a Linux path):

SELECT *
FROM table
INTO OUTFILE '/var/lib/mysql-files/report.csv'
    FIELDS TERMINATED BY ',' ENCLOSED BY '"'
    ESCAPED BY ''
    LINES TERMINATED BY '\n';

'invalid value encountered in double_scalars' warning, possibly numpy

I encount this while I was calculating np.var(np.array([])). np.var will divide size of the array which is zero in this case.

SELECT last id, without INSERT

I think to add timestamp to every record and get the latest. In this situation you can get any ids, pack rows and other ops.

jquery - Click event not working for dynamically created button

You could also create the input button in this way:

var button = '<input type="button" id="questionButton" value='+variable+'> <br />';


It might be the syntax of the Button creation that is off somehow.

Hibernate Error executing DDL via JDBC Statement

I have got this error when trying to create JPA entity with the name "User" (in Postgres) that is reserved. So the way it is resolved is to change the table name by @Table annotation:

@Entity
@Table(name="users")
public class User {..}

Or change the table name manually.

android: how to align image in the horizontal center of an imageview?

This is code in xml of how to center an ImageView, I used "layout_centerHorizontal".

<LinearLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:layout_centerHorizontal="true"
    >
    <ImageView
        android:layout_width="40dp"
        android:layout_height="40dp"
        android:src="@drawable/img2"
    />
    <ImageView
        android:layout_width="40dp"
        android:layout_height="40dp"
        android:src="@drawable/img1"
        />
</LinearLayout>

or this other example...

<LinearLayout
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:gravity="center_horizontal"
    >
    <ImageView
        android:layout_width="40dp"
        android:layout_height="40dp"
        android:src="@drawable/img2"
    />
    <ImageView
        android:layout_width="40dp"
        android:layout_height="40dp"
        android:src="@drawable/img1"
        />
</LinearLayout>

Using "If cell contains #N/A" as a formula condition.

Input the following formula in C1:

=IF(ISNA(A1),B1,A1*B1)

Screenshots:

When #N/A:

enter image description here

When not #N/A:

enter image description here

Let us know if this helps.

Cross field validation with Hibernate Validator (JSR 303)

Solution realated with question: How to access a field which is described in annotation property

@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Match {

    String field();

    String message() default "";
}

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = MatchValidator.class)
@Documented
public @interface EnableMatchConstraint {

    String message() default "Fields must match!";

    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};
}

public class MatchValidator implements  ConstraintValidator<EnableMatchConstraint, Object> {

    @Override
    public void initialize(final EnableMatchConstraint constraint) {}

    @Override
    public boolean isValid(final Object o, final ConstraintValidatorContext context) {
        boolean result = true;
        try {
            String mainField, secondField, message;
            Object firstObj, secondObj;

            final Class<?> clazz = o.getClass();
            final Field[] fields = clazz.getDeclaredFields();

            for (Field field : fields) {
                if (field.isAnnotationPresent(Match.class)) {
                    mainField = field.getName();
                    secondField = field.getAnnotation(Match.class).field();
                    message = field.getAnnotation(Match.class).message();

                    if (message == null || "".equals(message))
                        message = "Fields " + mainField + " and " + secondField + " must match!";

                    firstObj = BeanUtils.getProperty(o, mainField);
                    secondObj = BeanUtils.getProperty(o, secondField);

                    result = firstObj == null && secondObj == null || firstObj != null && firstObj.equals(secondObj);
                    if (!result) {
                        context.disableDefaultConstraintViolation();
                        context.buildConstraintViolationWithTemplate(message).addPropertyNode(mainField).addConstraintViolation();
                        break;
                    }
                }
            }
        } catch (final Exception e) {
            // ignore
            //e.printStackTrace();
        }
        return result;
    }
}

And how to use it...? Like this:

@Entity
@EnableMatchConstraint
public class User {

    @NotBlank
    private String password;

    @Match(field = "password")
    private String passwordConfirmation;
}

CSS media query to target only iOS devices

Yes, you can.

@supports (-webkit-touch-callout: none) {
  /* CSS specific to iOS devices */ 
}

@supports not (-webkit-touch-callout: none) {
  /* CSS for other than iOS devices */ 
}

YMMV.

It works because only Safari Mobile implements -webkit-touch-callout: https://developer.mozilla.org/en-US/docs/Web/CSS/-webkit-touch-callout

Please note that @supports does not work in IE. IE will skip both of the above @support blocks above. To find out more see https://hacks.mozilla.org/2016/08/using-feature-queries-in-css/. It is recommended to not use @supports not because of this.

What about Chrome or Firefox on iOS? The reality is these are just skins over the WebKit rendering engine. Hence the above works everywhere on iOS as long as iOS policy does not change. See 2.5.6 in App Store Review Guidelines.

Warning: iOS may remove support for this in any new iOS release in the coming years. You SHOULD try a bit harder to not need the above CSS. An earlier version of this answer used -webkit-overflow-scrolling but a new iOS version removed it. As a commenter pointed out, there are other options to choose from: Go to Supported CSS Properties and search for "Safari on iOS".

<meta charset="utf-8"> vs <meta http-equiv="Content-Type">

In HTML5, they are equivalent. Use the shorter one, it is easier to remember and type. Browser support is fine since it was designed for backwards compatibility.

How to manually include external aar package using new Gradle Android Build System

I've also had this problem. This issue report: https://code.google.com/p/android/issues/detail?id=55863 seems to suggest that directly referencing the .AAR file is not supported.

Perhaps the alternative for now is to define the actionbarsherlock library as a Gradle library under the parent directory of your project and reference accordingly.

The syntax is defined here http://tools.android.com/tech-docs/new-build-system/user-guide#TOC-Referencing-a-Library

What exactly does the T and Z mean in timestamp?

The T doesn't really stand for anything. It is just the separator that the ISO 8601 combined date-time format requires. You can read it as an abbreviation for Time.

The Z stands for the Zero timezone, as it is offset by 0 from the Coordinated Universal Time (UTC).

Both characters are just static letters in the format, which is why they are not documented by the datetime.strftime() method. You could have used Q or M or Monty Python and the method would have returned them unchanged as well; the method only looks for patterns starting with % to replace those with information from the datetime object.

Java Replace Character At Specific Position Of String?

If you need to re-use a string, then use StringBuffer:

String str = "hi";
StringBuffer sb = new StringBuffer(str);
while (...) {
    sb.setCharAt(1, 'k');
}

EDIT:

Note that StringBuffer is thread-safe, while using StringBuilder is faster, but not thread-safe.

std::enable_if to conditionally compile a member function

SFINAE only works if substitution in argument deduction of a template argument makes the construct ill-formed. There is no such substitution.

I thought of that too and tried to use std::is_same< T, int >::value and ! std::is_same< T, int >::value which gives the same result.

That's because when the class template is instantiated (which happens when you create an object of type Y<int> among other cases), it instantiates all its member declarations (not necessarily their definitions/bodies!). Among them are also its member templates. Note that T is known then, and !std::is_same< T, int >::value yields false. So it will create a class Y<int> which contains

class Y<int> {
    public:
        /* instantiated from
        template < typename = typename std::enable_if< 
          std::is_same< T, int >::value >::type >
        T foo() {
            return 10;
        }
        */

        template < typename = typename std::enable_if< true >::type >
        int foo();

        /* instantiated from

        template < typename = typename std::enable_if< 
          ! std::is_same< T, int >::value >::type >
        T foo() {
            return 10;
        }
        */

        template < typename = typename std::enable_if< false >::type >
        int foo();
};

The std::enable_if<false>::type accesses a non-existing type, so that declaration is ill-formed. And thus your program is invalid.

You need to make the member templates' enable_if depend on a parameter of the member template itself. Then the declarations are valid, because the whole type is still dependent. When you try to call one of them, argument deduction for their template arguments happen and SFINAE happens as expected. See this question and the corresponding answer on how to do that.

.substring error: "is not a function"

You can use substr

for example:

new Date().getFullYear().toString().substr(-2)

How to use CURL via a proxy?

Here is a well tested function which i used for my projects with detailed self explanatory comments


There are many times when the ports other than 80 are blocked by server firewall so the code appears to be working fine on localhost but not on the server

function get_page($url){

global $proxy;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
//curl_setopt($ch, CURLOPT_PROXY, $proxy);
curl_setopt($ch, CURLOPT_HEADER, 0); // return headers 0 no 1 yes
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // return page 1:yes
curl_setopt($ch, CURLOPT_TIMEOUT, 200); // http request timeout 20 seconds
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); // Follow redirects, need this if the url changes
curl_setopt($ch, CURLOPT_MAXREDIRS, 2); //if http server gives redirection responce
curl_setopt($ch, CURLOPT_USERAGENT,
    "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.7) Gecko/20070914 Firefox/2.0.0.7");
curl_setopt($ch, CURLOPT_COOKIEJAR, "cookies.txt"); // cookies storage / here the changes have been made
curl_setopt($ch, CURLOPT_COOKIEFILE, "cookies.txt");
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // false for https
curl_setopt($ch, CURLOPT_ENCODING, "gzip"); // the page encoding

$data = curl_exec($ch); // execute the http request
curl_close($ch); // close the connection
return $data;
}

How to launch Windows Scheduler by command-line?

I'm also running XP SP2, and this works perfectly (from the command line...):

start control schedtasks

Disable hover effects on mobile browsers

What I've done to solve the same problem is to have a feature detection (I use something like this code), seeing if onTouchMove is defined, and if so I add the css class "touchMode" to the body, else i add "desktopMode".

Then every time some style effect only applies to a touch device, or only to a desktop the css rule is prepended with the appropriate class:

.desktopMode .someClass:hover{ color: red }
.touchMode .mainDiv { width: 100%; margin: 0; /*etc.*/ }

Edit: This strategy of course adds a few extra characters to your css, so If you're concerned about css size, you could search for the touchMode and desktopMode definitons and put them into different files, so you can serve optimized css for each device type; or you could change the class names to something much shorter before going to prod.

TensorFlow not found using pip

I was facing the same issue. I tried the following and it worked. installing for Mac OS X, anaconda python 2.7

pip uninstall tensorflow export TF_BINARY_URL=<get the correct url from http://tflearn.org/installation/> pip install --upgrade $TF_BINARY_URL

Installed tensorflow-1.0.0

Procedure or function !!! has too many arguments specified

Use the following command before defining them:

cmd.Parameters.Clear()

Making a drop down list using swift?

A 'drop down menu' is a web control / term. In iOS we don't have these. You might be better looking at UIPopoverController. Check out this tutorial for a bit of an insight to PopoverControllers

http://www.raywenderlich.com/29472/ipad-for-iphone-developers-101-in-ios-6-uipopovercontroller-tutorial

Assign a class name to <img> tag instead of write it in css file?

Assigning a class name and applying a CSS style are two different things.

If you mean <img class="someclass">, and

.someclass {
  [cssrule]
}

, then there is no real performance difference between applying the css to the class, or to .column img

How to use JQuery with ReactJS

Earlier,I was facing problem in using jquery with React js,so I did following steps to make it working-

  1. npm install jquery --save

  2. Then, import $ from "jquery";

    See here

How to open maximized window with Javascript?

var params = [
    'height='+screen.height,
    'width='+screen.width,
    'fullscreen=yes' // only works in IE, but here for completeness
].join(',');
     // and any other options from
     // https://developer.mozilla.org/en/DOM/window.open

var popup = window.open('http://www.google.com', 'popup_window', params); 
popup.moveTo(0,0);

Please refrain from opening the popup unless the user really wants it, otherwise they will curse you and blacklist your site. ;-)

edit: Oops, as Joren Van Severen points out in a comment, this may not take into account taskbars and window decorations (in a possibly browser-dependent way). Be aware. It seems that ignoring height and width (only param is fullscreen=yes) seems to work on Chrome and perhaps Firefox too; the original 'fullscreen' functionality has been disabled in Firefox for being obnoxious, but has been replaced with maximization. This directly contradicts information on the same page of https://developer.mozilla.org/en/DOM/window.open which says that window-maximizing is impossible. This 'feature' may or may not be supported depending on the browser.

Regex to replace multiple spaces with a single space

I know that I am late to the party, but I discovered a nice solution.

Here it is:

var myStr = myStr.replace(/[ ][ ]*/g, ' ');

AddRange to a Collection

Try casting to List in the extension method before running the loop. That way you can take advantage of the performance of List.AddRange.

public static void AddRange<T>(this ICollection<T> destination,
                               IEnumerable<T> source)
{
    List<T> list = destination as List<T>;

    if (list != null)
    {
        list.AddRange(source);
    }
    else
    {
        foreach (T item in source)
        {
            destination.Add(item);
        }
    }
}

How to get Real IP from Visitor?

Try this php code.

<?PHP

function getUserIP()
{
    // Get real visitor IP behind CloudFlare network
    if (isset($_SERVER["HTTP_CF_CONNECTING_IP"])) {
              $_SERVER['REMOTE_ADDR'] = $_SERVER["HTTP_CF_CONNECTING_IP"];
              $_SERVER['HTTP_CLIENT_IP'] = $_SERVER["HTTP_CF_CONNECTING_IP"];
    }
    $client  = @$_SERVER['HTTP_CLIENT_IP'];
    $forward = @$_SERVER['HTTP_X_FORWARDED_FOR'];
    $remote  = $_SERVER['REMOTE_ADDR'];

    if(filter_var($client, FILTER_VALIDATE_IP))
    {
        $ip = $client;
    }
    elseif(filter_var($forward, FILTER_VALIDATE_IP))
    {
        $ip = $forward;
    }
    else
    {
        $ip = $remote;
    }

    return $ip;
}


$user_ip = getUserIP();

echo $user_ip; // Output IP address [Ex: 177.87.193.134]


?>

What are good grep tools for Windows?

Another good choice is MSYS. It gives you a bunch of other GNU utilities to allow you to be more productive.

Is it possible to sort a ES6 map object?

Perhaps a more realistic example about not sorting a Map object but preparing the sorting up front before doing the Map. The syntax gets actually pretty compact if you do it like this. You can apply the sorting before the map function like this, with a sort function before map (Example from a React app I am working on using JSX syntax)

Mark that I here define a sorting function inside using an arrow function that returns -1 if it is smaller and 0 otherwise sorted on a property of the Javascript objects in the array I get from an API.

report.ProcedureCodes.sort((a, b) => a.NumericalOrder < b.NumericalOrder ? -1 : 0).map((item, i) =>
                        <TableRow key={i}>

                            <TableCell>{item.Code}</TableCell>
                            <TableCell>{item.Text}</TableCell>
                            {/* <TableCell>{item.NumericalOrder}</TableCell> */}
                        </TableRow>
                    )

HTML/CSS - Adding an Icon to a button

Here's what you can do using font-awesome library.

_x000D_
_x000D_
button.btn.add::before {_x000D_
  font-family: fontAwesome;_x000D_
  content: "\f067\00a0";_x000D_
}_x000D_
_x000D_
button.btn.edit::before {_x000D_
  font-family: fontAwesome;_x000D_
  content: "\f044\00a0";_x000D_
}_x000D_
_x000D_
button.btn.save::before {_x000D_
  font-family: fontAwesome;_x000D_
  content: "\f00c\00a0";_x000D_
}_x000D_
_x000D_
button.btn.cancel::before {_x000D_
  font-family: fontAwesome;_x000D_
  content: "\f00d\00a0";_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>_x000D_
<!--FA unicodes here: http://astronautweb.co/snippet/font-awesome/-->_x000D_
<h4>Buttons with text</h4>_x000D_
<button class="btn cancel btn-default">Close</button>_x000D_
<button class="btn add btn-primary">Add</button>_x000D_
<button class="btn add btn-success">Insert</button>_x000D_
<button class="btn save btn-primary">Save</button>_x000D_
<button class="btn save btn-warning">Submit Changes</button>_x000D_
<button class="btn cancel btn-link">Delete</button>_x000D_
<button class="btn edit btn-info">Edit</button>_x000D_
<button class="btn edit btn-danger">Modify</button>_x000D_
_x000D_
<br/>_x000D_
<br/>_x000D_
<h4>Buttons without text</h4>_x000D_
<button class="btn edit btn-primary" />_x000D_
<button class="btn cancel btn-danger" />_x000D_
<button class="btn add btn-info" />_x000D_
<button class="btn save btn-success" />_x000D_
<button class="btn edit btn-link"/>_x000D_
<button class="btn cancel btn-link"/>
_x000D_
_x000D_
_x000D_

Fiddle here.

How to display databases in Oracle 11g using SQL*Plus

I am not clearly about it but typically one server has one database (with many users), if you create many databases mean that you create many instances, listeners, ... as well. So you can check your LISTENER to identify it.

In my testing I created 2 databases (dbtest and dbtest_1) so when I check my LISTENER status it appeared like this:

lsnrctl status

....

STATUS of the LISTENER

.....

(DESCRIPTION=(ADDRESS=(PROTOCOL=tcp)(HOST=10.10.20.20)(PORT=1521)))

Services Summary...

Service "dbtest" has 1 instance(s).

Instance "dbtest", status READY, has 1 handler(s) for this service...

Service "dbtest1XDB" has 1 instance(s).

Instance "dbtest1", status READY, has 1 handler(s) for this service...

Service "dbtest_1" has 1 instance(s).

Instance "dbtest1", status READY, has 1 handler(s) for this service... The command completed successfully

Non-static method requires a target

All the answers are pointing to a Lambda expression with an NRE (Null Reference Exception). I have found that it also occurs when using Linq to Entities. I thought it would be helpful to point out that this exception is not limited to just an NRE inside a Lambda expression.

Access multiple viewchildren using @viewchild

Use the @ViewChildren decorator combined with QueryList. Both of these are from "@angular/core"

@ViewChildren(CustomComponent) customComponentChildren: QueryList<CustomComponent>;

Doing something with each child looks like: this.customComponentChildren.forEach((child) => { child.stuff = 'y' })

There is further documentation to be had at angular.io, specifically: https://angular.io/docs/ts/latest/cookbook/component-communication.html#!#sts=Parent%20calls%20a%20ViewChild

How to add jQuery code into HTML Page

for latest Jquery. Simply:

<script src="https://code.jquery.com/jquery-latest.min.js"></script>

How to allow <input type="file"> to accept only image files?

Using this:

<input type="file" accept="image/*">

works in both FF and Chrome.

Java: How to set Precision for double value?

To set precision for double values DecimalFormat is good technique. To use this class import java.text.DecimalFormat and create object of it for example

double no=12.786;
DecimalFormat dec = new DecimalFormat("#0.00");
System.out.println(dec.format(no));

So it will print two digits after decimal point here it will print 12.79

Convert pandas Series to DataFrame

Series.to_frame can be used to convert a Series to DataFrame.

# The provided name (columnName) will substitute the series name
df = series.to_frame('columnName')

For example,

s = pd.Series(["a", "b", "c"], name="vals")
df = s.to_frame('newCol')
print(df)

   newCol
0    a
1    b
2    c

Is there a way that I can check if a data attribute exists?

This is the easiest solution in my opinion is to select all the element which has certain data attribute:

var data = $("#dataTable[data-timer]");
var diffs = [];

for(var i = 0; i + 1 < data.length; i++) {
    diffs[i] = data[i + 1] - data[i];
}

alert(diffs.join(', '));

Here is the screenshot of how it works.

console log of the jquery selector

How to paste into a terminal?

Shift + Insert usually works throughout X11.

JavaScript get clipboard data on paste event (Cross browser)

Solution that works for me is adding event listener to paste event if you are pasting to a text input. Since paste event happens before text in input changes, inside my on paste handler I create a deferred function inside which I check for changes in my input box that happened on paste:

onPaste: function() {
    var oThis = this;
    setTimeout(function() { // Defer until onPaste() is done
        console.log('paste', oThis.input.value);
        // Manipulate pasted input
    }, 1);
}

How can I show data using a modal when clicking a table row (using bootstrap)?

The best practice is to ajax load the order information when click tr tag, and render the information html in $('#orderDetails') like this:

  $.get('the_get_order_info_url', { order_id: the_id_var }, function(data){
    $('#orderDetails').html(data);
  }, 'script')

Alternatively, you can add class for each td that contains the order info, and use jQuery method $('.class').html(html_string) to insert specific order info into your #orderDetails BEFORE you show the modal, like:

  <% @restaurant.orders.each do |order| %>
  <!-- you should add more class and id attr to help control the DOM -->
  <tr id="order_<%= order.id %>" onclick="orderModal(<%= order.id  %>);">
    <td class="order_id"><%= order.id %></td>
    <td class="customer_id"><%= order.customer_id %></td>
    <td class="status"><%= order.status %></td>
  </tr>
  <% end %>

js:

function orderModal(order_id){
  var tr = $('#order_' + order_id);
  // get the current info in html table 
  var customer_id = tr.find('.customer_id');
  var status = tr.find('.status');

  // U should work on lines here:
  var info_to_insert = "order: " + order_id + ", customer: " + customer_id + " and status : " + status + ".";
  $('#orderDetails').html(info_to_insert);

  $('#orderModal').modal({
    keyboard: true,
    backdrop: "static"
  });
};

That's it. But I strongly recommend you to learn sth about ajax on Rails. It's pretty cool and efficient.

How to set top position using jquery

Just for reference, if you are using:

 $(el).offset().top 

To get the position, it can be affected by the position of the parent element. Thus you may want to be consistent and use the following to set it:

$(el).offset({top: pos});

As opposed to the CSS methods above.

PySpark 2.0 The size or shape of a DataFrame

You can get its shape with:

print((df.count(), len(df.columns)))

Redirecting output to $null in PowerShell, but ensuring the variable remains set

using a function:

function run_command ($command)
{
    invoke-expression "$command *>$null"
    return $_
}

if (!(run_command "dir *.txt"))
{
    if (!(run_command "dir *.doc"))
    {
        run_command "dir *.*"
    }
}

or if you like one-liners:

function run_command ($command) { invoke-expression "$command  "|out-null; return $_ }

if (!(run_command "dir *.txt")) { if (!(run_command "dir *.doc")) { run_command "dir *.*" } }

CSS selector for a checked radio button's label

If your input is a child element of the label and you have more than one labels, you can combine @Mike's trick with Flexbox + order.

enter image description here

_x000D_
_x000D_
label.switchLabel {
  display: flex;
  justify-content: space-between;
  width: 150px;
}
.switchLabel .left   { order: 1; }
.switchLabel .switch { order: 2; }
.switchLabel .right  { order: 3; }

/* sibling selector ~ */
.switchLabel .switch:not(:checked) ~ span.left { color: lightblue }
.switchLabel .switch:checked ~ span.right { color: lightblue }



/* style the switch */

:root {
  --radio-size: 14px;
}

.switchLabel input.switch  {
  width: var(--radio-size);
  height: var(--radio-size);
  border-radius: 50%;
  border: 1px solid #999999;
  box-sizing: border-box;
  outline: none;
  -webkit-appearance: inherit;
  -moz-appearance: inherit;
  appearance: inherit;
  
  box-shadow: calc(var(--radio-size) / 2) 0 0 0 gray, calc(var(--radio-size) / 4) 0 0 0 gray;
  margin: 0 calc(5px + var(--radio-size) / 2) 0 5px;
}

.switchLabel input.switch:checked {
  box-shadow: calc(-1 * var(--radio-size) / 2) 0 0 0 gray, calc(-1 * var(--radio-size) / 4) 0 0 0 gray;
  margin: 0 5px 0 calc(5px + var(--radio-size) / 2);
}
_x000D_
<label class="switchLabel">
  <input type="checkbox" class="switch" />
  <span class="left">Left</span>
  <span class="right">Right</span>
</label>
_x000D_
_x000D_
_x000D_ asd

html
<label class="switchLabel">
  <input type="checkbox" class="switch"/>
  <span class="left">Left</span>
  <span class="right">Right</span>
</label>
css
label.switchLabel {
  display: flex;
  justify-content: space-between;
  width: 150px;
}
.switchLabel .left   { order: 1; }
.switchLabel .switch { order: 2; }
.switchLabel .right  { order: 3; }

/* sibling selector ~ */
.switchLabel .switch:not(:checked) ~ span.left { color: lightblue }
.switchLabel .switch:checked ~ span.right { color: lightblue }

See it on JSFiddle.

note: Sibling selector only works within the same parent. To work around this, you can make the input hidden at top-level using @Nathan Blair hack.

How to enumerate an enum with String type?

Xcode 10 with Swift 4.2

enum Filter: String, CaseIterable {

    case salary = "Salary"
    case experience = "Experience"
    case technology = "Technology"
    case unutilized = "Unutilized"
    case unutilizedHV = "Unutilized High Value"

    static let allValues = Filter.allCases.map { $0.rawValue }
}

Call it

print(Filter.allValues)

Prints:

["Salary", "Experience", "Technology", "Unutilized", "Unutilized High Value"]


Older versions

For enum representing Int

enum Filter: Int {
    case salary
    case experience
    case technology
    case unutilized
    case unutilizedHV
    
    static let allRawValues = salary.rawValue...unutilizedHV.rawValue  // First to last case
    static let allValues = allRawValues.map { Filter(rawValue: $0)!.rawValue }
}

Call it like this:

print(Filter.allValues)

Prints:

[0, 1, 2, 3, 4]


For enum representing String

enum Filter: Int {
    case salary
    case experience
    case technology
    case unutilized
    case unutilizedHV
    
    static let allRawValues = salary.rawValue...unutilizedHV.rawValue  // First to last case
    static let allValues = allRawValues.map { Filter(rawValue: $0)!.description }
}

extension Filter: CustomStringConvertible {
    var description: String {
        switch self {
        case .salary: return "Salary"
        case .experience: return "Experience"
        case .technology: return "Technology"
        case .unutilized: return "Unutilized"
        case .unutilizedHV: return "Unutilized High Value"
        }
    }
}

Call it

print(Filter.allValues)

Prints:

["Salary", "Experience", "Technology", "Unutilized", "Unutilized High Value"]

How to get UTF-8 working in Java webapps?

Answering myself as the FAQ of this site encourages it. This works for me:

Mostly characters äåö are not a problematic as the default character set used by browsers and tomcat/java for webapps is latin1 ie. ISO-8859-1 which "understands" those characters.

To get UTF-8 working under Java+Tomcat+Linux/Windows+Mysql requires the following:

Configuring Tomcat's server.xml

It's necessary to configure that the connector uses UTF-8 to encode url (GET request) parameters:

<Connector port="8080" maxHttpHeaderSize="8192"
 maxThreads="150" minSpareThreads="25" maxSpareThreads="75"
 enableLookups="false" redirectPort="8443" acceptCount="100"
 connectionTimeout="20000" disableUploadTimeout="true" 
 compression="on" 
 compressionMinSize="128" 
 noCompressionUserAgents="gozilla, traviata" 
 compressableMimeType="text/html,text/xml,text/plain,text/css,text/ javascript,application/x-javascript,application/javascript"
 URIEncoding="UTF-8"
/>

The key part being URIEncoding="UTF-8" in the above example. This quarantees that Tomcat handles all incoming GET parameters as UTF-8 encoded. As a result, when the user writes the following to the address bar of the browser:

 https://localhost:8443/ID/Users?action=search&name=*?*

the character ? is handled as UTF-8 and is encoded to (usually by the browser before even getting to the server) as %D0%B6.

POST request are not affected by this.

CharsetFilter

Then it's time to force the java webapp to handle all requests and responses as UTF-8 encoded. This requires that we define a character set filter like the following:

package fi.foo.filters;

import javax.servlet.*;
import java.io.IOException;

public class CharsetFilter implements Filter {

    private String encoding;

    public void init(FilterConfig config) throws ServletException {
        encoding = config.getInitParameter("requestEncoding");
        if (encoding == null) encoding = "UTF-8";
    }

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain next)
            throws IOException, ServletException {
        // Respect the client-specified character encoding
        // (see HTTP specification section 3.4.1)
        if (null == request.getCharacterEncoding()) {
            request.setCharacterEncoding(encoding);
        }

        // Set the default response content type and encoding
        response.setContentType("text/html; charset=UTF-8");
        response.setCharacterEncoding("UTF-8");

        next.doFilter(request, response);
    }

    public void destroy() {
    }
}

This filter makes sure that if the browser hasn't set the encoding used in the request, that it's set to UTF-8.

The other thing done by this filter is to set the default response encoding ie. the encoding in which the returned html/whatever is. The alternative is to set the response encoding etc. in each controller of the application.

This filter has to be added to the web.xml or the deployment descriptor of the webapp:

 <!--CharsetFilter start--> 

  <filter>
    <filter-name>CharsetFilter</filter-name>
    <filter-class>fi.foo.filters.CharsetFilter</filter-class>
      <init-param>
        <param-name>requestEncoding</param-name>
        <param-value>UTF-8</param-value>
      </init-param>
  </filter>

  <filter-mapping>
    <filter-name>CharsetFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>

The instructions for making this filter are found at the tomcat wiki (http://wiki.apache.org/tomcat/Tomcat/UTF-8)

JSP page encoding

In your web.xml, add the following:

<jsp-config>
    <jsp-property-group>
        <url-pattern>*.jsp</url-pattern>
        <page-encoding>UTF-8</page-encoding>
    </jsp-property-group>
</jsp-config>

Alternatively, all JSP-pages of the webapp would need to have the following at the top of them:

 <%@page pageEncoding="UTF-8" contentType="text/html; charset=UTF-8"%>

If some kind of a layout with different JSP-fragments is used, then this is needed in all of them.

HTML-meta tags

JSP page encoding tells the JVM to handle the characters in the JSP page in the correct encoding. Then it's time to tell the browser in which encoding the html page is:

This is done with the following at the top of each xhtml page produced by the webapp:

   <?xml version="1.0" encoding="UTF-8"?>
   <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
   <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="fi">
   <head>
   <meta http-equiv='Content-Type' content='text/html; charset=UTF-8' />
   ...

JDBC-connection

When using a db, it has to be defined that the connection uses UTF-8 encoding. This is done in context.xml or wherever the JDBC connection is defiend as follows:

      <Resource name="jdbc/AppDB" 
        auth="Container"
        type="javax.sql.DataSource"
        maxActive="20" maxIdle="10" maxWait="10000"
        username="foo"
        password="bar"
        driverClassName="com.mysql.jdbc.Driver" url="jdbc:mysql://localhost:3306/      ID_development?useEncoding=true&amp;characterEncoding=UTF-8"
    />

MySQL database and tables

The used database must use UTF-8 encoding. This is achieved by creating the database with the following:

   CREATE DATABASE `ID_development` 
   /*!40100 DEFAULT CHARACTER SET utf8 COLLATE utf8_swedish_ci */;

Then, all of the tables need to be in UTF-8 also:

   CREATE TABLE  `Users` (
    `id` int(10) unsigned NOT NULL auto_increment,
    `name` varchar(30) collate utf8_swedish_ci default NULL
    PRIMARY KEY  (`id`)
   ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_swedish_ci ROW_FORMAT=DYNAMIC;

The key part being CHARSET=utf8.

MySQL server configuration

MySQL serveri has to be configured also. Typically this is done in Windows by modifying my.ini -file and in Linux by configuring my.cnf -file. In those files it should be defined that all clients connected to the server use utf8 as the default character set and that the default charset used by the server is also utf8.

   [client]
   port=3306
   default-character-set=utf8

   [mysql]
   default-character-set=utf8

Mysql procedures and functions

These also need to have the character set defined. For example:

   DELIMITER $$

   DROP FUNCTION IF EXISTS `pathToNode` $$
   CREATE FUNCTION `pathToNode` (ryhma_id INT) RETURNS TEXT CHARACTER SET utf8
   READS SQL DATA
   BEGIN

    DECLARE path VARCHAR(255) CHARACTER SET utf8;

   SET path = NULL;

   ...

   RETURN path;

   END $$

   DELIMITER ;

GET requests: latin1 and UTF-8

If and when it's defined in tomcat's server.xml that GET request parameters are encoded in UTF-8, the following GET requests are handled properly:

   https://localhost:8443/ID/Users?action=search&name=Petteri
   https://localhost:8443/ID/Users?action=search&name=?

Because ASCII-characters are encoded in the same way both with latin1 and UTF-8, the string "Petteri" is handled correctly.

The Cyrillic character ? is not understood at all in latin1. Because Tomcat is instructed to handle request parameters as UTF-8 it encodes that character correctly as %D0%B6.

If and when browsers are instructed to read the pages in UTF-8 encoding (with request headers and html meta-tag), at least Firefox 2/3 and other browsers from this period all encode the character themselves as %D0%B6.

The end result is that all users with name "Petteri" are found and also all users with the name "?" are found.

But what about äåö?

HTTP-specification defines that by default URLs are encoded as latin1. This results in firefox2, firefox3 etc. encoding the following

    https://localhost:8443/ID/Users?action=search&name=*Päivi*

in to the encoded version

    https://localhost:8443/ID/Users?action=search&name=*P%E4ivi*

In latin1 the character ä is encoded as %E4. Even though the page/request/everything is defined to use UTF-8. The UTF-8 encoded version of ä is %C3%A4

The result of this is that it's quite impossible for the webapp to correly handle the request parameters from GET requests as some characters are encoded in latin1 and others in UTF-8. Notice: POST requests do work as browsers encode all request parameters from forms completely in UTF-8 if the page is defined as being UTF-8

Stuff to read

A very big thank you for the writers of the following for giving the answers for my problem:

  • http://tagunov.tripod.com/i18n/i18n.html
  • http://wiki.apache.org/tomcat/Tomcat/UTF-8
  • http://java.sun.com/developer/technicalArticles/Intl/HTTPCharset/
  • http://dev.mysql.com/doc/refman/5.0/en/charset-syntax.html
  • http://cagan327.blogspot.com/2006/05/utf-8-encoding-fix-tomcat-jsp-etc.html
  • http://cagan327.blogspot.com/2006/05/utf-8-encoding-fix-for-mysql-tomcat.html
  • http://jeppesn.dk/utf-8.html
  • http://www.nabble.com/request-parameters-mishandle-utf-8-encoding-td18720039.html
  • http://www.utoronto.ca/webdocs/HTMLdocs/NewHTML/iso_table.html
  • http://www.utf8-chartable.de/

Important Note

supports the Basic Multilingual Plane using 3-byte UTF-8 characters. If you need to go outside of that (certain alphabets require more than 3-bytes of UTF-8), then you either need to use a flavor of VARBINARY column type or use the utf8mb4 character set (which requires MySQL 5.5.3 or later). Just be aware that using the utf8 character set in MySQL won't work 100% of the time.

Tomcat with Apache

One more thing If you are using Apache + Tomcat + mod_JK connector then you also need to do following changes:

  1. Add URIEncoding="UTF-8" into tomcat server.xml file for 8009 connector, it is used by mod_JK connector. <Connector port="8009" protocol="AJP/1.3" redirectPort="8443" URIEncoding="UTF-8"/>
  2. Goto your apache folder i.e. /etc/httpd/conf and add AddDefaultCharset utf-8 in httpd.conf file. Note: First check that it is exist or not. If exist you may update it with this line. You can add this line at bottom also.

Making authenticated POST requests with Spring RestTemplate for Android

Slightly different approach:

MultiValueMap<String, String> headers = new LinkedMultiValueMap<String, String>();
headers.add("HeaderName", "value");
headers.add("Content-Type", "application/json");

RestTemplate restTemplate = new RestTemplate();
restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());

HttpEntity<ObjectToPass> request = new HttpEntity<ObjectToPass>(objectToPass, headers);

restTemplate.postForObject(url, request, ClassWhateverYourControllerReturns.class);

How to control size of list-style-type disc in CSS?

I have always had good luck with using background images instead of trusting all browsers to interpret the bullet in exactly the same way. This would also give you tight control over the size of the bullet.

.moreLinks li {
    background: url("bullet.gif") no-repeat left 5px;
    padding-left: 1em;
}

Also, you may want to move your DIV outside of the UL. It's invalid markup as you have it now. You can use a list header LH if you must have it inside the list.

Verify object attribute value with mockito

And very nice and clean solution in koltin from com.nhaarman.mockito_kotlin

verify(mock).execute(argThat {
    this.param = expected
})

Smooth scrolling with just pure css

You need to use the target selector.

Here is a fiddle with another example: http://jsfiddle.net/YYPKM/3/

jQuery textbox change event doesn't fire until textbox loses focus?

if you write anything in your textbox, the event gets fired.
code as follows :

HTML:

<input type="text" id="textbox" />

JS:

<script type="text/javascript">
  $(function () {
      $("#textbox").bind('input', function() {
      alert("letter entered");
      });
   });
</script>

Get array of object's keys

If you decide to use Underscore.js you better do

var foo = { 'alpha' : 'puffin', 'beta' : 'beagle' };
var keys = [];
_.each( foo, function( val, key ) {
    keys.push(key);
});
console.log(keys);

Execute a terminal command from a Cocoa app

You can use NSTask. Here's an example that would run '/usr/bin/grep foo bar.txt'.

int pid = [[NSProcessInfo processInfo] processIdentifier];
NSPipe *pipe = [NSPipe pipe];
NSFileHandle *file = pipe.fileHandleForReading;

NSTask *task = [[NSTask alloc] init];
task.launchPath = @"/usr/bin/grep";
task.arguments = @[@"foo", @"bar.txt"];
task.standardOutput = pipe;

[task launch];

NSData *data = [file readDataToEndOfFile];
[file closeFile];

NSString *grepOutput = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding];
NSLog (@"grep returned:\n%@", grepOutput);

NSPipe and NSFileHandle are used to redirect the standard output of the task.

For more detailed information on interacting with the operating system from within your Objective-C application, you can see this document on Apple's Development Center: Interacting with the Operating System.

Edit: Included fix for NSLog problem

If you are using NSTask to run a command-line utility via bash, then you need to include this magic line to keep NSLog working:

//The magic line that keeps your log where it belongs
task.standardOutput = pipe;

An explanation is here: https://web.archive.org/web/20141121094204/https://cocoadev.com/HowToPipeCommandsWithNSTask

What is the simplest method of inter-process communication between 2 C# processes?

There's also MSMQ (Microsoft Message Queueing) which can operate across networks as well as on a local computer. Although there are better ways to communicate it's worth looking into: https://msdn.microsoft.com/en-us/library/ms711472(v=vs.85).aspx

Formatting a number with exactly two decimals in JavaScript

Put the following in some global scope:

Number.prototype.getDecimals = function ( decDigCount ) {
   return this.toFixed(decDigCount);
}

and then try:

var a = 56.23232323;
a.getDecimals(2); // will return 56.23

Update

Note that toFixed() can only work for the number of decimals between 0-20 i.e. a.getDecimals(25) may generate a javascript error, so to accomodate that you may add some additional check i.e.

Number.prototype.getDecimals = function ( decDigCount ) {
   return ( decDigCount > 20 ) ? this : this.toFixed(decDigCount);
}

Get month name from date in Oracle

If you are trying to pull the value from a field, you could use:

select extract(month from [field_name])
from [table_name]

You can also insert day or year for the "month" extraction value above.

Replace deprecated preg_replace /e with preg_replace_callback

You can use an anonymous function to pass the matches to your function:

$result = preg_replace_callback(
    "/\{([<>])([a-zA-Z0-9_]*)(\?{0,1})([a-zA-Z0-9_]*)\}(.*)\{\\1\/\\2\}/isU",
    function($m) { return CallFunction($m[1], $m[2], $m[3], $m[4], $m[5]); },
    $result
);

Apart from being faster, this will also properly handle double quotes in your string. Your current code using /e would convert a double quote " into \".

PHP function ssh2_connect is not working

Honestly, I'd recommend using phpseclib, a pure PHP SSH2 implementation. Example:

<?php
include('Net/SSH2.php');

$ssh = new Net_SSH2('www.domain.tld');
if (!$ssh->login('username', 'password')) {
    exit('Login Failed');
}

echo $ssh->exec('pwd');
echo $ssh->exec('ls -la');
?>

It's a ton more portable, easier to use and more feature packed too.

How to pause in C?

If you are making a console window program, you can use system("pause");

Simple excel find and replace for formulas

The way I typically handle this is with a second piece of software. For Windows I use Notepad++, for OS X I use Sublime Text 2.

  1. In Excel, hit Control + ~ (OS X)
  2. Excel will convert all values to their formula version
  3. CMD + A (I usually do this twice) to select the entire sheet
  4. Copy all contents and paste them into Notepad++/Sublime Text 2
  5. Find / Replace your formula contents here
  6. Copy the contents and paste back into Excel, confirming any issues about cell size differences
  7. Control + ~ to switch back to values mode

The network adapter could not establish the connection - Oracle 11g

First check your listener is on or off. Go to net manager then Local -> service naming -> orcl. Then change your HOST NAME and put your PC name. Now go to LISTENER and change the HOST and put your PC name.