Programs & Examples On #Visualization

Visualization is any technique for creating images, diagrams, or animations to communicate a message.

How do you change the size of figures drawn with matplotlib?

The first link in Google for 'matplotlib figure size' is AdjustingImageSize (Google cache of the page).

Here's a test script from the above page. It creates test[1-3].png files of different sizes of the same image:

#!/usr/bin/env python
"""
This is a small demo file that helps teach how to adjust figure sizes
for matplotlib

"""

import matplotlib
print "using MPL version:", matplotlib.__version__
matplotlib.use("WXAgg") # do this before pylab so you don'tget the default back end.

import pylab
import numpy as np

# Generate and plot some simple data:
x = np.arange(0, 2*np.pi, 0.1)
y = np.sin(x)

pylab.plot(x,y)
F = pylab.gcf()

# Now check everything with the defaults:
DPI = F.get_dpi()
print "DPI:", DPI
DefaultSize = F.get_size_inches()
print "Default size in Inches", DefaultSize
print "Which should result in a %i x %i Image"%(DPI*DefaultSize[0], DPI*DefaultSize[1])
# the default is 100dpi for savefig:
F.savefig("test1.png")
# this gives me a 797 x 566 pixel image, which is about 100 DPI

# Now make the image twice as big, while keeping the fonts and all the
# same size
F.set_size_inches( (DefaultSize[0]*2, DefaultSize[1]*2) )
Size = F.get_size_inches()
print "Size in Inches", Size
F.savefig("test2.png")
# this results in a 1595x1132 image

# Now make the image twice as big, making all the fonts and lines
# bigger too.

F.set_size_inches( DefaultSize )# resetthe size
Size = F.get_size_inches()
print "Size in Inches", Size
F.savefig("test3.png", dpi = (200)) # change the dpi
# this also results in a 1595x1132 image, but the fonts are larger.

Output:

using MPL version: 0.98.1
DPI: 80
Default size in Inches [ 8.  6.]
Which should result in a 640 x 480 Image
Size in Inches [ 16.  12.]
Size in Inches [ 16.  12.]

Two notes:

  1. The module comments and the actual output differ.

  2. This answer allows easily to combine all three images in one image file to see the difference in sizes.

How to combine 2 plots (ggplot) into one plot?

Dummy data (you should supply this for us)

visual1 = data.frame(ISSUE_DATE=runif(100,2006,2008),COUNTED=runif(100,0,50))
visual2 = data.frame(ISSUE_DATE=runif(100,2006,2008),COUNTED=runif(100,0,50))

combine:

visuals = rbind(visual1,visual2)
visuals$vis=c(rep("visual1",100),rep("visual2",100)) # 100 points of each flavour

Now do:

 ggplot(visuals, aes(ISSUE_DATE,COUNTED,group=vis,col=vis)) + 
   geom_point() + geom_smooth()

and adjust colours etc to taste.

enter image description here

3D Plotting from X, Y, Z Data, Excel or other Tools

You also can use Gnuplot which is also available from gretl. Put your x y z data on a text file an insert the following

splot 'test.txt' using 1:2:3 with points palette pointsize 3 pointtype 7

Then you can set labels, etc. using

set xlabel "xxx" rotate parallel
set ylabel "yyy" rotate parallel
set zlabel "zzz" rotate parallel
set grid
show grid
unset key

How to plot a histogram using Matplotlib in Python with a list of data?

This is an old question but none of the previous answers has addressed the real issue, i.e. that fact that the problem is with the question itself.

First, if the probabilities have been already calculated, i.e. the histogram aggregated data is available in a normalized way then the probabilities should add up to 1. They obviously do not and that means that something is wrong here, either with terminology or with the data or in the way the question is asked.

Second, the fact that the labels are provided (and not intervals) would normally mean that the probabilities are of categorical response variable - and a use of a bar plot for plotting the histogram is best (or some hacking of the pyplot's hist method), Shayan Shafiq's answer provides the code.

However, see issue 1, those probabilities are not correct and using bar plot in this case as "histogram" would be wrong because it does not tell the story of univariate distribution, for some reason (perhaps the classes are overlapping and observations are counted multiple times?) and such plot should not be called a histogram in this case.

Histogram is by definition a graphical representation of the distribution of univariate variable (see Histogram | NIST/SEMATECH e-Handbook of Statistical Methods & Histogram | Wikipedia) and is created by drawing bars of sizes representing counts or frequencies of observations in selected classes of the variable of interest. If the variable is measured on a continuous scale those classes are bins (intervals). Important part of histogram creation procedure is making a choice of how to group (or keep without grouping) the categories of responses for a categorical variable, or how to split the domain of possible values into intervals (where to put the bin boundaries) for continuous type variable. All observations should be represented, and each one only once in the plot. That means that the sum of the bar sizes should be equal to the total count of observation (or their areas in case of the variable widths, which is a less common approach). Or, if the histogram is normalised then all probabilities must add up to 1.

If the data itself is a list of "probabilities" as a response, i.e. the observations are probability values (of something) for each object of study then the best answer is simply plt.hist(probability) with maybe binning option, and use of x-labels already available is suspicious.

Then bar plot should not be used as histogram but rather simply

import matplotlib.pyplot as plt
probability = [0.3602150537634409, 0.42028985507246375, 
  0.373117033603708, 0.36813186813186816, 0.32517482517482516, 
  0.4175257731958763, 0.41025641025641024, 0.39408866995073893, 
  0.4143222506393862, 0.34, 0.391025641025641, 0.3130841121495327, 
  0.35398230088495575]
plt.hist(probability)
plt.show()

with the results

enter image description here

matplotlib in such case arrives by default with the following histogram values

(array([1., 1., 1., 1., 1., 2., 0., 2., 0., 4.]),
 array([0.31308411, 0.32380469, 0.33452526, 0.34524584, 0.35596641,
        0.36668698, 0.37740756, 0.38812813, 0.39884871, 0.40956928,
        0.42028986]),
 <a list of 10 Patch objects>)

the result is a tuple of arrays, the first array contains observation counts, i.e. what will be shown against the y-axis of the plot (they add up to 13, total number of observations) and the second array are the interval boundaries for x-axis.

One can check they they are equally spaced,

x = plt.hist(probability)[1]
for left, right in zip(x[:-1], x[1:]):
  print(left, right, right-left)

enter image description here

Or, for example for 3 bins (my judgment call for 13 observations) one would get this histogram

plt.hist(probability, bins=3)

enter image description here

with the plot data "behind the bars" being

enter image description here

The author of the question needs to clarify what is the meaning of the "probability" list of values - is the "probability" just a name of the response variable (then why are there x-labels ready for the histogram, it makes no sense), or are the list values the probabilities calculated from the data (then the fact they do not add up to 1 makes no sense).

plot different color for different categorical levels using matplotlib

You can convert the categorical column into a numerical one by using the commands:

#we converting it into categorical data
cat_col = df['column_name'].astype('categorical') 

#we are getting codes for it 
cat_col = cat_col.cat.codes 

# we are using c parameter to change the color.
plt.scatter(df['column1'],df['column2'], c=cat_col) 

Side-by-side plots with ggplot2

The above solutions may not be efficient if you want to plot multiple ggplot plots using a loop (e.g. as asked here: Creating multiple plots in ggplot with different Y-axis values using a loop), which is a desired step in analyzing the unknown (or large) data-sets (e.g., when you want to plot Counts of all variables in a data-set).

The code below shows how to do that using the mentioned above 'multiplot()', the source of which is here: http://www.cookbook-r.com/Graphs/Multiple_graphs_on_one_page_(ggplot2):

plotAllCounts <- function (dt){   
  plots <- list();
  for(i in 1:ncol(dt)) {
    strX = names(dt)[i]
    print(sprintf("%i: strX = %s", i, strX))
    plots[[i]] <- ggplot(dt) + xlab(strX) +
      geom_point(aes_string(strX),stat="count")
  }

  columnsToPlot <- floor(sqrt(ncol(dt)))
  multiplot(plotlist = plots, cols = columnsToPlot)
}

Now run the function - to get Counts for all variables printed using ggplot on one page

dt = ggplot2::diamonds
plotAllCounts(dt)

One things to note is that:
using aes(get(strX)), which you would normally use in loops when working with ggplot , in the above code instead of aes_string(strX) will NOT draw the desired plots. Instead, it will plot the last plot many times. I have not figured out why - it may have to do the aes and aes_string are called in ggplot.

Otherwise, hope you'll find the function useful.

Good tool to visualise database schema?

I'm start to create own Perl script based on SQL::Translator module (GraphViz). Here are first results.

Why do many examples use `fig, ax = plt.subplots()` in Matplotlib/pyplot/python

Just a supplement here.

The following question is that what if I want more subplots in the figure?

As mentioned in the Doc, we can use fig = plt.subplots(nrows=2, ncols=2) to set a group of subplots with grid(2,2) in one figure object.

Then as we know, the fig, ax = plt.subplots() returns a tuple, let's try fig, ax1, ax2, ax3, ax4 = plt.subplots(nrows=2, ncols=2) firstly.

ValueError: not enough values to unpack (expected 4, got 2)

It raises a error, but no worry, because we now see that plt.subplots() actually returns a tuple with two elements. The 1st one must be a figure object, and the other one should be a group of subplots objects.

So let's try this again:

fig, [[ax1, ax2], [ax3, ax4]] = plt.subplots(nrows=2, ncols=2)

and check the type:

type(fig) #<class 'matplotlib.figure.Figure'>
type(ax1) #<class 'matplotlib.axes._subplots.AxesSubplot'>

Of course, if you use parameters as (nrows=1, ncols=4), then the format should be:

fig, [ax1, ax2, ax3, ax4] = plt.subplots(nrows=1, ncols=4)

So just remember to keep the construction of the list as the same as the subplots grid we set in the figure.

Hope this would be helpful for you.

How can I create a correlation matrix in R?

You could use 'corrplot' package.

d <- data.frame(x1=rnorm(10),
                 x2=rnorm(10),
                 x3=rnorm(10))
M <- cor(d) # get correlations

library('corrplot') #package corrplot
corrplot(M, method = "circle") #plot matrix

enter image description here

More information here: http://cran.r-project.org/web/packages/corrplot/vignettes/corrplot-intro.html

Visualizing decision tree in scikit-learn

If, like me, you have a problem installing graphviz, you can visualize the tree by

  1. exporting it with export_graphviz as shown in previous answers
  2. Open the .dot file in a text editor
  3. Copy the piece of code and paste it @ webgraphviz.com

How to print object array in JavaScript?

There is a wonderful print_r implementation for JavaScript in php.js library.

Note, you should also add echo support in the code.

DEMO: http://jsbin.com/esexiw/1

What is the difference between for and foreach?

You can use the foreach for an simple array like

int[] test = { 0, 1, 2, 3, ...};

And you can use the for when you have a 2D array

int[][] test = {{1,2,3,4},
                {5,2,6,5,8}};

What is the most efficient way to get first and last line of a text file?

Nobody mentioned using reversed:

f=open(file,"r")
r=reversed(f.readlines())
last_line_of_file = r.next()

tkinter: Open a new window with a button prompt

Here's the nearly shortest possible solution to your question. The solution works in python 3.x. For python 2.x change the import to Tkinter rather than tkinter (the difference being the capitalization):

import tkinter as tk
#import Tkinter as tk  # for python 2
    
def create_window():
    window = tk.Toplevel(root)

root = tk.Tk()
b = tk.Button(root, text="Create new window", command=create_window)
b.pack()

root.mainloop()

This is definitely not what I recommend as an example of good coding style, but it illustrates the basic concepts: a button with a command, and a function that creates a window.

Open File in Another Directory (Python)

from pathlib import Path

data_folder = Path("source_data/text_files/")
file_to_open = data_folder / "raw_data.txt"

f = open(file_to_open)
print(f.read())

How to update column value in laravel

Version 1:

// Update data of question values with $data from formulay
$Q1 = Question::find($id);
$Q1->fill($data);
$Q1->push();

Version 2:

$Q1 = Question::find($id);
$Q1->field = 'YOUR TEXT OR VALUE';
$Q1->save();

In case of answered question you can use them:

$page = Page::find($id);
$page2update = $page->where('image', $path);
$page2update->image = 'IMGVALUE';
$page2update->save();

Detect WebBrowser complete page loading

You can use the event ProgressChanged ; the last time it is raised will indicate that the document is fully rendered:

this.webBrowser.ProgressChanged += new
WebBrowserProgressChangedEventHandler(webBrowser_ProgressChanged);

How do I revert an SVN commit?

svn merge -r 1944:1943 . should revert the changes of r1944 in your working copy. You can then review the changes in your working copy (with diff), but you'd need to commit in order to apply the revert into the repository.

Is there a method that tells my program to quit?

See sys.exit. That function will quit your program with the given exit status.

Support for ES6 in Internet Explorer 11

The statement from Microsoft regarding the end of Internet Explorer 11 support mentions that it will continue to receive security updates, compatibility fixes, and technical support until its end of life. The wording of this statement leads me to believe that Microsoft has no plans to continue adding features to Internet Explorer 11, and instead will be focusing on Edge.

If you require ES6 features in Internet Explorer 11, check out a transpiler such as Babel.

MySQL with Node.js

Imo, you should try MySQL Connector/Node.js which is the official Node.js driver for MySQL. See ref-1 and ref-2 for detailed explanation. I have tried mysqljs/mysql which is available here, but I don't find detailed documentation on classes, methods, properties of this library.

So I switched to the standard MySQL Connector/Node.js with X DevAPI, since it is an asynchronous Promise-based client library and provides good documentation. Take a look at the following code snippet :

const mysqlx = require('@mysql/xdevapi');
const rows = [];

mysqlx.getSession('mysqlx://localhost:33060')
.then(session => {
    const table = session.getSchema('testSchema').getTable('testTable');

    // The criteria is defined through the expression.
    return table.update().where('name = "bar"').set('age', 50)
        .execute()
        .then(() => {
            return table.select().orderBy('name ASC')
                .execute(row => rows.push(row));
        });
})
.then(() => {
    console.log(rows);
});

How do I determine if a checkbox is checked?

_x000D_
_x000D_
var elementCheckBox = document.getElementById("IdOfCheckBox");_x000D_
_x000D_
_x000D_
elementCheckBox[0].checked //return true if checked and false if not checked
_x000D_
_x000D_
_x000D_

thanks

Bash script processing limited number of commands in parallel

Use the wait built-in:

process1 &
process2 &
process3 &
process4 &
wait
process5 &
process6 &
process7 &
process8 &
wait

For the above example, 4 processes process1 ... process4 would be started in the background, and the shell would wait until those are completed before starting the next set.

From the GNU manual:

wait [jobspec or pid ...]

Wait until the child process specified by each process ID pid or job specification jobspec exits and return the exit status of the last command waited for. If a job spec is given, all processes in the job are waited for. If no arguments are given, all currently active child processes are waited for, and the return status is zero. If neither jobspec nor pid specifies an active child process of the shell, the return status is 127.

SQL server query to get the list of columns in a table along with Data types, NOT NULL, and PRIMARY KEY constraints

select
      c.name as [column name], 
      t.name as [type name],
      tbl.name as [table name]
from sys.columns c
         inner join sys.types t 
      on c.system_type_id = t.system_type_id 
         inner join sys.tables tbl
      on c.object_id = tbl.object_id
where
      c.object_id = OBJECT_ID('YourTableName1') 
          and 
      t.name like '%YourSearchDataType%'
union
(select
      c.name as [column name], 
      t.name as [type name],
      tbl.name as [table name]
from sys.columns c
         inner join sys.types t 
      on c.system_type_id = t.system_type_id 
         inner join sys.tables tbl
      on c.object_id = tbl.object_id
where
      c.object_id = OBJECT_ID('YourTableName2') 
          and 
      t.name like '%YourSearchDataType%')
union
(select
      c.name as [column name], 
      t.name as [type name],
      tbl.name as [table name]
from sys.columns c
         inner join sys.types t 
      on c.system_type_id = t.system_type_id 
         inner join sys.tables tbl
      on c.object_id = tbl.object_id
where
      c.object_id = OBJECT_ID('YourTableName3') 
          and 
      t.name like '%YourSearchDataType%')
order by tbl.name

To search which column is in which table based on your search data type for three different table in one database. This query is expandable to 'n' tables.

How to truncate the time on a DateTime object in Python?

You could use pandas for that (although it could be overhead for that task). You could use round, floor and ceil like for usual numbers and any pandas frequency from offset-aliases:

import pandas as pd
import datetime as dt

now = dt.datetime.now()
pd_now = pd.Timestamp(now)

freq = '1d'
pd_round = pd_now.round(freq)
dt_round = pd_round.to_pydatetime()

print(now)
print(dt_round)

"""
2018-06-15 09:33:44.102292
2018-06-15 00:00:00
"""

How to use AND in IF Statement

If there are no typos in the question, you got the conditions wrong:

You said this:

IF cells (i,"A") contains the text 'Miami'

...but your code says:

If Cells(i, "A") <> "Miami"

--> <> means that the value of the cell is not equal to "Miami", so you're not checking what you think you are checking.

I guess you want this instead:

If Cells(i, "A") like "*Miami*"

EDIT:

Sorry, but I can't really help you more. As I already said in a comment, I'm no Excel VBA expert.
Normally I would open Excel now and try your code myself, but I don't even have Excel on any of my machines at home (I use OpenOffice).

Just one general thing: can you identify the row that does not work?
Maybe this helps someone else to answer the question.

Does it ever execute (or at least try to execute) the Cells(i, "C").Value = "BA" line?
Or is the If Cells(i, "A") like "*Miami*" stuff already False?
If yes, try checking just one cell and see if that works.

How to send control+c from a bash script?

You can get the PID of a particular process like MySQL by using following commands: ps -e | pgrep mysql

This command will give you the PID of MySQL rocess. e.g, 13954 Now, type following command on terminal. kill -9 13954 This will kill the process of MySQL.

Microsoft Visual C++ Compiler for Python 3.4

For the different python versions:

Visual C++ |CPython
--------------------
14.0       |3.5
10.0       |3.3, 3.4
9.0        |2.6, 2.7, 3.0, 3.1, 3.2

Source: Windows Compilers for py

Also refer: this answer

PostgreSQL Crosstab Query

Solution with JSON aggregation:

CREATE TEMP TABLE t (
  section   text
, status    text
, ct        integer  -- don't use "count" as column name.
);

INSERT INTO t VALUES 
  ('A', 'Active', 1), ('A', 'Inactive', 2)
, ('B', 'Active', 4), ('B', 'Inactive', 5)
                   , ('C', 'Inactive', 7); 


SELECT section,
       (obj ->> 'Active')::int AS active,
       (obj ->> 'Inactive')::int AS inactive
FROM (SELECT section, json_object_agg(status,ct) AS obj
      FROM t
      GROUP BY section
     )X

Send email using java

Try this out. it works well for me. Make sure that before send email u need to give the access for less secure app in your gmail account. So go to the following link and try out with this java code.
Activate gmail for less secure app

You need to import javax.mail.jar file and activation.jar file to your project.

This is the full code for send email in java

import javax.mail.*;
import javax.mail.internet.*;
import java.util.*;

public class SendEmail {

    final String senderEmail = "your email address";
    final String senderPassword = "your password";
    final String emailSMTPserver = "smtp.gmail.com";
    final String emailServerPort = "587";
    String receiverEmail = null;
    String emailSubject = null;
    String emailBody = null;

    public SendEmail(String receiverEmail, String Subject, String message) {
        this.receiverEmail = receiverEmail;
        this.emailSubject = Subject;
        this.emailBody = message;

        Properties props = new Properties();
        props.put("mail.smtp.user", senderEmail);
        props.put("mail.smtp.host", emailSMTPserver);
        props.put("mail.smtp.port", emailServerPort);
        props.put("mail.smtp.starttls.enable", "true");
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.socketFactory.port", emailServerPort);
        props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");

        SecurityManager security = System.getSecurityManager();

        try {
            Authenticator auth = new SMTPAuthenticator();
            Session session = Session.getInstance(props, auth);

            Message msg = new MimeMessage(session);
            msg.setText(emailBody);
            msg.setSubject(emailSubject);
            msg.setFrom(new InternetAddress(senderEmail));
            msg.addRecipient(Message.RecipientType.TO,
                    new InternetAddress(receiverEmail));
            Transport.send(msg);
            System.out.println("send successfully");
        } catch (Exception ex) {
            System.err.println("Error occurred while sending.!");
        }

    }

    private class SMTPAuthenticator extends javax.mail.Authenticator {

        public PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(senderEmail, senderPassword);
        }
    }

    public static void main(String[] args) {
        SendEmail send = new SendEmail("receiver email address", "subject", "message");
    }

}

Git merge two local branches

on branchB do $git checkout branchA to switch to branch A

on branchA do $git merge branchB

That's all you need.

Call PHP function from Twig template

Its not possible to access any PHP function inside Twig directly.

What you can do is write a Twig extension. A common structure is, writing a service with some utility functions, write a Twig extension as bridge to access the service from twig. The Twig extension will use the service and your controller can use the service too.

Take a look: http://symfony.com/doc/current/cookbook/templating/twig_extension.html

Cheers.

How to add new column to MYSQL table?

Something like:

$db = mysqli_connect("localhost", "user", "password", "database");
$name = $db->mysqli_real_escape_string($name);
$query = 'ALTER TABLE assesment ADD ' . $name . ' TINYINT NOT NULL DEFAULT \'0\'';
if($db->query($query)) {
    echo "It worked";
}

Haven't tested it but should work.

Refresh/reload the content in Div using jquery/ajax

I always use this, works perfect.

$(document).ready(function(){
        $(function(){
        $('#ideal_form').submit(function(e){
                e.preventDefault();
                var form = $(this);
                var post_url = form.attr('action');
                var post_data = form.serialize();
                $('#loader3', form).html('<img src="../../images/ajax-loader.gif" />       Please wait...');
                $.ajax({
                    type: 'POST',
                    url: post_url, 
                    data: post_data,
                    success: function(msg) {
                        $(form).fadeOut(800, function(){
                            form.html(msg).fadeIn().delay(2000);

                        });
                    }
                });
            });
        });
         });

How to differ sessions in browser-tabs?

I see many implementations which have client side changes to manipulate session id cookies. But in general session id cookies should be HttpOnly so java-script cannot access otherwise it may lead to Session Hijack thru XSS

jQuery select2 get value of select tag?

Solution :

var my_veriable = $('#your_select2_id').select2().val();
var my_last_veriable = my_veriable.toString();

Ruby optional parameters

Time has moved on and since version 2 Ruby supports named parameters:

def ldap_get ( base_dn, filter, scope: "some_scope", attrs: nil )
  p attrs
end

ldap_get("first_arg", "second_arg", attrs: "attr1, attr2") # => "attr1, attr2"

How to push a new folder (containing other folders and files) to an existing git repo?

You can directly go to Web IDE and upload your folder there.

Steps:

  1. Go to Web IDE(Mostly located below the clone option).
  2. Create new directory at your path
  3. Upload your files and folders

In some cases you may not be able to directly upload entire folder containing folders, In such cases, you will have to create directory structure yourself.

What is difference between Axios and Fetch?

One more major difference between fetch API & axios API

  • While using service worker, you have to use fetch API only if you want to intercept the HTTP request
  • Ex. While performing caching in PWA using service worker you won't be able to cache if you are using axios API (it works only with fetch API)

Inline IF Statement in C#

You can do inline ifs with

return y == 20 ? 1 : 2;

which will give you 1 if true and 2 if false.

Linq to Entities join vs groupjoin

According to eduLINQ:

The best way to get to grips with what GroupJoin does is to think of Join. There, the overall idea was that we looked through the "outer" input sequence, found all the matching items from the "inner" sequence (based on a key projection on each sequence) and then yielded pairs of matching elements. GroupJoin is similar, except that instead of yielding pairs of elements, it yields a single result for each "outer" item based on that item and the sequence of matching "inner" items.

The only difference is in return statement:

Join:

var lookup = inner.ToLookup(innerKeySelector, comparer); 
foreach (var outerElement in outer) 
{ 
    var key = outerKeySelector(outerElement); 
    foreach (var innerElement in lookup[key]) 
    { 
        yield return resultSelector(outerElement, innerElement); 
    } 
} 

GroupJoin:

var lookup = inner.ToLookup(innerKeySelector, comparer); 
foreach (var outerElement in outer) 
{ 
    var key = outerKeySelector(outerElement); 
    yield return resultSelector(outerElement, lookup[key]); 
} 

Read more here:

how to set "camera position" for 3d plots using python/matplotlib?

Minimal example varying azim, dist and elev

To add some simple sample images to what was explained at: https://stackoverflow.com/a/12905458/895245

Here is my test program:

#!/usr/bin/env python3

import sys

import matplotlib.pyplot as plt
from matplotlib import cm
from matplotlib.ticker import LinearLocator, FormatStrFormatter
import numpy as np

fig = plt.figure()
ax = fig.gca(projection='3d')

if len(sys.argv) > 1:
    azim = int(sys.argv[1])
else:
    azim = None
if len(sys.argv) > 2:
    dist = int(sys.argv[2])
else:
    dist = None
if len(sys.argv) > 3:
    elev = int(sys.argv[3])
else:
    elev = None

# Make data.
X = np.arange(-5, 6, 1)
Y = np.arange(-5, 6, 1)
X, Y = np.meshgrid(X, Y)
Z = X**2

# Plot the surface.
surf = ax.plot_surface(X, Y, Z, linewidth=0, antialiased=False)

# Labels.
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.set_zlabel('z')

if azim is not None:
    ax.azim = azim
if dist is not None:
    ax.dist = dist
if elev is not None:
    ax.elev = elev

print('ax.azim = {}'.format(ax.azim))
print('ax.dist = {}'.format(ax.dist))
print('ax.elev = {}'.format(ax.elev))

plt.savefig(
    'main_{}_{}_{}.png'.format(ax.azim, ax.dist, ax.elev),
    format='png',
    bbox_inches='tight'
)

Running it without arguments gives the default values:

ax.azim = -60
ax.dist = 10
ax.elev = 30

main_-60_10_30.png

enter image description here

Vary azim

The azimuth is the rotation around the z axis e.g.:

  • 0 means "looking from +x"
  • 90 means "looking from +y"

main_-60_10_30.png

enter image description here

main_0_10_30.png

enter image description here

main_60_10_30.png

enter image description here

Vary dist

dist seems to be the distance from the center visible point in data coordinates.

main_-60_10_30.png

enter image description here

main_-60_5_30.png

enter image description here

main_-60_20_-30.png

enter image description here

Vary elev

From this we understand that elev is the angle between the eye and the xy plane.

main_-60_10_60.png

enter image description here

main_-60_10_30.png

enter image description here

main_-60_10_0.png

enter image description here

main_-60_10_-30.png

enter image description here

Tested on matpotlib==3.2.2.

sys.argv[1] meaning in script

sys.argv[1] contains the first command line argument passed to your script.

For example, if your script is named hello.py and you issue:

$ python3.1 hello.py foo

or:

$ chmod +x hello.py  # make script executable
$ ./hello.py foo

Your script will print:

Hello there foo

New Line Issue when copying data from SQL Server 2012 to Excel

  • If your table contains an nvarchar(max) field move that field to the bottom of your table.
  • In the event the field type is different to nvarchar(max), then identify the offending field or fields and use this same technique.
  • Save It.
  • Reselect the Table in SQL.
  • If you cant save without an alter you can temporarily turn of relevant warnings in TOOLS | OPTIONS. This method carries no risk.
  • Copy and Paste the SQL GRID display with Headers to Excel.
  • The data may still exhibit a carriage return but at least your data is all on the same row.
  • Then select all row records and do a custom sort on the ID column.
  • All of your records should now be intact and consecutive.

When and how should I use a ThreadLocal variable?

There are 3 scenarios for using a class helper like SimpleDateFormat in multithread code, which best one is use ThreadLocal

Scenarios

1- Using like share object by the help of lock or synchronization mechanism which makes the app slow

2- Using as a local object inside a method

In this scenario, if we have 4 thread each one calls a method 1000 time then we have
4000 SimpleDateFormat object created and waiting for GC to erase them

3- Using ThreadLocal

if we have 4 thread and we gave to each thread one SimpleDateFormat instance
so we have 4 threads, 4 objects of SimpleDateFormat.

There is no need of lock mechanism and object creation and destruction. (Good time complexity and space complexity)

Getting Class type from String

You can get the Class reference of any class during run time through the Java Reflection Concept.

Check the Below Code. Explanation is given below

Here is one example that uses returned Class to create an instance of AClass:

package com.xyzws;
class AClass {
    public AClass() {
        System.out.println("AClass's Constructor"); 
    }  
    static {   
        System.out.println("static block in AClass");  
    }
}
public class Program {   
    public static void main(String[] args) {
        try {       
            System.out.println("The first time calls forName:");   
            Class c = Class.forName("com.xyzws.AClass");      
            AClass a = (AClass)c.newInstance();    
            System.out.println("The second time calls forName:");  
            Class c1 = Class.forName("com.xyzws.AClass"); 
        } catch (ClassNotFoundException e) { 
            // ...
        } catch (InstantiationException e) {  
            // ...
        } catch (IllegalAccessException e) { 
            // ...
        }     
    }
}

The printed output is

    The first time calls forName:
    static block in AClass
    AClass's Constructor
    The second time calls forName:

The class has already been loaded so there is no second "static block in AClass"

The Explanation is below

Class.ForName is called to get a Class Object

By Using the Class Object we are creating the new instance of the Class.

Any doubts about this let me know

How do I position an image at the bottom of div?

Add relative positioning to the wrapping div tag, then absolutely position the image within it like this:

CSS:

.div-wrapper {
    position: relative;
    height: 300px;
    width: 300px;
}

.div-wrapper img {
    position: absolute;
    left: 0;
    bottom: 0;
}

HTML:

<div class="div-wrapper">
    <img src="blah.png"/>
</div>

Now the image sits at the bottom of the div.

How to use bootstrap datepicker

Just add this below JS file

<script type="text/javascript">
    $(document).ready(function () {
        $('your input's id or class with # or .').datepicker({
            format: "dd/mm/yyyy"
        });
    });
</script>

django: TypeError: 'tuple' object is not callable

You're missing comma (,) inbetween:

>>> ((1,2) (2,3))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'tuple' object is not callable

Put comma:

>>> ((1,2), (2,3))
((1, 2), (2, 3))

Make a URL-encoded POST request using `http.NewRequest(...)`

URL-encoded payload must be provided on the body parameter of the http.NewRequest(method, urlStr string, body io.Reader) method, as a type that implements io.Reader interface.

Based on the sample code:

package main

import (
    "fmt"
    "net/http"
    "net/url"
    "strconv"
    "strings"
)

func main() {
    apiUrl := "https://api.com"
    resource := "/user/"
    data := url.Values{}
    data.Set("name", "foo")
    data.Set("surname", "bar")

    u, _ := url.ParseRequestURI(apiUrl)
    u.Path = resource
    urlStr := u.String() // "https://api.com/user/"

    client := &http.Client{}
    r, _ := http.NewRequest(http.MethodPost, urlStr, strings.NewReader(data.Encode())) // URL-encoded payload
    r.Header.Add("Authorization", "auth_token=\"XXXXXXX\"")
    r.Header.Add("Content-Type", "application/x-www-form-urlencoded")
    r.Header.Add("Content-Length", strconv.Itoa(len(data.Encode())))

    resp, _ := client.Do(r)
    fmt.Println(resp.Status)
}

resp.Status is 200 OK this way.

getting JRE system library unbound error in build path

oh boy, this got resolved, I just had to name my Installed JRE appropriately. I had only the jdk installed and eclipse had taken the default jdk name, i renamed it to JavaSE-1.6 and voila it worked, though i had to redo everthing from the scratch.

How do I make the first letter of a string uppercase in JavaScript?

You can do it in one line like this

string[0].toUpperCase() + string.substring(1)

Conditional WHERE clause in SQL Server

This seemed easier to think about where either of two parameters could be passed into a stored procedure. It seems to work:

SELECT * 
FROM x 
WHERE CONDITION1
AND ((@pol IS NOT NULL AND x.PolicyNo = @pol) OR (@st IS NOT NULL AND x.State = @st))
AND OTHERCONDITIONS

How to include a sub-view in Blade templates?

EDIT: Below was the preferred solution in 2014. Nowadays you should use @include, as mentioned in the other answer.


In Laravel views the dot is used as folder separator. So for example I have this code

return View::make('auth.details', array('id' => $id));

which points to app/views/auth/details.blade.php

And to include a view inside a view you do like this:

file: layout.blade.php

<html>
  <html stuff>
  @yield('content')
</html>

file: hello.blade.php

@extends('layout')

@section('content')
  <html stuff>
@stop

Min width in window resizing

You can set min-width property of CSS for body tag. Since this property is not supported by IE6, you can write like:

body{
   min-width:1000px;        /* Suppose you want minimum width of 1000px */
   width: auto !important;  /* Firefox will set width as auto */
   width:1000px;            /* As IE6 ignores !important it will set width as 1000px; */
}

Or:

body{
   min-width:1000px; // Suppose you want minimum width of 1000px
   _width: expression( document.body.clientWidth > 1000 ? "1000px" : "auto" ); /* sets max-width for IE6 */
}

How to test abstract class in Java with JUnit?

With the example class you posted it doesn't seem to make much sense to test getFuel() and getSpeed() since they can only return 0 (there are no setters).

However, assuming that this was just a simplified example for illustrative purposes, and that you have legitimate reasons to test methods in the abstract base class (others have already pointed out the implications), you could setup your test code so that it creates an anonymous subclass of the base class that just provides dummy (no-op) implementations for the abstract methods.

For example, in your TestCase you could do this:

c = new Car() {
       void drive() { };
   };

Then test the rest of the methods, e.g.:

public class CarTest extends TestCase
{
    private Car c;

    public void setUp()
    {
        c = new Car() {
            void drive() { };
        };
    }

    public void testGetFuel() 
    {
        assertEquals(c.getFuel(), 0);
    }

    [...]
}

(This example is based on JUnit3 syntax. For JUnit4, the code would be slightly different, but the idea is the same.)

How do I tar a directory of files and folders without including the directory itself?

cd my_directory/ && tar -zcvf ../my_dir.tgz . && cd - 

should do the job in one line. It works well for hidden files as well. "*" doesn't expand hidden files by path name expansion at least in bash. Below is my experiment:

$ mkdir my_directory
$ touch my_directory/file1
$ touch my_directory/file2
$ touch my_directory/.hiddenfile1
$ touch my_directory/.hiddenfile2
$ cd my_directory/ && tar -zcvf ../my_dir.tgz . && cd ..
./
./file1
./file2
./.hiddenfile1
./.hiddenfile2
$ tar ztf my_dir.tgz
./
./file1
./file2
./.hiddenfile1
./.hiddenfile2

jQuery Datepicker onchange event issue

Your looking for the onSelect event in the datepicker object:

$('.selector').datepicker({
   onSelect: function(dateText, inst) { ... }
});

jQuery animate scroll

var page_url = windws.location.href;
var page_id = page_url.substring(page_url.lastIndexOf("#") + 1);
if (page_id == "") {
    $("html, body").animate({
        scrollTop: $("#scroll-" + page_id).offset().top
    }, 2000)
} else if (page_id == "") {
    $("html, body").animate({
        scrollTop: $("#scroll-" + page_id).offset().top
    }, 2000)
}

});

Convert a 1D array to a 2D array in numpy

Change 1D array into 2D array without using Numpy.

l = [i for i in range(1,21)]
part = 3
new = []
start, end = 0, part


while end <= len(l):
    temp = []
    for i in range(start, end):
        temp.append(l[i])
    new.append(temp)
    start += part
    end += part
print("new values:  ", new)


# for uneven cases
temp = []
while start < len(l):
    temp.append(l[start])
    start += 1
    new.append(temp)
print("new values for uneven cases:   ", new)

Eclipse: Enable autocomplete / content assist

If you would like to use autocomplete all the time without having to worry about hitting Ctrl + Spacebar or your own keyboard shortcut, you can make the following adjustment in the Eclipse preferences to trigger autocomplete simply by typing several different characters:

  1. Eclipse > Preferences > Java > Editor > Content Assist
  2. Auto Activation > Auto activation triggers for Java
  3. Enter all the characters you want to trigger autocomplete, such as the following:

abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ._

Now any time that you type any of these characters, Eclipse will trigger autocomplete suggestions based on the context.

What Does 'zoom' do in CSS?

Surprised that nobody mentioned that zoom: 1; is useful for IE6-7, to solve most IE-only bugs by triggering hasLayout.

asp:TextBox ReadOnly=true or Enabled=false?

Readonly will allow the user to copy text from it. Disabled will not.

Binding ConverterParameter

No, unfortunately this will not be possible because ConverterParameter is not a DependencyProperty so you won't be able to use bindings

But perhaps you could cheat and use a MultiBinding with IMultiValueConverter to pass in the 2 Tag properties.

Parameterize an SQL IN clause

Another possible solution is instead of passing a variable number of arguments to a stored procedure, pass a single string containing the names you're after, but make them unique by surrounding them with '<>'. Then use PATINDEX to find the names:

SELECT * 
FROM Tags 
WHERE PATINDEX('%<' + Name + '>%','<jo>,<john>,<scruffy>,<rubyonrails>') > 0

iterating through Enumeration of hastable keys throws NoSuchElementException error

You're calling e.nextElement() twice inside your loop when you're only guaranteed that you can call it once without an exception. Rewrite the loop like so:

while(e.hasMoreElements()){
  String param = e.nextElement();
  System.out.println(param);
}

Include an SVG (hosted on GitHub) in MarkDown

Just like this worked for me on Github.

![Imgae Caption](ImageAddressOnGitHub.svg)

or

<img src="ImageAddressOnGitHub.svg">

Adding a HTTP header to the Angular HttpClient doesn't send the header, why?

First, you need to add HttpHeaders with HttpClient

import { HttpClient,HttpHeaders  } from '@angular/common/http';

your constructor should be like this.

constructor(private http: HttpClient) { }

then you can use like this

   let header = new HttpHeaders({ "Authorization": "Bearer "+token});

   const requestOptions = {  headers: header};                                                                                                                                                                            

    return this.http.get<any>(url, requestOptions)
        .toPromise()
        .then(data=> {
            //...
            return data;
    });

convert 12-hour hh:mm AM/PM to 24-hour hh:mm

function convertTo24Hour(time) {
    time = time.toUpperCase();
    var hours = parseInt(time.substr(0, 2));
    if(time.indexOf('AM') != -1 && hours == 12) {
        time = time.replace('12', '0');
    }
    if(time.indexOf('PM')  != -1 && hours < 12) {
        time = time.replace(hours, (hours + 12));
    }
    return time.replace(/(AM|PM)/, '');
}

Can I force a page break in HTML printing?

Add a CSS class called "pagebreak" (or "pb"), like so:

@media print {
    .pagebreak { page-break-before: always; } /* page-break-after works, as well */
}

Then add an empty DIV tag (or any block element that generates a box) where you want the page break.

<div class="pagebreak"> </div>

It won't show up on the page, but will break up the page when printing.

P.S. Perhaps this only applies when using -after (and also what else you might be doing with other <div>s on the page), but I found that I had to augment the CSS class as follows:

@media print {
    .pagebreak {
        clear: both;
        page-break-after: always;
    }
}

How to select rows with no matching entry in another table?

I would use EXISTS expression since it is more powerful, you can e.g. more precisely choose rows you would like to join. In the case of LEFT JOIN, you have to take everything that's in the joined table. Its efficiency is probably the same as in the case of LEFT JOIN with null constraint.

SELECT t1.ID
FROM Table1 t1
WHERE NOT EXISTS (SELECT t2.ID FROM Table2 t2 WHERE t1.ID = t2.ID)

How to determine if Javascript array contains an object with an attribute that equals a given value?

Correct me if i'm wrong.. i could have used forEach method like this,

var found=false;
vendors.forEach(function(item){
   if(item.name === "name"){
       found=true;

   }
});

Nowadays i'm used to it ,because of it simplicity and self explanatory word. Thank you.

What does "for" attribute do in HTML <label> tag?

The for attribute of the <label> tag should be equal to the id attribute of the related element to bind them together.

Making heatmap from pandas DataFrame

Useful sns.heatmap api is here. Check out the parameters, there are a good number of them. Example:

import seaborn as sns
%matplotlib inline

idx= ['aaa','bbb','ccc','ddd','eee']
cols = list('ABCD')
df = DataFrame(abs(np.random.randn(5,4)), index=idx, columns=cols)

# _r reverses the normal order of the color map 'RdYlGn'
sns.heatmap(df, cmap='RdYlGn_r', linewidths=0.5, annot=True)

enter image description here

indexOf and lastIndexOf in PHP?

You need the following functions to do this in PHP:

strpos Find the position of the first occurrence of a substring in a string

strrpos Find the position of the last occurrence of a substring in a string

substr Return part of a string

Here's the signature of the substr function:

string substr ( string $string , int $start [, int $length ] )

The signature of the substring function (Java) looks a bit different:

string substring( int beginIndex, int endIndex )

substring (Java) expects the end-index as the last parameter, but substr (PHP) expects a length.

It's not hard, to get the desired length by the end-index in PHP:

$sub = substr($str, $start, $end - $start);

Here is the working code

$start = strpos($message, '-') + 1;
if ($req_type === 'RMT') {
    $pt_password = substr($message, $start);
}
else {
    $end = strrpos($message, '-');
    $pt_password = substr($message, $start, $end - $start);
}

Is it possible to get a list of files under a directory of a website? How?

DirBuster is such a hacking script that guesses a bunch of common names as nsanders had mentioned. It literally brute forces lists of common words and file endings (.html, .php) and over time figures out the directory structure of such sites, this could discover the page as you described but would also discover many others.

How to Convert the value in DataTable into a string array in c#

Very easy:

var stringArr = dataTable.Rows[0].ItemArray.Select(x => x.ToString()).ToArray();

Where DataRow.ItemArray property is an array of objects containing the values of the row for each columns of the data table.

python - if not in list

if I got it right, you can try

for item in [x for x in checklist if x not in mylist]:
    print (item)

Date format in the json output using spring boot

Starting from Spring Boot version 1.2.0.RELEASE , there is a property you can add to your application.properties to set a default date format to all of your classes spring.jackson.date-format.

For your date format example, you would add this line to your properties file:

spring.jackson.date-format=yyyy-MM-dd

Reference https://docs.spring.io/spring-boot/docs/1.2.0.RELEASE/reference/html/common-application-properties.html

What primitive data type is time_t?

You can use the function difftime. It returns the difference between two given time_t values, the output value is double (see difftime documentation).

time_t actual_time;
double actual_time_sec;
actual_time = time(0);
actual_time_sec = difftime(actual_time,0); 
printf("%g",actual_time_sec);

Change string color with NSAttributedString?

Use something like this (Not compiler checked)

NSMutableAttributedString *string = [[NSMutableAttributedString alloc]initWithString:self.text.text];
NSRange range=[self.myLabel.text rangeOfString:texts[sliderValue]]; //myLabel is the outlet from where you will get the text, it can be same or different

NSArray *colors=@[[UIColor redColor],
                  [UIColor redColor],
                  [UIColor yellowColor],
                  [UIColor greenColor]
                 ];

[string addAttribute:NSForegroundColorAttributeName 
               value:colors[sliderValue] 
               range:range];           

[self.scanLabel setAttributedText:texts[sliderValue]];

How to make CSS3 rounded corners hide overflow in Chrome/Opera

I found another solution for this problem. This looks like another bug in WebKit (or probably Chrome), but it works. All you need to do - is to add a WebKit CSS Mask to the #wrapper element. You can use a single pixel png image and even include it to the CSS to save a HTTP request.

#wrapper {
width: 300px; height: 300px;
border-radius: 100px;
overflow: hidden;
position: absolute; /* this breaks the overflow:hidden in Chrome/Opera */

/* this fixes the overflow:hidden in Chrome */
-webkit-mask-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAIAAACQd1PeAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAA5JREFUeNpiYGBgAAgwAAAEAAGbA+oJAAAAAElFTkSuQmCC);
}

#box {
width: 300px; height: 300px;
background-color: #cde;
}?

JSFiddle Example

How to check for a JSON response using RSpec?

I found a customer matcher here: https://raw.github.com/gist/917903/92d7101f643e07896659f84609c117c4c279dfad/have_content_type.rb

Put it in spec/support/matchers/have_content_type.rb and make sure to load stuff from support with something like this in you spec/spec_helper.rb

Dir[Rails.root.join('spec/support/**/*.rb')].each {|f| require f}

Here is the code itself, just in case it disappeared from the given link.

RSpec::Matchers.define :have_content_type do |content_type|
  CONTENT_HEADER_MATCHER = /^(.*?)(?:; charset=(.*))?$/

  chain :with_charset do |charset|
    @charset = charset
  end

  match do |response|
    _, content, charset = *content_type_header.match(CONTENT_HEADER_MATCHER).to_a

    if @charset
      @charset == charset && content == content_type
    else
      content == content_type
    end
  end

  failure_message_for_should do |response|
    if @charset
      "Content type #{content_type_header.inspect} should match #{content_type.inspect} with charset #{@charset}"
    else
      "Content type #{content_type_header.inspect} should match #{content_type.inspect}"
    end
  end

  failure_message_for_should_not do |model|
    if @charset
      "Content type #{content_type_header.inspect} should not match #{content_type.inspect} with charset #{@charset}"
    else
      "Content type #{content_type_header.inspect} should not match #{content_type.inspect}"
    end
  end

  def content_type_header
    response.headers['Content-Type']
  end
end

Which language uses .pde extension?

The .pde file extension is the one used by the Processing, Wiring, and the Arduino IDE.

Processing is not C-based but rather Java-based and with a syntax derived from Java. It is a Java framework that can be used as a Java library. It includes a default IDE that uses .pde extension. Just wanted to rectify @kersny's answer.

Wiring is a microcontroller that uses the same IDE. Arduino uses a modified version, but also with .pde. The OpenProcessing page where you found it is a website to exhibit some Processing work.

If you know Java, it should be fairly easy to convert the Processing code to Java AWT.

How to select a radio button by default?

This doesn't exactly answer the question but for anyone using AngularJS trying to achieve this, the answer is slightly different. And actually the normal answer won't work (at least it didn't for me).

Your html will look pretty similar to the normal radio button:

<input type='radio' name='group' ng-model='mValue' value='first' />First
<input type='radio' name='group' ng-model='mValue' value='second' /> Second

In your controller you'll have declared the mValue that is associated with the radio buttons. To have one of these radio buttons preselected, assign the $scope variable associated with the group to the desired input's value:

$scope.mValue="second"

This makes the "second" radio button selected on loading the page.

EDIT: Since AngularJS 2.x

The above approach does not work if you're using version 2.x and above. Instead use ng-checked attribute as follows:

<input type='radio' name='gender' ng-model='genderValue' value='male' ng-checked='genderValue === male'/>Male
<input type='radio' name='gender' ng-model='genderValue' value='female' ng-checked='genderValue === female'/> Female

Horizontal scroll on overflow of table

I think your overflow should be on the outer container. You can also explicitly set a min width for the columns. Like this:

.search-table-outter { overflow-x: scroll; }
th, td { min-width: 200px; }

Fiddle: http://jsfiddle.net/5WsEt/

Calculating a 2D Vector's Cross Product

In short: It's a shorthand notation for a mathematical hack.

Long explanation:

You can't do a cross product with vectors in 2D space. The operation is not defined there.

However, often it is interesting to evaluate the cross product of two vectors assuming that the 2D vectors are extended to 3D by setting their z-coordinate to zero. This is the same as working with 3D vectors on the xy-plane.

If you extend the vectors that way and calculate the cross product of such an extended vector pair you'll notice that only the z-component has a meaningful value: x and y will always be zero.

That's the reason why the z-component of the result is often simply returned as a scalar. This scalar can for example be used to find the winding of three points in 2D space.

From a pure mathematical point of view the cross product in 2D space does not exist, the scalar version is the hack and a 2D cross product that returns a 2D vector makes no sense at all.

what is the differences between sql server authentication and windows authentication..?

I don't know SQLServer as well as other DBMS' but I imagine the benefit is the same as with DB2 and Oracle. If you use Windows authentication, you only have to maintain one set of users and/or passwords, that of Windows, which is already done for you.

DBMS authentication means having a separate set of users and/or passwords which must be maintained.

In addition, Windows passwords allow them to be configured centrally for the enterprise (Active Directory) whereas SQLServer has to maintain one set for each DBMS instance.

C/C++ line number

You should use the preprocessor macro __LINE__ and __FILE__. They are predefined macros and part of the C/C++ standard. During preprocessing, they are replaced respectively by a constant string holding an integer representing the current line number and by the current file name.

Others preprocessor variables :

  • __func__ : function name (this is part of C99, not all C++ compilers support it)
  • __DATE__ : a string of form "Mmm dd yyyy"
  • __TIME__ : a string of form "hh:mm:ss"

Your code will be :

if(!Logical)
  printf("Not logical value at line number %d in file %s\n", __LINE__, __FILE__);

What's the difference between a web site and a web application?

A web application is a website in the same way that a square is a rectangle.

The application part is the model-controller combo. The web part (the view) is why it qualifies as a website.

Something that is only a website and not a web application is simply missing the dynamic aspect.

Of course, it can be difficult to decide on how much server-side processing is required to qualify it as a web application. Probably when it has a data store.

Thus, you have the primary role of webapps confused. A website's primary role is to inform. A web app's primary role is to inform using dynamic content (the do something part).

Check if EditText is empty.

You could call this function for each of the edit texts:

public boolean isEmpty(EditText editText) {
    boolean isEmptyResult = false;
    if (editText.getText().length() == 0) {
        isEmptyResult = true;
    }
    return isEmptyResult;
}

PHP error: "The zip extension and unzip command are both missing, skipping."

Not to belabor the point, but if you are working in a Dockerfile, you would solve this particular issue with Composer by installing the unzip utility. Below is an example using the official PHP image to install unzip and the zip PHP extension for good measure.

FROM php:7.4-apache

# Install Composer
COPY --from=composer /usr/bin/composer /usr/bin/composer

# Install unzip utility and libs needed by zip PHP extension 
RUN apt-get update && apt-get install -y \
    zlib1g-dev \
    libzip-dev \
    unzip
RUN docker-php-ext-install zip

This is a helpful GitHub issue where the above is lovingly lifted from.

How to check if a string contains only digits in Java

You must allow for more than a digit (the + sign) as in:

String regex = "[0-9]+"; 
String data = "23343453"; 
System.out.println(data.matches(regex));

How to create a temporary directory and get the path / file name in Python

In Python 3, TemporaryDirectory in the tempfile module can be used.

This is straight from the examples:

import tempfile
with tempfile.TemporaryDirectory() as tmpdirname:
     print('created temporary directory', tmpdirname)
# directory and contents have been removed

If you would like to keep the directory a bit longer, you could do something like this:

import tempfile

temp_dir = tempfile.TemporaryDirectory()
print(temp_dir.name)
# use temp_dir, and when done:
temp_dir.cleanup()

The documentation also says that "On completion of the context or destruction of the temporary directory object the newly created temporary directory and all its contents are removed from the filesystem." So at the end of the program, for example, Python will clean up the directory if it wasn't explicitly removed. Python's unittest may complain of ResourceWarning: Implicitly cleaning up <TemporaryDirectory... if you rely on this, though.

What does <a href="#" class="view"> mean?

The href is probably generated in a javascript function. For example with jQuery:

$(function() {
    $('a.view').attr('href', 'http://www.google.com');
});

How to insert a column in a specific position in oracle without dropping and recreating the table?

You (still) can not choose the position of the column using ALTER TABLE: it can only be added to the end of the table. You can obviously select the columns in any order you want, so unless you are using SELECT * FROM column order shouldn't be a big deal.

If you really must have them in a particular order and you can't drop and recreate the table, then you might be able to drop and recreate columns instead:-

First copy the table

CREATE TABLE my_tab_temp AS SELECT * FROM my_tab;

Then drop columns that you want to be after the column you will insert

ALTER TABLE my_tab DROP COLUMN three;

Now add the new column (two in this example) and the ones you removed.

ALTER TABLE my_tab ADD (two NUMBER(2), three NUMBER(10));

Lastly add back the data for the re-created columns

UPDATE my_tab SET my_tab.three = (SELECT my_tab_temp.three FROM my_tab_temp WHERE my_tab.one = my_tab_temp.one);

Obviously your update will most likely be more complex and you'll have to handle indexes and constraints and won't be able to use this in some cases (LOB columns etc). Plus this is a pretty hideous way to do this - but the table will always exist and you'll end up with the columns in a order you want. But does column order really matter that much?

how to get files from <input type='file' .../> (Indirect) with javascript

Based on Ray Nicholus's answer :

inputElement.onchange = function(event) {
   var fileList = inputElement.files;
   //TODO do something with fileList.  
}

using this will also work :

inputElement.onchange = function(event) {
   var fileList = event.target.files;
   //TODO do something with fileList.  
}

Selecting data from two different servers in SQL Server

Querying across 2 different databases is a distributed query. Here is a list of some techniques plus the pros and cons:

  1. Linked servers: Provide access to a wider variety of data sources than SQL Server replication provides
  2. Linked servers: Connect with data sources that replication does not support or which require ad hoc access
  3. Linked servers: Perform better than OPENDATASOURCE or OPENROWSET
  4. OPENDATASOURCE and OPENROWSET functions: Convenient for retrieving data from data sources on an ad hoc basis. OPENROWSET has BULK facilities as well that may/may not require a format file which might be fiddley
  5. OPENQUERY: Doesn't support variables
  6. All are T-SQL solutions. Relatively easy to implement and set up
  7. All are dependent on connection between source and destionation which might affect performance and scalability

How to get the SHA-1 fingerprint certificate in Android Studio for debug mode?

I found a very easy process to find you MD5, SHA-1 fingerprint using Android Studio.

  1. Run your project
  2. Go to Gradle Menu (Menu: View -> Tool Windows -> Gradle)
  3. Go to 'signingReport' in Gradle window. (Your project -> Tasks -> android -> signingReport)
  4. Run it. (Using double-click or Ctrl + Shift + F10)
  5. In Run window you will find all info.

It's work only for debug mode. In realease mode I can not see sha-1. Here result of gradlew signingReport

Variant: release
Config: none
----------
Variant: releaseUnitTest
Config: none
----------
Variant: debug
Config: debug
Store: path\Android\avd\.android\debug.keystore
Alias: AndroidDebugKey
MD5: xx:xx:xx:62:86:B7:9C:BC:FB:AD:C8:C6:64:69:xx:xx
SHA1: xx:xx:xx:xx:0F:B0:82:86:1D:14:0D:AF:67:99:58:1A:01:xx:xx:xx
Valid until: Friday, July 19, 2047
----------

So I must use keytool to get sha-1. Here official Firebase doc:

Get_sha-1_for_release

Maximize a window programmatically and prevent the user from changing the windows state

To stop the window being resizeable once you've maximised it you need to change the FormBorderStyle from Sizable to one of the fixed constants:

FixedSingle
Fixed3D
FixedDialog

From the MSDN Page Remarks section:

The border style of the form determines how the outer edge of the form appears. In addition to changing the border display for a form, certain border styles prevent the form from being sized. For example, the FormBorderStyle.FixedDialog border style changes the border of the form to that of a dialog box and prevents the form from being resized. The border style can also affect the size or availability of the caption bar section of a form.

It will change the appearance of the form if you pick Fixed3D for example, and you'll probably have to do some work if you want the form to restore to non-maximised and be resizeable again.

int to string in MySQL

If you have a column called "col1" which is int, you cast it to String like this:

CONVERT(col1,char)

e.g. this allows you to check an int value is containing another value (here 9) like this:

CONVERT(col1,char) LIKE '%9%'

filters on ng-model in an input

If you are doing complex, async input validation it might be worth it to abstract ng-model up one level as part of a custom class with its own validation methods.

https://plnkr.co/edit/gUnUjs0qHQwkq2vPZlpO?p=preview

html

<div>

  <label for="a">input a</label>
  <input 
    ng-class="{'is-valid': vm.store.a.isValid == true, 'is-invalid': vm.store.a.isValid == false}"
    ng-keyup="vm.store.a.validate(['isEmpty'])"
    ng-model="vm.store.a.model"
    placeholder="{{vm.store.a.isValid === false ? vm.store.a.warning : ''}}"
    id="a" />

  <label for="b">input b</label>
  <input 
    ng-class="{'is-valid': vm.store.b.isValid == true, 'is-invalid': vm.store.b.isValid == false}"
    ng-keyup="vm.store.b.validate(['isEmpty'])"
    ng-model="vm.store.b.model"
    placeholder="{{vm.store.b.isValid === false ? vm.store.b.warning : ''}}"
    id="b" />

</div>

code

(function() {

  const _ = window._;

  angular
    .module('app', [])
    .directive('componentLayout', layout)
    .controller('Layout', ['Validator', Layout])
    .factory('Validator', function() { return Validator; });

  /** Layout controller */

  function Layout(Validator) {
    this.store = {
      a: new Validator({title: 'input a'}),
      b: new Validator({title: 'input b'})
    };
  }

  /** layout directive */

  function layout() {
    return {
      restrict: 'EA',
      templateUrl: 'layout.html',
      controller: 'Layout',
      controllerAs: 'vm',
      bindToController: true
    };
  }

  /** Validator factory */  

  function Validator(config) {
    this.model = null;
    this.isValid = null;
    this.title = config.title;
  }

  Validator.prototype.isEmpty = function(checkName) {
    return new Promise((resolve, reject) => {
      if (/^\s+$/.test(this.model) || this.model.length === 0) {
        this.isValid = false;
        this.warning = `${this.title} cannot be empty`;
        reject(_.merge(this, {test: checkName}));
      }
      else {
        this.isValid = true;
        resolve(_.merge(this, {test: checkName}));
      }
    });
  };

  /**
   * @memberof Validator
   * @param {array} checks - array of strings, must match defined Validator class methods
   */

  Validator.prototype.validate = function(checks) {
    Promise
      .all(checks.map(check => this[check](check)))
      .then(res => { console.log('pass', res)  })
      .catch(e => { console.log('fail', e) })
  };

})();

Python: Is there an equivalent of mid, right, and left from BASIC?

This is Andy's solution. I just addressed User2357112's concern and gave it meaningful variable names. I'm a Python rookie and preferred these functions.

def left(aString, howMany):
    if howMany <1:
        return ''
    else:
        return aString[:howMany]

def right(aString, howMany):
    if howMany <1:
        return ''
    else:
        return aString[-howMany:]

def mid(aString, startChar, howMany):
    if howMany < 1:
        return ''
    else:
        return aString[startChar:startChar+howMany]

Have log4net use application config file for configuration data

All appender names must be reflected in the root section.
In your case the appender name is EventLogAppender but in the <root> <appender-ref .. section it is named as ConsoleAppender. They need to match.

You can add multiple appenders to your log config but you need to register each of them in the <root> section.

<appender-ref ref="ConsoleAppender" />
<appender-ref ref="EventLogAppender" />

You can also refer to the apache documentation on configuring log4net.

Mod of negative number is melting my brain

Adding some understanding.

By Euclidean definition the mod result must be always positive.

Ex:

 int n = 5;
 int x = -3;

 int mod(int n, int x)
 {
     return ((n%x)+x)%x;
 }

Output:

 -1

SELECT max(x) is returning null; how can I make it return 0?

You can also use COALESCE ( expression [ ,...n ] ) - returns first non-null like:

SELECT COALESCE(MAX(X),0) AS MaxX
FROM tbl
WHERE XID = 1

White spaces are required between publicId and systemId

I just found my self with this Exception, I was trying to consume a JAX-WS, with a custom URL like this:

String WSDL_URL= <get value from properties file>;
Customer service = new Customer(new URL(WSDL_URL));
ExecutePtt port = service.getExecutePt();
return port.createMantainCustomers(part);

and Java threw:

XML reader error: javax.xml.stream.XMLStreamException: ParseError at [row,col]:[1,63]
Message: White spaces are required between publicId and systemId.

Turns out that the URL string used to construct the service was missing the "?wsdl" at the end. For instance:

Bad:

http://www.host.org/service/Customer

Good:

http://www.host.org/service/Customer?wsdl

mysql: SOURCE error 2?

Related issue I had getting error 2 running source command: filename must not be in quotes even if it contains spaces in name or path to file.

onClick function of an input type="button" not working

When I try:

<input type="button" id="moreFields" onclick="alert('The text will be show!!'); return false;" value="Give me more fields!"  />

It's worked well. So I think the problem is position of moreFields() function. Ensure that function will be define before your input tag.

Pls try:

<script type="text/javascript">
    function moreFields() {
        alert("The text will be show");
    }
</script>

<input type="button" id="moreFields" onclick="moreFields()" value="Give me more fields!"  />

Hope it helped.

Creating a new column based on if-elif-else condition

For this particular relationship, you could use np.sign:

>>> df["C"] = np.sign(df.A - df.B)
>>> df
   A  B  C
a  2  2  0
b  3  1  1
c  1  3 -1

Sun JSTL taglib declaration fails with "Can not find the tag library descriptor"

If you use Tomcat server I suggest you to put JSTL .jar file to the Tomcat lib folder. By doing this you will have an access to JSTL in all your web projects automatically (with taglib declaration in .jsp files of course).

How do I pass a URL with multiple parameters into a URL?

In jQuery, you can use:

let myObject = {first:1, second:12, third:5};
jQuery.param(myObject);

Doc: http://api.jquery.com/jquery.param/ The output: first=1&second=12&third=5 This will format it, whatever your object contain.

git: diff between file in local repo and origin

To view the differences going from the remote file to the local file:

git diff remotename/branchname:remote/path/file1.txt local/path/file1.txt

To view the differences in the other direction:

git diff HEAD:local/path/file1.txt remotename/branchname:remote/path/file1.txt

Basically you can diff any two files anywhere using this notation:

git diff ref1:path/to/file1 ref2:path/to/file2

As usual, ref1 and ref2 could be branch names, remotename/branchname, commit SHAs, etc.

How to create JSON string in JavaScript?

json strings can't have line breaks in them. You'd have to make it all one line: {"key":"val","key2":"val2",etc....}.

But don't generate JSON strings yourself. There's plenty of libraries that do it for you, the biggest of which is jquery.

Java Long primitive type maximum limit

Ranges from -9,223,372,036,854,775,808 to +9,223,372,036,854,775,807.

It will start from -9,223,372,036,854,775,808

Long.MIN_VALUE.

Heap vs Binary Search Tree (BST)

Heap just guarantees that elements on higher levels are greater (for max-heap) or smaller (for min-heap) than elements on lower levels

I love the above answer and putting my comment just more specific to my need and usage. I had to get the n locations list find the distance from each location to specific point say (0,0) and then return the a m locations having smaller distance. I used Priority Queue which is Heap. For finding distances and putting in heap it took me n(log(n)) n-locations log(n) each insertion. Then for getting m with shortest distances it took m(log(n)) m-locations log(n) deletions of heaping up.

I if would have to do this with BST, it would have taken me n(n) worst case insertion.(Say the first value is very smaller and all other comes sequentially longer and longer and the tree spans to right child only or left child in case of smaller and smaller. The min would have taken O(1) time but again I had to balance. So from my situation and all above answers what I got is when you are only after the values at min or max priority basis go for heap.

How to prevent IFRAME from redirecting top-level window

Since the page you load inside the iframe can execute the "break out" code with a setInterval, onbeforeunload might not be that practical, since it could flud the user with 'Are you sure you want to leave?' dialogs.

There is also the iframe security attribute which only works on IE & Opera

:(

How to flush output of print function?

I did it like this in Python 3.4:

'''To write to screen in real-time'''
message = lambda x: print(x, flush=True, end="")
message('I am flushing out now...')

How can I quickly sum all numbers in a file?

In Go:

package main

import (
    "bufio"
    "fmt"
    "os"
    "strconv"
)

func main() {
    scanner := bufio.NewScanner(os.Stdin)
    sum := int64(0)
    for scanner.Scan() {
        v, err := strconv.ParseInt(scanner.Text(), 10, 64)
        if err != nil {
            fmt.Fprintf(os.Stderr, "Not an integer: '%s'\n", scanner.Text())
            os.Exit(1)
        }
        sum += v
    }
    fmt.Println(sum)
}

How do I show the changes which have been staged?

For Staging Area vs Repository(last commit) comparison use

 $git diff --staged

The command compares your staged($ git add fileName) changes to your last commit. If you want to see what you’ve staged that will go into your next commit, you can use git diff --staged. This command compares your staged changes to your last commit.

For Working vs Staging comparison use

$ git diff 

The command compares what is in your working directory with what is in your staging area. It’s important to note that git diff by itself doesn’t show all changes made since your last commit — only changes that are still unstaged. If you’ve staged all of your changes($ git add fileName), git diff will give you no output.

Also, if you stage a file($ git add fileName) and then edit it, you can use git diff to see the changes in the file that are staged and the changes that are unstaged.

How to create multiple output paths in Webpack config

I wrote a plugin that can hopefully do what you want, you can specify known or unknown entry points (using glob) and specify exact outputs or dynamically generate them using the entry file path and name. https://www.npmjs.com/package/webpack-entry-plus

Cannot open Windows.h in Microsoft Visual Studio

I got this error fatal error lnk1104: cannot open file 'kernel32.lib'. this error is getting because there is no path in VC++ directories. To solve this problem

Open Visual Studio 2008

  1. go to Tools-options-Projects and Solutions-VC++ directories-*
  2. then at right corner select Library files
  3. here you need to add path of kernel132.lib

In my case It is C:\Program Files\Microsoft SDKs\Windows\v6.0A\Lib

Use xml.etree.ElementTree to print nicely formatted xml files

You could use the library lxml (Note top level link is now spam) , which is a superset of ElementTree. Its tostring() method includes a parameter pretty_print - for example:

>>> print(etree.tostring(root, pretty_print=True))
<root>
  <child1/>
  <child2/>
  <child3/>
</root>

How to upload, display and save images using node.js and express

First of all, you should make an HTML form containing a file input element. You also need to set the form's enctype attribute to multipart/form-data:

<form method="post" enctype="multipart/form-data" action="/upload">
    <input type="file" name="file">
    <input type="submit" value="Submit">
</form>

Assuming the form is defined in index.html stored in a directory named public relative to where your script is located, you can serve it this way:

const http = require("http");
const path = require("path");
const fs = require("fs");

const express = require("express");

const app = express();
const httpServer = http.createServer(app);

const PORT = process.env.PORT || 3000;

httpServer.listen(PORT, () => {
  console.log(`Server is listening on port ${PORT}`);
});

// put the HTML file containing your form in a directory named "public" (relative to where this script is located)
app.get("/", express.static(path.join(__dirname, "./public")));

Once that's done, users will be able to upload files to your server via that form. But to reassemble the uploaded file in your application, you'll need to parse the request body (as multipart form data).

In Express 3.x you could use express.bodyParser middleware to handle multipart forms but as of Express 4.x, there's no body parser bundled with the framework. Luckily, you can choose from one of the many available multipart/form-data parsers out there. Here, I'll be using multer:

You need to define a route to handle form posts:

const multer = require("multer");

const handleError = (err, res) => {
  res
    .status(500)
    .contentType("text/plain")
    .end("Oops! Something went wrong!");
};

const upload = multer({
  dest: "/path/to/temporary/directory/to/store/uploaded/files"
  // you might also want to set some limits: https://github.com/expressjs/multer#limits
});


app.post(
  "/upload",
  upload.single("file" /* name attribute of <file> element in your form */),
  (req, res) => {
    const tempPath = req.file.path;
    const targetPath = path.join(__dirname, "./uploads/image.png");

    if (path.extname(req.file.originalname).toLowerCase() === ".png") {
      fs.rename(tempPath, targetPath, err => {
        if (err) return handleError(err, res);

        res
          .status(200)
          .contentType("text/plain")
          .end("File uploaded!");
      });
    } else {
      fs.unlink(tempPath, err => {
        if (err) return handleError(err, res);

        res
          .status(403)
          .contentType("text/plain")
          .end("Only .png files are allowed!");
      });
    }
  }
);

In the example above, .png files posted to /upload will be saved to uploaded directory relative to where the script is located.

In order to show the uploaded image, assuming you already have an HTML page containing an img element:

<img src="/image.png" />

you can define another route in your express app and use res.sendFile to serve the stored image:

app.get("/image.png", (req, res) => {
  res.sendFile(path.join(__dirname, "./uploads/image.png"));
});

Removing duplicate characters from a string

If order is not the matter:

>>> foo='mppmt'
>>> ''.join(set(foo))
'pmt'

To keep the order:

>>> foo='mppmt'
>>> ''.join([j for i,j in enumerate(foo) if j not in foo[:i]])
'mpt'

Checking if date is weekend PHP

For guys like me, who aren't minimalistic, there is a PECL extension called "intl". I use it for idn conversion since it works way better than the "idn" extension and some other n1 classes like "IntlDateFormatter".

Well, what I want to say is, the "intl" extension has a class called "IntlCalendar" which can handle many international countries (e.g. in Saudi Arabia, sunday is not a weekend day). The IntlCalendar has a method IntlCalendar::isWeekend for that. Maybe you guys give it a shot, I like that "it works for almost every country" fact on these intl-classes.

EDIT: Not quite sure but since PHP 5.5.0, the intl extension is bundled with PHP (--enable-intl).

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

seeing how the rules are fairly complicated, I'd suggest the following:

/^[a-z](\w*)[a-z0-9]$/i

match the whole string and capture intermediate characters. Then either with the string functions or the following regex:

/__/

check if the captured part has two underscores in a row. For example in Python it would look like this:

>>> import re
>>> def valid(s):
    match = re.match(r'^[a-z](\w*)[a-z0-9]$', s, re.I)
    if match is not None:
        return match.group(1).count('__') == 0
    return False

How to implement the Java comparable interface?

This thing can easily be done by implementing a public class that implements Comparable. This will allow you to use compareTo method which can be used with any other object to which you wish to compare.

for example you can implement it in this way:

public String compareTo(Animal oth) 
{
    return String.compare(this.population, oth.population);
}

I think this might solve your purpose.

How to debug on a real device (using Eclipse/ADT)

Sometimes you need to reset ADB. To do that, in Eclipse, go:

Window>> Show View >> Android (Might be found in the "Other" option)>>Devices

in the device Tab, click the down arrow, and choose reset adb.

JavaScript: Check if mouse button down?

the solution isn't good. one could "mousedown" on the document, then "mouseup" outside the browser, and on this case the browser would still be thinking the mouse is down.

the only good solution is using IE.event object.

Add shadow to custom shape on Android

I think this method produces very good results:

<!-- Drop Shadow Stack -->
<item>
    <shape>
        <padding
                android:top="1dp"
                android:right="1dp"
                android:bottom="1dp"
                android:left="1dp"/>
        <solid android:color="#00CCCCCC"/>
    </shape>
</item>
<item>
    <shape>
        <padding
                android:top="1dp"
                android:right="1dp"
                android:bottom="1dp"
                android:left="1dp"/>
        <solid android:color="#10CCCCCC"/>
    </shape>
</item>
<item>
    <shape>
        <padding
                android:top="1dp"
                android:right="1dp"
                android:bottom="1dp"
                android:left="1dp"/>
        <solid android:color="#20CCCCCC"/>
    </shape>
</item>
<item>
    <shape>
        <padding
                android:top="1dp"
                android:right="1dp"
                android:bottom="1dp"
                android:left="1dp"/>
        <solid android:color="#30CCCCCC"/>
    </shape>
</item>
<item>
    <shape>
        <padding
                android:top="1dp"
                android:right="1dp"
                android:bottom="1dp"
                android:left="1dp"/>
        <solid android:color="#50CCCCCC"/>
    </shape>
</item>

<item>

    <shape android:shape="rectangle">
        <stroke android:color="#CCC" android:width="1dp"/>
        <solid android:color="#FFF" />
        <corners android:radius="2dp" />

    </shape>

</item>

Calling async method synchronously

I prefer a non blocking approach:

            Dim aw1=GenerateCodeAsync().GetAwaiter()
            While Not aw1.IsCompleted
                Application.DoEvents()
            End While

What's the difference between integer class and numeric class in R

There are multiple classes that are grouped together as "numeric" classes, the 2 most common of which are double (for double precision floating point numbers) and integer. R will automatically convert between the numeric classes when needed, so for the most part it does not matter to the casual user whether the number 3 is currently stored as an integer or as a double. Most math is done using double precision, so that is often the default storage.

Sometimes you may want to specifically store a vector as integers if you know that they will never be converted to doubles (used as ID values or indexing) since integers require less storage space. But if they are going to be used in any math that will convert them to double, then it will probably be quickest to just store them as doubles to begin with.

Python object.__repr__(self) should be an expression?

It should be a Python expression that, when eval'd, creates an object with the exact same properties as this one. For example, if you have a Fraction class that contains two integers, a numerator and denominator, your __repr__() method would look like this:

# in the definition of Fraction class
def __repr__(self):
    return "Fraction(%d, %d)" % (self.numerator, self.denominator)

Assuming that the constructor takes those two values.

Creating and Update Laravel Eloquent

Save function:

$shopOwner->save()

already do what you want...

Laravel code:

    // If the model already exists in the database we can just update our record
    // that is already in this database using the current IDs in this "where"
    // clause to only update this model. Otherwise, we'll just insert them.
    if ($this->exists)
    {
        $saved = $this->performUpdate($query);
    }

    // If the model is brand new, we'll insert it into our database and set the
    // ID attribute on the model to the value of the newly inserted row's ID
    // which is typically an auto-increment value managed by the database.
    else
    {
        $saved = $this->performInsert($query);
    }

Configure active profile in SpringBoot via Maven

I would like to run an automation test in different environments.
So I add this to command maven command:

spring-boot:run -Drun.jvmArguments="-Dspring.profiles.active=productionEnv1"

Here is the link where I found the solution: [1]https://github.com/spring-projects/spring-boot/issues/1095

Recommended way to save uploaded files in a servlet application

I post my final way of doing it based on the accepted answer:

@SuppressWarnings("serial")
@WebServlet("/")
@MultipartConfig
public final class DataCollectionServlet extends Controller {

    private static final String UPLOAD_LOCATION_PROPERTY_KEY="upload.location";
    private String uploadsDirName;

    @Override
    public void init() throws ServletException {
        super.init();
        uploadsDirName = property(UPLOAD_LOCATION_PROPERTY_KEY);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        // ...
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        Collection<Part> parts = req.getParts();
        for (Part part : parts) {
            File save = new File(uploadsDirName, getFilename(part) + "_"
                + System.currentTimeMillis());
            final String absolutePath = save.getAbsolutePath();
            log.debug(absolutePath);
            part.write(absolutePath);
            sc.getRequestDispatcher(DATA_COLLECTION_JSP).forward(req, resp);
        }
    }

    // helpers
    private static String getFilename(Part part) {
        // courtesy of BalusC : http://stackoverflow.com/a/2424824/281545
        for (String cd : part.getHeader("content-disposition").split(";")) {
            if (cd.trim().startsWith("filename")) {
                String filename = cd.substring(cd.indexOf('=') + 1).trim()
                        .replace("\"", "");
                return filename.substring(filename.lastIndexOf('/') + 1)
                        .substring(filename.lastIndexOf('\\') + 1); // MSIE fix.
            }
        }
        return null;
    }
}

where :

@SuppressWarnings("serial")
class Controller extends HttpServlet {

    static final String DATA_COLLECTION_JSP="/WEB-INF/jsp/data_collection.jsp";
    static ServletContext sc;
    Logger log;
    // private
    // "/WEB-INF/app.properties" also works...
    private static final String PROPERTIES_PATH = "WEB-INF/app.properties";
    private Properties properties;

    @Override
    public void init() throws ServletException {
        super.init();
        // synchronize !
        if (sc == null) sc = getServletContext();
        log = LoggerFactory.getLogger(this.getClass());
        try {
            loadProperties();
        } catch (IOException e) {
            throw new RuntimeException("Can't load properties file", e);
        }
    }

    private void loadProperties() throws IOException {
        try(InputStream is= sc.getResourceAsStream(PROPERTIES_PATH)) {
                if (is == null)
                    throw new RuntimeException("Can't locate properties file");
                properties = new Properties();
                properties.load(is);
        }
    }

    String property(final String key) {
        return properties.getProperty(key);
    }
}

and the /WEB-INF/app.properties :

upload.location=C:/_/

HTH and if you find a bug let me know

Add and remove multiple classes in jQuery

You can separate multiple classes with the space:

$("p").addClass("myClass yourClass");

http://api.jquery.com/addClass/

Uncaught TypeError: Cannot set property 'onclick' of null

Try to put all your <script ...></script> tags before the </body> tag. Perhaps the js is trying to access an object of the DOM before it's built up.

mysqli_fetch_assoc() expects parameter 1 to be mysqli_result, boolean given

Mysqli makes use of object oriented programming. Try using this approach instead:

function dbCon() {
        if($mysqli = new mysqli('$hostname','$username','$password','$databasename')) return $mysqli; else return false;
}

if(!dbCon())
exit("<script language='javascript'>alert('Unable to connect to database')</script>");
else $con=dbCon();

if (isset($_GET['part'])){
    $partid = $_GET['part'];
    $sql = "SELECT * 
        FROM $usertable 
        WHERE PartNumber = $partid";

    $result=$con->query($sql_query);
    $row = $result->fetch_assoc();

    $partnumber = $partid;
    $nsn = $row["NSN"];
    $description = $row["Description"];
    $quantity = $row["Quantity"];
    $condition = $row["Conditio"];
}

Let me know if you have any questions, I could not test this code so you might need to tripple check it!

How to extract multiple JSON objects from one file?

Added streaming support based on the answer of @dunes:

import re
from json import JSONDecoder, JSONDecodeError

NOT_WHITESPACE = re.compile(r"[^\s]")


def stream_json(file_obj, buf_size=1024, decoder=JSONDecoder()):
    buf = ""
    ex = None
    while True:
        block = file_obj.read(buf_size)
        if not block:
            break
        buf += block
        pos = 0
        while True:
            match = NOT_WHITESPACE.search(buf, pos)
            if not match:
                break
            pos = match.start()
            try:
                obj, pos = decoder.raw_decode(buf, pos)
            except JSONDecodeError as e:
                ex = e
                break
            else:
                ex = None
                yield obj
        buf = buf[pos:]
    if ex is not None:
        raise ex

How to send data with angularjs $http.delete() request?

My suggestion:

$http({
    method: 'DELETE',
    url: '/roles/' + roleid,
    data: {
        user: userId
    },
    headers: {
        'Content-type': 'application/json;charset=utf-8'
    }
})
.then(function(response) {
    console.log(response.data);
}, function(rejection) {
    console.log(rejection.data);
});

How many spaces will Java String.trim() remove?

trim() will remove all leading and trailing blanks. But be aware: Your string isn't changed. trim() will return a new string instance instead.

How to build and use Google TensorFlow C++ api

If you don't want to build Tensorflow yourself and your operating system is Debian or Ubuntu, you can download prebuilt packages with the Tensorflow C/C++ libraries. This distribution can be used for C/C++ inference with CPU, GPU support is not included:

https://github.com/kecsap/tensorflow_cpp_packaging/releases

There are instructions written how to freeze a checkpoint in Tensorflow (TFLearn) and load this model for inference with the C/C++ API:

https://github.com/kecsap/tensorflow_cpp_packaging/blob/master/README.md

Beware: I am the developer of this Github project.

Registry key for global proxy settings for Internet Explorer 10 on Windows 8

Create a .reg file containing your proxy settings for your users. Create a batch file setting it to setting it to run the .reg file with the extension /s

On a server using a logon script, tell the logon to run the batch file. Jason

Limiting the number of characters per line with CSS

The latest way to go is to use the unit 'ch' which stands for character.

You can simply write:

p { max-width: 75ch; }

The only trick is that whitespaces won't be counted as characters..

Check also this post: https://stackoverflow.com/a/26975271/4069992

Grep to find item in Perl array

This could be done using List::Util's first function:

use List::Util qw/first/;

my @array = qw/foo bar baz/;
print first { $_ eq 'bar' } @array;

Other functions from List::Util like max, min, sum also may be useful for you

"SyntaxError: Unexpected token < in JSON at position 0"

For future googlers:

This message will be generated if the server-side function crashes.

Or if the server-side function doesn't even exist ( i.e. Typo in function name ).

So - suppose you are using a GET request... and everything looks perfect and you've triple-checked everything...

Check that GET string one more time. Mine was:

'/theRouteIWant&someVar=Some value to send'

should be

'/theRouteIWant?someVar=Some value to send'
               ^

CrAsH !       ( ... invisibly, on the server ...)

Node/Express sends back the incredibly helpful message:
Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0

How can I scan barcodes on iOS?

The problem with iPhone camera is that the first models (of which there are tons in use) have a fixed-focus camera that cannot take picture in-focus for distances under 2ft. The images are blurry and distorted and if taken from greater distance there is not enough detail/information from the barcode.

A few companies have developed iPhone apps that can accomodate for that by using advanced de-blurring technologies. Those applications you can find on Apple app store: pic2shop, RedLaser and ShopSavvy. All of the companies have announced that they have also SDKs available - some for free or very preferential terms, check that one out.

Echo equivalent in PowerShell for script testing

It should also be mentioned, that Set-PSDebug is similar to the old-school echo on batch command:

Set-PSDebug -Trace 1

This command will result in showing every line of the executing script:

When the Trace parameter has a value of 1, each line of script is traced as it runs. When the parameter has a value of 2, variable assignments, function calls, and script calls are also traced. If the Step parameter is specified, you're prompted before each line of the script runs.

mkdir -p functionality in Python

mkdir -p gives you an error if the file already exists:

$ touch /tmp/foo
$ mkdir -p /tmp/foo
mkdir: cannot create directory `/tmp/foo': File exists

So a refinement to the previous suggestions would be to re-raise the exception if os.path.isdir returns False (when checking for errno.EEXIST).

(Update) See also this highly similar question; I agree with the accepted answer (and caveats) except I would recommend os.path.isdir instead of os.path.exists.

(Update) Per a suggestion in the comments, the full function would look like:

import os
def mkdirp(directory):
    if not os.path.isdir(directory):
        os.makedirs(directory) 

Java Replace Line In Text File

just how to replace strings :) as i do first arg will be filename second target string third one the string to be replaced instead of targe

public class ReplaceString{
      public static void main(String[] args)throws Exception {
        if(args.length<3)System.exit(0);
        String targetStr = args[1];
        String altStr = args[2];
        java.io.File file = new java.io.File(args[0]);
        java.util.Scanner scanner = new java.util.Scanner(file);
        StringBuilder buffer = new StringBuilder();
        while(scanner.hasNext()){
          buffer.append(scanner.nextLine().replaceAll(targetStr, altStr));
          if(scanner.hasNext())buffer.append("\n");
        }
        scanner.close();
        java.io.PrintWriter printer = new java.io.PrintWriter(file);
        printer.print(buffer);
        printer.close();
      }
    }

How to use comparison and ' if not' in python?

There are two ways. In case of doubt, you can always just try it. If it does not work, you can add extra braces to make sure, like that:

if not ((u0 <= u) and (u < u0+step)):

ValueError: math domain error

You may also use math.log1p.

According to the official documentation :

math.log1p(x)

Return the natural logarithm of 1+x (base e). The result is calculated in a way which is accurate for x near zero.

You may convert back to the original value using math.expm1 which returns e raised to the power x, minus 1.

Bootstrap 4 navbar color

You can just use "!important" to get your custom color

.navbar {
 background-color: yourcolor !important;
 }

Amazon S3 exception: "The specified key does not exist"

In my case the error was appearing because I had uploaded the whole folder, containing the website files, into the container.

I solved it by moving all the files outside the folder, right into the container.

Print all properties of a Python Class

Here is full code. The result is exactly what you want.

class Animal(object):
    def __init__(self):
        self.legs = 2
        self.name = 'Dog'
        self.color= 'Spotted'
        self.smell= 'Alot'
        self.age  = 10
        self.kids = 0

if __name__ == '__main__':
    animal = Animal()
    temp = vars(animal)
    for item in temp:
        print item , ' : ' , temp[item]
        #print item , ' : ', temp[item] ,

Difference between getAttribute() and getParameter()

request.getParameter()

We use request.getParameter() to extract request parameters (i.e. data sent by posting a html form ). The request.getParameter() always returns String value and the data come from client.

request.getAttribute()

We use request.getAttribute() to get an object added to the request scope on the server side i.e. using request.setAttribute(). You can add any type of object you like here, Strings, Custom objects, in fact any object. You add the attribute to the request and forward the request to another resource, the client does not know about this. So all the code handling this would typically be in JSP/servlets. You can use request.setAttribute() to add extra-information and forward/redirect the current request to another resource.

For example,consider about first.jsp,

//First Page : first.jsp
<%@ page import="java.util.*" import="java.io.*"%>
<% request.setAttribute("PAGE", "first.jsp");%>
<jsp:forward page="/second.jsp"/>

and second.jsp:

<%@ page import="java.util.*" import="java.io.*"%>
From Which Page : <%=request.getAttribute("PAGE")%><br>
Data From Client : <%=request.getParameter("CLIENT")%>

From your browser, run first.jsp?CLIENT=you and the output on your browser is

From Which Page : *first.jsp*
Data From Client : you

The basic difference between getAttribute() and getParameter() is that the first method extracts a (serialized) Java object and the other provides a String value. For both cases a name is given so that its value (be it string or a java bean) can be looked up and extracted.

form_for but to post to a different action

I have done it like that

<%= form_for :user, url: {action: "update", params: {id: @user.id}} do |f| %>

Note the optional parameter id set to user instance id attribute.

How to find if div with specific id exists in jQuery?

put the id you want to check in jquery is method.

var idcheck = $("selector").is("#id"); 

if(idcheck){ // if the selector contains particular id

// your code if particular Id is there

}
else{
// your code if particular Id is NOT there
}

Center form submit buttons HTML / CSS

<style>
form div {
    width: 400px;   
    border: 1px solid black;
} 

form input[type='submit']  {
    display: inline-block;
    width: 70px;
}

div.submitWrapper  {
   text-align: center;    
}    
</style>
<form>

<div class='submitWrapper'>    
<input type='submit' name='submit' value='Submit'> 
 </div>

Also Check this jsfiddle

Longer object length is not a multiple of shorter object length?

Yes, this is something that you should worry about. Check the length of your objects with nrow(). R can auto-replicate objects so that they're the same length if they differ, which means you might be performing operations on mismatched data.

In this case you have an obvious flaw in that your subtracting aggregated data from raw data. These will definitely be of different lengths. I suggest that you merge them as time series (using the dates), then locf(), then do your subtraction. Otherwise merge them by truncating the original dates to the same interval as the aggregated series. Just be very careful that you don't drop observations.

Lastly, as some general advice as you get started: look at the result of your computations to see if they make sense. You might even pull them into a spreadsheet and replicate the results.

How can I pass a class member function as a callback?

Is m_cRedundencyManager able to use member functions? Most callbacks are set up to use regular functions or static member functions. Take a look at this page at C++ FAQ Lite for more information.

Update: The function declaration you provided shows that m_cRedundencyManager is expecting a function of the form: void yourCallbackFunction(int, void *). Member functions are therefore unacceptable as callbacks in this case. A static member function may work, but if that is unacceptable in your case, the following code would also work. Note that it uses an evil cast from void *.


// in your CLoggersInfra constructor:
m_cRedundencyManager->Init(myRedundencyManagerCallBackHandler, this);

// in your CLoggersInfra header:
void myRedundencyManagerCallBackHandler(int i, void * CLoggersInfraPtr);

// in your CLoggersInfra source file:
void myRedundencyManagerCallBackHandler(int i, void * CLoggersInfraPtr)
{
    ((CLoggersInfra *)CLoggersInfraPtr)->RedundencyManagerCallBack(i);
}

Easy pretty printing of floats in python?

First, elements inside a collection print their repr. you should learn about __repr__ and __str__.

This is the difference between print repr(1.1) and print 1.1. Let's join all those strings instead of the representations:

numbers = [9.0, 0.053, 0.0325754, 0.0108928, 0.0557025, 0.07933]
print "repr:", " ".join(repr(n) for n in numbers)
print "str:", " ".join(str(n) for n in numbers)

How to edit a JavaScript alert box title?

To answer the questions in terms of how you asked it.

This is actually REALLY easy (in Internet Explorer, at least), i did it in like 17.5 seconds.

If you use the custom script that cxfx provided: (place it in your apsx file)

<script language="VBScript">
Sub myAlert(title, content)
MsgBox content, 0, title 
End Sub 
</script>

You can then call it just like you called the regular alert. Just modify your code to the following.

Response.Write("<script language=JavaScript> myAlert('Message Header Here','Hi select a valid date'); </script>");

Hope that helps you, or someone else!

invalid conversion from 'const char*' to 'char*'

First of all this code snippet

char *addr=NULL;
strcpy(addr,retstring().c_str());

is invalid because you did not allocate memory where you are going to copy retstring().c_str().

As for the error message then it is clear enough. The type of expression data.str().c_str() is const char * but the third parameter of the function is declared as char *. You may not assign an object of type const char * to an object of type char *. Either the function should define the third parameter as const char * if it does not change the object pointed by the third parameter or you may not pass argument of type const char *.

Adding a css class to select using @Html.DropDownList()

Looking at the controller, and learing a bit more about how MVC actually works, I was able to make sense of this.

My view was one of the auto-generated ones, and contained this line of code:

@Html.DropDownList("PriorityID", string.Empty)

To add html attributes, I needed to do something like this:

@Html.DropDownList("PriorityID", (IEnumerable<SelectListItem>)ViewBag.PriorityID, new { @class="dropdown" })

Thanks again to @Laurent for your help, I realise the question wasn't as clear as it could have been...

UPDATE:

A better way of doing this would be to use DropDownListFor where possible, that way you don't rely on a magic string for the name attribute

@Html.DropDownListFor(x => x.PriorityID, (IEnumerable<SelectListItem>)ViewBag.PriorityID, new { @class = "dropdown" })

How to convert IPython notebooks to PDF and HTML?

The plain python version of partizanos's answer.

  • open Terminal (Linux, MacOS) or get to point where you can execute python files in Windows
  • Type the following code in a .py file (say tejas.py)
import os

[os.system("jupyter nbconvert --to pdf " + f) for f in os.listdir(".") if f.endswith("ipynb")]
  • Navigate to the folder containing the jupyter notebooks
  • Ensure that tejas.py is in the current folder. Copy it to the current folder if necessary.
  • type "python tejas.py"
  • Job done

How do I filter an array with TypeScript in Angular 2?

You can check an example in Plunker over here plunker example filters

filter() {

    let storeId = 1;
    this.bookFilteredList = this.bookList
                                .filter((book: Book) => book.storeId === storeId);
    this.bookList = this.bookFilteredList; 
}

How to replace negative numbers in Pandas Data Frame by zero

With lambda function

df['column'] = df['column'].apply(lambda x : x if x > 0 else 0)

What is the best way to create a string array in python?

strlist =[{}]*10
strlist[0] = set()
strlist[0].add("Beef")
strlist[0].add("Fish")
strlist[1] = {"Apple", "Banana"}
strlist[1].add("Cherry")
print(strlist[0])
print(strlist[1])
print(strlist[2])
print("Array size:", len(strlist))
print(strlist)

Pass row number as variable in excel sheet

An alternative is to use OFFSET:

Assuming the column value is stored in B1, you can use the following

C1 = OFFSET(A1, 0, B1 - 1)

This works by:

a) taking a base cell (A1)
b) adding 0 to the row (keeping it as A)
c) adding (A5 - 1) to the column

You can also use another value instead of 0 if you want to change the row value too.

Pytorch reshape tensor dimension

Use torch.unsqueeze(input, dim, out=None)

>>> import torch
>>> a = torch.Tensor([1,2,3,4,5])
>>> a

 1
 2
 3
 4
 5
[torch.FloatTensor of size 5]

>>> a = a.unsqueeze(0)
>>> a

 1  2  3  4  5
[torch.FloatTensor of size 1x5]

Mutex example / tutorial?

I stumbled upon this post recently and think that it needs an updated solution for the standard library's c++11 mutex (namely std::mutex).

I've pasted some code below (my first steps with a mutex - I learned concurrency on win32 with HANDLE, SetEvent, WaitForMultipleObjects etc).

Since it's my first attempt with std::mutex and friends, I'd love to see comments, suggestions and improvements!

#include <condition_variable>
#include <mutex>
#include <algorithm>
#include <thread>
#include <queue>
#include <chrono>
#include <iostream>


int _tmain(int argc, _TCHAR* argv[])
{   
    // these vars are shared among the following threads
    std::queue<unsigned int>    nNumbers;

    std::mutex                  mtxQueue;
    std::condition_variable     cvQueue;
    bool                        m_bQueueLocked = false;

    std::mutex                  mtxQuit;
    std::condition_variable     cvQuit;
    bool                        m_bQuit = false;


    std::thread thrQuit(
        [&]()
        {
            using namespace std;            

            this_thread::sleep_for(chrono::seconds(5));

            // set event by setting the bool variable to true
            // then notifying via the condition variable
            m_bQuit = true;
            cvQuit.notify_all();
        }
    );


    std::thread thrProducer(
        [&]()
        {
            using namespace std;

            int nNum = 13;
            unique_lock<mutex> lock( mtxQuit );

            while ( ! m_bQuit )
            {
                while( cvQuit.wait_for( lock, chrono::milliseconds(75) ) == cv_status::timeout )
                {
                    nNum = nNum + 13 / 2;

                    unique_lock<mutex> qLock(mtxQueue);
                    cout << "Produced: " << nNum << "\n";
                    nNumbers.push( nNum );
                }
            }
        }   
    );

    std::thread thrConsumer(
        [&]()
        {
            using namespace std;
            unique_lock<mutex> lock(mtxQuit);

            while( cvQuit.wait_for(lock, chrono::milliseconds(150)) == cv_status::timeout )
            {
                unique_lock<mutex> qLock(mtxQueue);
                if( nNumbers.size() > 0 )
                {
                    cout << "Consumed: " << nNumbers.front() << "\n";
                    nNumbers.pop();
                }               
            }
        }
    );

    thrQuit.join();
    thrProducer.join();
    thrConsumer.join();

    return 0;
}

ServletContext.getRequestDispatcher() vs ServletRequest.getRequestDispatcher()

I think you will understand it through these examples below.

Source code structure:

/src/main/webapp/subdir/sample.jsp
/src/main/webapp/sample.jsp

Context is: TestApp
So the entry point: http://yourhostname-and-port/TestApp


Forward to RELATIVE path:

Using servletRequest.getRequestDispatcher("sample.jsp"):

http://yourhostname-and-port/TestApp/subdir/fwdServlet  ==> \subdir\sample.jsp
http://yourhostname-and-port/TestApp/fwdServlet ==> /sample.jsp

Using servletContext.getRequestDispatcher("sample.jsp"):

http://yourhostname-and-port/TestApp/subdir/fwdServlet ==> java.lang.IllegalArgumentException: Path sample.jsp does not start with a "/" character
http://yourhostname-and-port/TestApp/fwdServlet ==> java.lang.IllegalArgumentException: Path sample.jsp does not start with a "/" character


Forward to ABSOLUTE path:

Using servletRequest.getRequestDispatcher("/sample.jsp"):

http://yourhostname-and-port/TestApp/subdir/fwdServlet  ==> /sample.jsp
http://yourhostname-and-port/TestApp/fwdServlet ==> /sample.jsp

Using servletContext.getRequestDispatcher("/sample.jsp"):

http://yourhostname-and-port/TestApp/subdir/fwdServlet ==> /sample.jsp
http://yourhostname-and-port/TestApp/fwdServlet ==> /sample.jsp

How to check if a column exists in a datatable

Base on accepted answer, I made an extension method to check column exist in table as

I shared for whom concern.

 public static class DatatableHelper
 {
        public static bool ContainColumn(this DataTable table, string columnName)
        {
            DataColumnCollection columns = table.Columns;
            if (columns.Contains(columnName))
            {
                return true;
            }

            return false;
        }
}

And use as dtTagData.ContainColumn("SystemName")

How to loop through a HashMap in JSP?

Below code works for me

first I defined the partnerTypesMap like below in the server side,

Map<String, String> partnerTypes = new HashMap<>();

after adding values to it I added the object to model,

model.addAttribute("partnerTypesMap", partnerTypes);

When rendering the page I use below foreach to print them one by one.

<c:forEach items="${partnerTypesMap}" var="partnerTypesMap">
      <form:option value="${partnerTypesMap['value']}">${partnerTypesMap['key']}</form:option>
</c:forEach>

How do you know a variable type in java?

I learned from the Search Engine(My English is very bad , So code...) How to get variable's type? Up's :

String str = "test";
String type = str.getClass().getName();
value: type = java.lang.String

this method :

str.getClass().getSimpleName();
value:String

now example:

Object o = 1;
o.getClass().getSimpleName();
value:Integer

SQL Server convert select a column and convert it to a string

SELECT  CAST(<COLUMN Name> AS VARCHAR(3)) + ','
FROM    <TABLE Name>
FOR     XML PATH('')

javascript compare strings without being case sensitive

You can also use string.match().

var string1 = "aBc";
var match = string1.match(/AbC/i);

if(match) {
}

Import regular CSS file in SCSS file?

Looks like this is unimplemented, as of the time of this writing:

https://github.com/sass/sass/issues/193

For libsass (C/C++ implementation), import works for *.css the same way as for *.scss files - just omit the extension:

@import "path/to/file";

This will import path/to/file.css.

See this answer for further details.

See this answer for Ruby implementation (sass gem)

Java 8 Lambda function that throws exception?

You can.

Extending @marcg 's UtilException and adding generic <E extends Exception> where necessary: this way, the compiler will force you again to add throw clauses and everything's as if you could throw checked exceptions natively on java 8's streams.

public final class LambdaExceptionUtil {

    @FunctionalInterface
    public interface Function_WithExceptions<T, R, E extends Exception> {
        R apply(T t) throws E;
    }

    /**
     * .map(rethrowFunction(name -> Class.forName(name))) or .map(rethrowFunction(Class::forName))
     */
    public static <T, R, E extends Exception> Function<T, R> rethrowFunction(Function_WithExceptions<T, R, E> function) throws E  {
        return t -> {
            try {
                return function.apply(t);
            } catch (Exception exception) {
                throwActualException(exception);
                return null;
            }
        };
    }

    @SuppressWarnings("unchecked")
    private static <E extends Exception> void throwActualException(Exception exception) throws E {
        throw (E) exception;
    }

}

public class LambdaExceptionUtilTest {

    @Test
    public void testFunction() throws MyTestException {
        List<Integer> sizes = Stream.of("ciao", "hello").<Integer>map(rethrowFunction(s -> transform(s))).collect(toList());
        assertEquals(2, sizes.size());
        assertEquals(4, sizes.get(0).intValue());
        assertEquals(5, sizes.get(1).intValue());
    }

    private Integer transform(String value) throws MyTestException {
        if(value==null) {
            throw new MyTestException();
        }
        return value.length();
    }

    private static class MyTestException extends Exception { }
}

Best practice for partial updates in a RESTful service

I am running into a similar problem. PUT on a sub-resource seems to work when you want to update only a single field. However, sometimes you want to update a bunch of things: Think of a web form representing the resource with option to change some entries. The user's submission of form should not result in a multiple PUTs.

Here are two solution that I can think of:

  1. do a PUT with the entire resource. On the server-side, define the semantics that a PUT with the entire resource ignores all the values that haven't changed.

  2. do a PUT with a partial resource. On the server-side, define the semantics of this to be a merge.

2 is just a bandwidth-optimization of 1. Sometimes 1 is the only option if the resource defines some fields are required fields (think proto buffers).

The problem with both these approaches is how to clear a field. You will have to define a special null value (especially for proto buffers since null values are not defined for proto buffers) that will cause clearing of the field.

Comments?

Rendering HTML elements to <canvas>

Take a look on MDN

It will render html element using creating SVG images.

For Example: There is <em>I</em> like <span style="color:white; text-shadow:0 0 2px blue;">cheese</span> HTML element. And I want to add it into <canvas id="canvas" style="border:2px solid black;" width="200" height="200"></canvas> Canvas Element.

Here is Javascript Code to add HTML element to canvas.

_x000D_
_x000D_
var canvas = document.getElementById('canvas');_x000D_
var ctx = canvas.getContext('2d');_x000D_
_x000D_
var data = '<svg xmlns="http://www.w3.org/2000/svg" width="200" height="200">' +_x000D_
  '<foreignObject width="100%" height="100%">' +_x000D_
  '<div xmlns="http://www.w3.org/1999/xhtml" style="font-size:40px">' +_x000D_
  '<em>I</em> like <span style="color:white; text-shadow:0 0 2px blue;">cheese</span>' +_x000D_
  '</div>' +_x000D_
  '</foreignObject>' +_x000D_
  '</svg>';_x000D_
_x000D_
var DOMURL = window.URL || window.webkitURL || window;_x000D_
_x000D_
var img = new Image();_x000D_
var svg = new Blob([data], {_x000D_
  type: 'image/svg+xml;charset=utf-8'_x000D_
});_x000D_
var url = DOMURL.createObjectURL(svg);_x000D_
_x000D_
img.onload = function() {_x000D_
  ctx.drawImage(img, 0, 0);_x000D_
  DOMURL.revokeObjectURL(url);_x000D_
}_x000D_
_x000D_
img.src = url;
_x000D_
<canvas id="canvas" style="border:2px solid black;" width="200" height="200"></canvas>
_x000D_
_x000D_
_x000D_

An efficient compression algorithm for short text strings

Huffman has a static cost, the Huffman table, so I disagree it's a good choice.

There are adaptative versions which do away with this, but the compression rate may suffer. Actually, the question you should ask is "what algorithm to compress text strings with these characteristics". For instance, if long repetitions are expected, simple Run-Lengh Encoding might be enough. If you can guarantee that only English words, spaces, punctiation and the occasional digits will be present, then Huffman with a pre-defined Huffman table might yield good results.

Generally, algorithms of the Lempel-Ziv family have very good compression and performance, and libraries for them abound. I'd go with that.

With the information that what's being compressed are URLs, then I'd suggest that, before compressing (with whatever algorithm is easily available), you CODIFY them. URLs follow well-defined patterns, and some parts of it are highly predictable. By making use of this knowledge, you can codify the URLs into something smaller to begin with, and ideas behind Huffman encoding can help you here.

For example, translating the URL into a bit stream, you could replace "http" with the bit 1, and anything else with the bit "0" followed by the actual procotol (or use a table to get other common protocols, like https, ftp, file). The "://" can be dropped altogether, as long as you can mark the end of the protocol. Etc. Go read about URL format, and think on how they can be codified to take less space.

Sql error on update : The UPDATE statement conflicted with the FOREIGN KEY constraint

This error is encountered when the primary key of a table is updated but it is referenced by a foreign key from another table and the update specific is set to No action. The No action is the default option.

If this is your case and No action is set on the update operation you can change the foreign-key definition to Cascade.

Right click your foreign key and select Modify. In the Foreign key relationships dialog under the INSERT and UPDATE specifics set the UPDATE rule on Cascade:

enter image description here

You can also set the rule using T-SQL:

ALTER TABLE YourTable
DROP Constraint Your_FK
GO

ALTER TABLE YourTable
ADD CONSTRAINT [New_FK_Constraint]
FOREIGN KEY (YourColumn) REFERENCES ReferencedTable(YourColumn)
ON DELETE CASCADE ON UPDATE CASCADE
GO 

Hope this helps

How to prevent robots from automatically filling up a form?

I have a simple approach to stopping spammers which is 100% effective, at least in my experience, and avoids the use of reCAPTCHA and similar approaches. I went from close to 100 spams per day on one of my sites' html forms to zero for the last 5 years once I implemented this approach.

It works by taking advantage of the e-mail ALIAS capabilities of most html form handling scripts (I use FormMail.pl), along with a graphic submission "code", which is easily created in the most simple of graphics programs. One such graphic includes the code M19P17nH and the prompt "Please enter the code at left".

This particular example uses a random sequence of letters and numbers, but I tend to use non-English versions of words familiar to my visitors (e.g. "pnofrtay"). Note that the prompt for the form field is built into the graphic, rather than appearing on the form. Thus, to a robot, that form field presents no clue as to its purpose.

The only real trick here is to make sure that your form html assigns this code to the "recipient" variable. Then, in your mail program, make sure that each such code you use is set as an e-mail alias, which points to whatever e-mail addresses you want to use. Since there is no prompt of any kind on the form for a robot to read and no e-mail addresses, it has no idea what to put in the blank form field. If it puts nothing in the form field or anything except acceptable codes, the form submission fails with a "bad recipient" error. You can use a different graphic on different forms, although it isn't really necessary in my experience.

Of course, a human being can solve this problem in a flash, without all the problems associated with reCAPTCHA and similar, more elegant, schemes. If a human spammer does respond to the recipient failure and programs the image code into the robot, you can change it easily, once you realize that the robot has been hard-coded to respond. In five years of using this approach, I've never had a spam from any of the forms on which I use it nor have I ever had a complaint from any human user of the forms. I'm certain that this could be beaten with OCR capability in the robot, but I've never had it happen on any of my sites which use html forms. I have also used "spam traps" (hidden "come hither" html code which points to my anti-spam policies) to good effect, but they were only about 90% effective.

What are some alternatives to ReSharper?

I think that CodeRush has a free, limited version, too. I ended up going with ReSharper, and I still recommend it, even though some of the functionality is in Visual Studio 2010. There are just some things that make it worth it.

Keep in mind that you don't need the full ReSharper license if you only code in one language. I have the C# version, and it's cheaper.

Create auto-numbering on images/figures in MS Word

  • Select whole document (Ctrl+A)
  • Press F9
  • Save

Should update the figure caption automatically.

My question is tho, how can one also 'assign' referenced figures '(Fig.4)' in the text to do the same thing - aka change when an image is added above it?

EDIT: Figured it out.. In word go to Insert and Cross-ref and assign the ref. Then Ctrl+A and F9 and everything should sort itself out.

jQuery - replace all instances of a character in a string

You need to use a regular expression, so that you can specify the global (g) flag:

var s = 'some+multi+word+string'.replace(/\+/g, ' ');

(I removed the $() around the string, as replace is not a jQuery method, so that won't work at all.)

Show Curl POST Request Headers? Is there a way to do this?

You can make you request headers by yourself using:

// open a socket connection on port 80
$fp = fsockopen($host, 80);

// send the request headers:
fputs($fp, "POST $path HTTP/1.1\r\n");
fputs($fp, "Host: $host\r\n");
fputs($fp, "Referer: $referer\r\n");
fputs($fp, "Content-type: application/x-www-form-urlencoded\r\n");
fputs($fp, "Content-length: ". strlen($data) ."\r\n");
fputs($fp, "Connection: close\r\n\r\n");
fputs($fp, $data);

$result = ''; 
while(!feof($fp)) {
    // receive the results of the request
    $result .= fgets($fp, 128);
}

// close the socket connection:
fclose($fp);

Like writen on how make request

@font-face not working

This is probably due to CORS (or not quoting paths) and is expected behaviour. I know it sounds confusing, but the reason is due to the source of your fonts and not the web page itself.

A good explanation and numerous solutions for Apache, NGINX, IIS or PHP available in multiple languages can be found here:

https://www.hirehop.com/blog/cross-domain-fonts-cors-font-face-issue/

How do I get the HTML code of a web page in PHP?

You may want to check out the YQL libraries from Yahoo: http://developer.yahoo.com/yql

The task at hand is as simple as

select * from html where url = 'http://stackoverflow.com/questions/ask'

You can try this out in the console at: http://developer.yahoo.com/yql/console (requires login)

Also see Chris Heilmanns screencast for some nice ideas what more you can do: http://developer.yahoo.net/blogs/theater/archives/2009/04/screencast_collating_distributed_information.html

Foreign Key to multiple tables

The first option in @Nathan Skerl's list is what was implemented in a project I once worked with, where a similar relationship was established between three tables. (One of them referenced two others, one at a time.)

So, the referencing table had two foreign key columns, and also it had a constraint to guarantee that exactly one table (not both, not neither) was referenced by a single row.

Here's how it could look when applied to your tables:

CREATE TABLE dbo.[Group]
(
    ID int NOT NULL CONSTRAINT PK_Group PRIMARY KEY,
    Name varchar(50) NOT NULL
);

CREATE TABLE dbo.[User]
(
    ID int NOT NULL CONSTRAINT PK_User PRIMARY KEY,
    Name varchar(50) NOT NULL
);

CREATE TABLE dbo.Ticket
(
    ID int NOT NULL CONSTRAINT PK_Ticket PRIMARY KEY,
    OwnerGroup int NULL
      CONSTRAINT FK_Ticket_Group FOREIGN KEY REFERENCES dbo.[Group] (ID),
    OwnerUser int NULL
      CONSTRAINT FK_Ticket_User  FOREIGN KEY REFERENCES dbo.[User]  (ID),
    Subject varchar(50) NULL,
    CONSTRAINT CK_Ticket_GroupUser CHECK (
      CASE WHEN OwnerGroup IS NULL THEN 0 ELSE 1 END +
      CASE WHEN OwnerUser  IS NULL THEN 0 ELSE 1 END = 1
    )
);

As you can see, the Ticket table has two columns, OwnerGroup and OwnerUser, both of which are nullable foreign keys. (The respective columns in the other two tables are made primary keys accordingly.) The CK_Ticket_GroupUser check constraint ensures that only one of the two foreign key columns contains a reference (the other being NULL, that's why both have to be nullable).

(The primary key on Ticket.ID is not necessary for this particular implementation, but it definitely wouldn't harm to have one in a table like this.)

Jquery assiging class to th in a table

You had thead in your selector, but there is no thead in your table. Also you had your selectors backwards. As you mentioned above, you wanted to be adding the tr class to the th, not vice-versa (although your comment seems to contradict what you wrote up above).

$('tr th').each(function(index){     if($('tr td').eq(index).attr('class') != ''){         // get the class of the td         var tdClass = $('tr td').eq(index).attr('class');         // add it to this th         $(this).addClass(tdClass );     } }); 

Fiddle

Xml serialization - Hide null values

Additionally to what Chris Taylor wrote: if you have something serialized as an attribute, you can have a property on your class named {PropertyName}Specified to control if it should be serialized. In code:

public class MyClass
{
    [XmlAttribute]
    public int MyValue;

    [XmlIgnore]
    public bool MyValueSpecified;
}

How can I connect to MySQL in Python 3 on Windows?

This is a quick tutorial on how to get Python 3.7 working with Mysql
Thanks to all from who I got answers to my questions
- hope this helps somebody someday.
----------------------------------------------------
My System:
Windows Version: Pro 64-bit

REQUIREMENTS.. download and install these first...
1. Download Xampp..
https://www.apachefriends.org/download.html
2. Download Python
https://www.python.org/downloads/windows/

--------------
//METHOD
--------------
Install xampp first after finished installing - install Python 3.7.
Once finished installing both - reboot your windows system.
Now start xampp and from the control panel - start the mysql server.
Confirm the versions by opening up CMD and in the terminal type

c:\>cd c:\xampp\mysql\bin

c:\xampp\mysql\bin>mysql -h localhost -v
Welcome to the MariaDB monitor.  Commands end with ; or \g.
Your MariaDB connection id is 2
Server version: 10.1.21-MariaDB mariadb.org binary distribution

Copyright (c) 2000, 2016, Oracle, MariaDB Corporation Ab and others.

This is to check the MYSQL version

c:\xampp\mysql\bin>python
Python 3.7.0b3 (v3.7.0b3:4e7efa9c6f, Mar 29 2018, 18:42:04) [MSC v.1913 64 bit (AMD64)] on win32

This is to check the Python version
Now that both have been confirmed type the following into the CMD...

c:\xampp\mysql\bin>pip install pymysql

After the install of pymysql is completed.
create a new file called "testconn.py" on your desktop or whereever for quick access.
Open this file with sublime or another text editor and put this into it.
Remember to change the settings to reflect your database.

#!/usr/bin/python
import pymysql
pymysql.install_as_MySQLdb() 

import MySQLdb
db = MySQLdb.connect(user="yourusernamehere",passwd="yourpasswordhere",host="yourhosthere",db="yourdatabasehere")
cursor = db.cursor()
cursor.execute("SELECT * from yourmysqltablehere")
data=cursor.fetchall()
for row in data :
    print (row)
db.close()

Now in your CMD - type

c:\Desktop>testconn.py

And thats it... your now fully connected from a python script to mysql...
Enjoy...

Floating point comparison functions for C#

Further to Andrew Wang's answer: if the BitConverter method is too slow but you cannot use unsafe code in your project, this struct is ~6x quicker than BitConverter:

[StructLayout(LayoutKind.Explicit)]
public struct FloatToIntSafeBitConverter
{
    public static int Convert(float value)
    {
        return new FloatToIntSafeBitConverter(value).IntValue;
    }

    public FloatToIntSafeBitConverter(float floatValue): this()
    {
        FloatValue = floatValue;
    }

    [FieldOffset(0)]
    public readonly int IntValue;

    [FieldOffset(0)]
    public readonly float FloatValue;
}

(Incidentally, I tried using the accepted solution but it (well my conversion at least) failed some of the unit tests also mentioned in the answer. e.g. assertTrue(nearlyEqual(Float.MIN_VALUE, -Float.MIN_VALUE)); )

POST request with a simple string in body with Alamofire

Based on Illya Krit's answer

Details

  • Xcode Version 10.2.1 (10E1001)
  • Swift 5
  • Alamofire 4.8.2

Solution

import Alamofire

struct BodyStringEncoding: ParameterEncoding {

    private let body: String

    init(body: String) { self.body = body }

    func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest {
        guard var urlRequest = urlRequest.urlRequest else { throw Errors.emptyURLRequest }
        guard let data = body.data(using: .utf8) else { throw Errors.encodingProblem }
        urlRequest.httpBody = data
        return urlRequest
    }
}

extension BodyStringEncoding {
    enum Errors: Error {
        case emptyURLRequest
        case encodingProblem
    }
}

extension BodyStringEncoding.Errors: LocalizedError {
    var errorDescription: String? {
        switch self {
            case .emptyURLRequest: return "Empty url request"
            case .encodingProblem: return "Encoding problem"
        }
    }
}

Usage

Alamofire.request(url, method: .post, parameters: nil, encoding: BodyStringEncoding(body: text), headers: headers).responseJSON { response in
     print(response)
}

WPF loading spinner

You can do it without any additional controls and libraries, using only Image control and transform:

<Image
    Source="/images/spinner.png"
    Width="100"
    Height="100"
    RenderTransformOrigin="0.5, 0.5" Visibility="{Binding IsLoading, Converter={StaticResource BooleanToVisibilityConverter}}">
    <Image.RenderTransform>
        <RotateTransform x:Name="noFreeze" />
    </Image.RenderTransform>
    <Image.Triggers>
        <EventTrigger RoutedEvent="Loaded">
            <BeginStoryboard>
                <Storyboard>
                    <DoubleAnimation
                        Storyboard.TargetProperty="(Image.RenderTransform).(RotateTransform.Angle)"
                        To="360" Duration="0:0:1" RepeatBehavior="Forever" />
                </Storyboard>
            </BeginStoryboard>
        </EventTrigger>
    </Image.Triggers>
</Image>

Replace /images/spinner.png with your image. Change To="360" to To="-360" if you want to rotate it counterclockwise. Duration="0:0:1" equals to 1 second per rotation.

How to subtract X days from a date using Java calendar?

Eli Courtwright second solution is wrong, it should be:

Calendar c = Calendar.getInstance();
c.setTime(date);
c.add(Calendar.DATE, -days);
date.setTime(c.getTime().getTime());

Why doesn't file_get_contents work?

The error may be that you need to change the permission of folder and file which you are going to access. If like GoDaddy service you can access the file and change the permission or by ssh use the command like:

sudo chmod 777 file.jpeg

and then you can access if the above mentioned problems are not your case.

In c# is there a method to find the max of 3 numbers?

You could try this code:

private float GetBrightestColor(float r, float g, float b) { 
    if (r > g && r > b) {
        return r;
    } else if (g > r && g > b) { 
        return g;
    } else if (b > r && b > g) { 
        return b;
    }
}

Convert JSON array to an HTML table in jQuery

with pure jquery:

window.jQuery.ajax({
    type: "POST",
    url: ajaxUrl,
    contentType: 'application/json',
    success: function (data) {

        var odd_even = false;
        var response = JSON.parse(data);

        var head = "<thead class='thead-inverse'><tr>";
        $.each(response[0], function (k, v) {
            head = head + "<th scope='row'>" + k.toString() + "</th>";
        })
        head = head + "</thead></tr>";
        $(table).append(head);//append header
       var body="<tbody><tr>";
        $.each(response, function () {
            body=body+"<tr>";
            $.each(this, function (k, v) {
                body=body +"<td>"+v.toString()+"</td>";                                        
            }) 
            body=body+"</tr>";               
        })
        body=body +"</tbody>";
        $(table).append(body);//append body
    },
    error: function (xhr, ajaxOptions, thrownError) {
        alert(xhr.responsetext);
    }
});

what is the difference between GROUP BY and ORDER BY in sql

The difference is exactly what the name implies: a group by performs a grouping operation, and an order by sorts.

If you do SELECT * FROM Customers ORDER BY Name then you get the result list sorted by the customers name.

If you do SELECT IsActive, COUNT(*) FROM Customers GROUP BY IsActive you get a count of active and inactive customers. The group by aggregated the results based on the field you specified.

Vagrant ssh authentication failure

Make sure your first network interface is NAT. The other second network interface can be anything you want when you're building box. Don't forget the Vagrant user, as discussed in the Google thread.

Good luck.

Check file uploaded is in csv format

Mime type option is not best option for validating CSV file. I used this code this worked well in all browser

$type = explode(".",$_FILES['file']['name']);
if(strtolower(end($type)) == 'csv'){

}
else
{

}