Programs & Examples On #Rpt

Only on Firefox "Loading failed for the <script> with source"

Today I ran into the exact same problem while working on a progressive web app (PWA) page and deleting some cache and service worker data for that page from Firefox. The dev console reported that none of the 4 Javascript files on the page would load anymore. The problem persisted in Safe mode, so it was not an add-on issue. The same script files loaded fine from other web pages on the same website. No amount of clearing the Firefox cache or wiping web page data from Firefox would help, nor would rebooting the Windows 10 PC. Chrome all the time worked fine on the problem page. In the end I did a restore of the entire Firefox profile folder from a day-old backup, and the problem was immediately gone, so it was not a problem with my PWA app. Apparently something in Firefox got corrupted.

How to integrate SAP Crystal Reports in Visual Studio 2017

I had exactly the same problem with my VS 2013 solutions when I install VS 2017 and Crystal Reports SP21. In fact it's because VS does not necessarily convert the solution in the first launch.

Once you have installed Crystal Report SP 21, make sure that VS 2017 upgrade your solution : a window must appear "SAP Crystal Reports, version for Visual" with a radio button "Convert the solution".

Screenshot in french :

enter image description here

When I used the menu "File / Open / Project/Solution", the conversion was not done.

I have to do that :

  1. Add VS 2017 on the tasks bar
  2. Run VS 2017 and Open the solution with File menu
  3. Try to build the project, errors appear with Crystal Reports
  4. Close VS 2017
  5. Right click on VS 2017 shortcur in then tasks bar and open the solution directly
  6. The conversion run this time, you can open .rpt and the solution build without error.

sudo: docker-compose: command not found

Or, just add your binary path into the PATH. At the end of the bashrc:

... 
export PATH=$PATH:/home/user/.local/bin/

save the file and run:

source .bashrc

and the command will work.

Datetime current year and month in Python

>>> from datetime import date
>>> date.today().month
2
>>> date.today().year
2020
>>> date.today().day
13

Determining if Swift dictionary contains key and obtaining any of its values

The accepted answer let keyExists = dict[key] != nil will not work if the Dictionary contains the key but has a value of nil.

If you want to be sure the Dictionary does not contain the key at all use this (tested in Swift 4).

if dict.keys.contains(key) {
  // contains key
} else { 
  // does not contain key
}

Display Python datetime without time

>>> print then.date(), type(then.date())
2013-05-07 <type 'datetime.date'>

How to extract hours and minutes from a datetime.datetime object?

It's easier to use the timestamp for this things since Tweepy gets both

import datetime
print(datetime.datetime.fromtimestamp(int(t1)).strftime('%H:%M'))

time data does not match format

To compare date time, you can try this. Datetime format can be changed

from datetime import datetime

>>> a = datetime.strptime("10/12/2013", "%m/%d/%Y")
>>> b = datetime.strptime("10/15/2013", "%m/%d/%Y")
>>> a>b
False

Oracle SQL Developer: Failure - Test failed: The Network Adapter could not establish the connection?

I solved this by writing the explicit IP address defined in the Listener.ora file as the hostname.

enter image description here

So, instead of "localhost", I wrote "192.168.1.2" as the "Hostname" in the SQL Developer field.

In the below picture I highlighted the input boxes that I've modified: enter image description here

JPG vs. JPEG image formats

The term "JPEG" is an acronym for the Joint Photographic Experts Group, which created the standard. .jpeg and .jpg files are identical. JPEG images are identified with 6 different standard file name extensions:

  • .jpg
  • .jpeg
  • .jpe
  • .jif
  • .jfif
  • .jfi

The jpg was used in Microsoft Operating Systems when they only supported 3 chars-extensions.

The JPEG File Interchange Format (JFIF - last three extensions in my list) is an image file format standard for exchanging JPEG encoded files compliant with the JPEG Interchange Format (JIF) standard, solving some of JIF's limitations in regard. Image data in JFIF files is compressed using the techniques in the JPEG standard, hence JFIF is sometimes referred to as "JPEG/JFIF".

Call asynchronous method in constructor?

A quick way to execute some time-consuming operation in any constructor is by creating an action and run them asynchronously.

new Action( async() => await InitializeThingsAsync())();

Running this piece of code will neither block your UI nor leave you with any loose threads. And if you need to update any UI (considering you are not using MVVM approach), you can use the Dispatcher to do so as many have suggested.

A Note: This option only provides you a way to start an execution of a method from the constructor if you don't have any init or onload or navigated overrides. Most likely this will keep on running even after the construction has been completed. Hence the result of this method call may NOT be available in the constructor itself.

How to compare Boolean?

As long as checker is not null, you may use !checker as posted. This is possible since Java 5, because this Boolean variable will be autoboxed to the primivite boolean value.

Add column with number of days between dates in DataFrame pandas

Assuming these were datetime columns (if they're not apply to_datetime) you can just subtract them:

df['A'] = pd.to_datetime(df['A'])
df['B'] = pd.to_datetime(df['B'])

In [11]: df.dtypes  # if already datetime64 you don't need to use to_datetime
Out[11]:
A    datetime64[ns]
B    datetime64[ns]
dtype: object

In [12]: df['A'] - df['B']
Out[12]:
one   -58 days
two   -26 days
dtype: timedelta64[ns]

In [13]: df['C'] = df['A'] - df['B']

In [14]: df
Out[14]:
             A          B        C
one 2014-01-01 2014-02-28 -58 days
two 2014-02-03 2014-03-01 -26 days

Note: ensure you're using a new of pandas (e.g. 0.13.1), this may not work in older versions.

What does "res.render" do, and what does the html file look like?

Renders a view and sends the rendered HTML string to the client.

res.render('index');

Or

res.render('index', function(err, html) {
  if(err) {...}
  res.send(html);
});

DOCS HERE: https://expressjs.com/en/api.html#res.render

Angular.js directive dynamic templateURL

You don't need custom directive here. Just use ng-include src attribute. It's compiled so you can put code inside. See plunker with solution for your issue.

<div ng-repeat="week in [1,2]">
  <div ng-repeat="day in ['monday', 'tuesday']">
    <ng-include src="'content/before-'+ week + '-' + day + '.html'"></ng-include>
  </div>
</div>

ValueError: unconverted data remains: 02:05

Best answer is to use the from dateutil import parser.

usage:

from dateutil import parser
datetime_obj = parser.parse('2018-02-06T13:12:18.1278015Z')
print datetime_obj
# output: datetime.datetime(2018, 2, 6, 13, 12, 18, 127801, tzinfo=tzutc())

Display Bootstrap Modal using javascript onClick

You don't need an onclick. Assuming you're using Bootstrap 3 Bootstrap 3 Documentation

<div class="span4 proj-div" data-toggle="modal" data-target="#GSCCModal">Clickable content, graphics, whatever</div>

<div id="GSCCModal" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
 <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;  </button>
        <h4 class="modal-title" id="myModalLabel">Modal title</h4>
      </div>
      <div class="modal-body">
        ...
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary">Save changes</button>
      </div>
    </div>
  </div>
</div>

If you're using Bootstrap 2, you'd follow the markup here: http://getbootstrap.com/2.3.2/javascript.html#modals

Spring Data JPA - "No Property Found for Type" Exception

If your project used Spring-Boot ,you can try to add this annotations at your Application.java.

@EnableJpaRepositories(repositoryFactoryBeanClass=CustomRepositoryFactoryBean.class)
@SpringBootApplication

public class Application {.....

AttributeError: 'datetime' module has no attribute 'strptime'

Use the correct call: strptime is a classmethod of the datetime.datetime class, it's not a function in the datetime module.

self.date = datetime.datetime.strptime(self.d, "%Y-%m-%d")

As mentioned by Jon Clements in the comments, some people do from datetime import datetime, which would bind the datetime name to the datetime class, and make your initial code work.

To identify which case you're facing (in the future), look at your import statements

  • import datetime: that's the module (that's what you have right now).
  • from datetime import datetime: that's the class.

Convert unix time to readable date in pandas dataframe

Alternatively, by changing a line of the above code:

# df.date = df.date.apply(lambda d: datetime.strptime(d, "%Y-%m-%d"))
df.date = df.date.apply(lambda d: datetime.datetime.fromtimestamp(int(d)).strftime('%Y-%m-%d'))

It should also work.

How to plot time series in python

Convert your x-axis data from text to datetime.datetime, use datetime.strptime:

>>> from datetime import datetime
>>> datetime.strptime("2012-may-31 19:00", "%Y-%b-%d %H:%M")
 datetime.datetime(2012, 5, 31, 19, 0)

This is an example of how to plot data once you have an array of datetimes:

import matplotlib.pyplot as plt
import datetime
import numpy as np

x = np.array([datetime.datetime(2013, 9, 28, i, 0) for i in range(24)])
y = np.random.randint(100, size=x.shape)

plt.plot(x,y)
plt.show()

enter image description here

Reading and writing to serial port in C on Linux

1) I'd add a /n after init. i.e. write( USB, "init\n", 5);

2) Double check the serial port configuration. Odds are something is incorrect in there. Just because you don't use ^Q/^S or hardware flow control doesn't mean the other side isn't expecting it.

3) Most likely: Add a "usleep(100000); after the write(). The file-descriptor is set not to block or wait, right? How long does it take to get a response back before you can call read? (It has to be received and buffered by the kernel, through system hardware interrupts, before you can read() it.) Have you considered using select() to wait for something to read()? Perhaps with a timeout?

Edited to Add:

Do you need the DTR/RTS lines? Hardware flow control that tells the other side to send the computer data? e.g.

int tmp, serialLines;

cout << "Dropping Reading DTR and RTS\n";
ioctl ( readFd, TIOCMGET, & serialLines );
serialLines &= ~TIOCM_DTR;
serialLines &= ~TIOCM_RTS;
ioctl ( readFd, TIOCMSET, & serialLines );
usleep(100000);
ioctl ( readFd, TIOCMGET, & tmp );
cout << "Reading DTR status: " << (tmp & TIOCM_DTR) << endl;
sleep (2);

cout << "Setting Reading DTR and RTS\n";
serialLines |= TIOCM_DTR;
serialLines |= TIOCM_RTS;
ioctl ( readFd, TIOCMSET, & serialLines );
ioctl ( readFd, TIOCMGET, & tmp );
cout << "Reading DTR status: " << (tmp & TIOCM_DTR) << endl;

How to upload images into MySQL database using PHP code

Just few more details:

  • Add mysql field

`image` blob

  • Get data from image

$image = addslashes(file_get_contents($_FILES['image']['tmp_name']));

  • Insert image data into db

$sql = "INSERT INTO `product_images` (`id`, `image`) VALUES ('1', '{$image}')";

  • Show image to the web

<img src="data:image/png;base64,'.base64_encode($row['image']).'">

  • End

How to deal with "data of class uneval" error from ggplot2?

when you add a new data set to a geom you need to use the data= argument. Or put the arguments in the proper order mapping=..., data=.... Take a look at the arguments for ?geom_line.

Thus:

p + geom_line(data=df.last, aes(HrEnd, MWh, group=factor(Date)), color="red") 

Or:

p + geom_line(aes(HrEnd, MWh, group=factor(Date)), df.last, color="red") 

C#, Looping through dataset and show each record from a dataset column

I believe you intended it more this way:

foreach (DataTable table in ds.Tables)
{
    foreach (DataRow dr in table.Rows)
    {
        DateTime TaskStart = DateTime.Parse(dr["TaskStart"].ToString());
        TaskStart.ToString("dd-MMMM-yyyy");
        rpt.SetParameterValue("TaskStartDate", TaskStart);
    }
}

You always accessed your first row in your dataset.

Python datetime strptime() and strftime(): how to preserve the timezone information

Unfortunately, strptime() can only handle the timezone configured by your OS, and then only as a time offset, really. From the documentation:

Support for the %Z directive is based on the values contained in tzname and whether daylight is true. Because of this, it is platform-specific except for recognizing UTC and GMT which are always known (and are considered to be non-daylight savings timezones).

strftime() doesn't officially support %z.

You are stuck with python-dateutil to support timezone parsing, I am afraid.

How do I make a Windows batch script completely silent?

To suppress output, use redirection to NUL.

There are two kinds of output that console commands use:

  • standard output, or stdout,

  • standard error, or stderr.

Of the two, stdout is used more often, both by internal commands, like copy, and by console utilities, or external commands, like find and others, as well as by third-party console programs.

>NUL suppresses the standard output and works fine e.g. for suppressing the 1 file(s) copied. message of the copy command. An alternative syntax is 1>NUL. So,

COPY file1 file2 >NUL

or

COPY file1 file2 1>NUL

or

>NUL COPY file1 file2

or

1>NUL COPY file1 file2

suppresses all of COPY's standard output.

To suppress error messages, which are typically printed to stderr, use 2>NUL instead. So, to suppress a File Not Found message that DEL prints when, well, the specified file is not found, just add 2>NUL either at the beginning or at the end of the command line:

DEL file 2>NUL

or

2>NUL DEL file

Although sometimes it may be a better idea to actually verify whether the file exists before trying to delete it, like you are doing in your own solution. Note, however, that you don't need to delete the files one by one, using a loop. You can use a single command to delete the lot:

IF EXIST "%scriptDirectory%*.noext" DEL "%scriptDirectory%*.noext"

How to get the last N rows of a pandas DataFrame?

Don't forget DataFrame.tail! e.g. df1.tail(10)

How to drop a list of rows from Pandas dataframe?

In a comment to @theodros-zelleke's answer, @j-jones asked about what to do if the index is not unique. I had to deal with such a situation. What I did was to rename the duplicates in the index before I called drop(), a la:

dropped_indexes = <determine-indexes-to-drop>
df.index = rename_duplicates(df.index)
df.drop(df.index[dropped_indexes], inplace=True)

where rename_duplicates() is a function I defined that went through the elements of index and renamed the duplicates. I used the same renaming pattern as pd.read_csv() uses on columns, i.e., "%s.%d" % (name, count), where name is the name of the row and count is how many times it has occurred previously.

How to convert a date string to different format

I assume I have import datetime before running each of the lines of code below

datetime.datetime.strptime("2013-1-25", '%Y-%m-%d').strftime('%m/%d/%y')

prints "01/25/13".

If you can't live with the leading zero, try this:

dt = datetime.datetime.strptime("2013-1-25", '%Y-%m-%d')
print '{0}/{1}/{2:02}'.format(dt.month, dt.day, dt.year % 100)

This prints "1/25/13".

EDIT: This may not work on every platform:

datetime.datetime.strptime("2013-1-25", '%Y-%m-%d').strftime('%m/%d/%y')

In SSRS, why do I get the error "item with same key has already been added" , when I'm making a new report?

SSRS will not accept duplicated columns so ensure that your query or store procedure is returning unique column names.

String contains - ignore case

You can use java.util.regex.Pattern with the CASE_INSENSITIVE flag for case insensitive matching:

Pattern.compile(Pattern.quote(strptrn), Pattern.CASE_INSENSITIVE).matcher(str1).find();

How to drop rows of Pandas DataFrame whose value in a certain column is NaN

Don't drop, just take the rows where EPS is not NA:

df = df[df['EPS'].notna()]

How to convert a timezone aware string to datetime in Python without dateutil?

There are two issues with the code in the original question: there should not be a : in the timezone and the format string for "timezone as an offset" is lower case %z not upper %Z.

This works for me in Python v3.6

>>> from datetime import datetime
>>> t = datetime.strptime("2012-11-01T04:16:13-0400", "%Y-%m-%dT%H:%M:%S%z")
>>> print(t)
2012-11-01 04:16:13-04:00

Python datetime - setting fixed hour and minute after using strptime to get day,month,year

Use datetime.replace:

from datetime import datetime
dt = datetime.strptime('26 Sep 2012', '%d %b %Y')
newdatetime = dt.replace(hour=11, minute=59)

Why is datetime.strptime not working in this simple example?

You should be using datetime.datetime.strptime. Note that very old versions of Python (2.4 and older) don't have datetime.datetime.strptime; use time.strptime in that case.

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

Use the isin method:

rpt[rpt['STK_ID'].isin(stk_list)]

Explanation of 'String args[]' and static in 'public static void main(String[] args)'

I would break up

public static void main(String args[])

in parts:

public

It means that you can call this method from outside of the class you are currently in. This is necessary because this method is being called by the Java runtime system which is not located in your current class.


static

When the JVM makes call to the main method there is no object existing for the class being called therefore it has to have static method to allow invocation from class.


void

Java is platform independent language and if it will return some value then the value may mean different things to different platforms. Also there are other ways to exit the program on a multithreaded system. Detailed explaination.


main

It's just the name of method. This name is fixed and as it's called by the JVM as entry point for an application.


String args[]

These are the arguments of type String that your Java application accepts when you run it.

Change Activity's theme programmatically

user1462299's response works great, but if you include fragments, they will use the original activities theme. To apply the theme to all fragments as well you can override the getTheme() method of the Context instead:

@Override
public Resources.Theme getTheme() {
    Resources.Theme theme = super.getTheme();
    if(useAlternativeTheme){
        theme.applyStyle(R.style.AlternativeTheme, true);
    }
    // you could also use a switch if you have many themes that could apply
    return theme;
}

You do not need to call setTheme() in the onCreate() Method anymore. You are overriding every request to get the current theme within this context this way.

Remove large .pack file created by git

I am a little late for the show but in case the above answer didn't solve the query then I found another way. Simply remove the specific large file from .pack. I had this issue where I checked in a large 2GB file accidentally. I followed the steps explained in this link: http://www.ducea.com/2012/02/07/howto-completely-remove-a-file-from-git-history/

How to convert a time string to seconds?

A little more pythonic way I think would be:

timestr = '00:04:23'

ftr = [3600,60,1]

sum([a*b for a,b in zip(ftr, map(int,timestr.split(':')))])

Output is 263Sec.

I would be interested to see if anyone could simplify it further.

Parsing time string in Python

datetime.datetime.strptime has problems with timezone parsing. Have a look at the dateutil package:

>>> from dateutil import parser
>>> parser.parse("Tue May 08 15:14:45 +0800 2012")
datetime.datetime(2012, 5, 8, 15, 14, 45, tzinfo=tzoffset(None, 28800))

Improve SQL Server query performance on large tables

I know it's been quite a time since the beginning... There is a lot of wisdom in all these answers. Good indexing is the first thing when trying to improve a query. Well, almost the first. The most-first (so to speak) is making changes to code so that it's efficient. So, after all's been said and done, if one has a query with no WHERE, or when the WHERE-condition is not selective enough, there is only one way to get the data: TABLE SCAN (INDEX SCAN). If one needs all the columns from a table, then TABLE SCAN will be used - no question about it. This might be a heap scan or clustered index scan, depending on the type of data organization. The only last way to speed things up (if at all possible), is to make sure that as many cores are used as possible to do the scan: OPTION (MAXDOP 0). I'm ignoring the subject of storage, of course, but one should make sure that one has unlimited RAM, which goes without saying :)

"Strict Standards: Only variables should be passed by reference" error

array_shift the only parameter is an array passed by reference. The return value of explode(".", $value) does not have any reference. Hence the error.

You should store the return value to a variable first.

    $arr = explode(".", $value);
    $extension = strtolower(array_pop($arr));   
    $fileName = array_shift($arr);

From PHP.net

The following things can be passed by reference:

- Variables, i.e. foo($a)
- New statements, i.e. foo(new foobar())
- [References returned from functions][2]

No other expressions should be passed by reference, as the result is undefined. For example, the following examples of passing by reference are invalid:

Difference between two dates in Python

I tried a couple of codes, but end up using something as simple as (in Python 3):

from datetime import datetime
df['difference_in_datetime'] = abs(df['end_datetime'] - df['start_datetime'])

If your start_datetime and end_datetime columns are in datetime64[ns] format, datetime understands it and return the difference in days + timestamp, which is in timedelta64[ns] format.

If you want to see only the difference in days, you can separate only the date portion of the start_datetime and end_datetime by using (also works for the time portion):

df['start_date'] = df['start_datetime'].dt.date
df['end_date'] = df['end_datetime'].dt.date

And then run:

df['difference_in_days'] = abs(df['end_date'] - df['start_date'])

The Network Adapter could not establish the connection when connecting with Oracle DB

If it is on a Linux box, I would suggest you add the database IP name and IP resolution to the /etc/hosts.

I have the same error and when we do the above, it works fine.

How to add dll in c# project

The DLL must be present at all times - as the name indicates, a reference only tells VS that you're trying to use stuff from the DLL. In the project file, VS stores the actual path and file name of the referenced DLL. If you move or delete it, VS is not able to find it anymore.

I usually create a libs folder within my project's folder where I copy DLLs that are not installed to the GAC. Then, I actually add this folder to my project in VS (show hidden files in VS, then right-click and "Include in project"). I then reference the DLLs from the folder, so when checking into source control, the library is also checked in. This makes it much easier when more than one developer will have to change the project.

(Please make sure to set the build type to "none" and "don't copy to output folder" for the DLL in your project.)

PS: I use a German Visual Studio, so the captions I quoted may not exactly match the English version...

How to troubleshoot an "AttributeError: __exit__" in multiproccesing in Python?

The problem is in this line:

with pattern.findall(row) as f:

You are using the with statement. It requires an object with __enter__ and __exit__ methods. But pattern.findall returns a list, with tries to store the __exit__ method, but it can't find it, and raises an error. Just use

f = pattern.findall(row)

instead.

Adding days to a date in Python

Sometimes we need to use searching by from date & to date. If we use date__range then we need to add 1 day to to_date otherwise queryset will be empty.

Example:

from datetime import timedelta  

from_date  = parse_date(request.POST['from_date'])

to_date    = parse_date(request.POST['to_date']) + timedelta(days=1)

attendance_list = models.DailyAttendance.objects.filter(attdate__range = [from_date, to_date])

Using %f with strftime() in Python to get microseconds

If you want an integer, try this code:

import datetime
print(datetime.datetime.now().strftime("%s%f")[:13])

Output:

1545474382803

Creating a copy of an object in C#

The easiest way to do this is writing a copy constructor in the MyClass class.

Something like this:

namespace Example
{
    class MyClass
    {
        public int val;

        public MyClass()
        {
        }

        public MyClass(MyClass other)
        {
            val = other.val;
        }
    }
}

The second constructor simply accepts a parameter of his own type (the one you want to copy) and creates a new object assigned with the same value

class Program
{
    static void Main(string[] args)
    {
        MyClass objectA = new MyClass();
        MyClass objectB = new MyClass(objectA);
        objectA.val = 10;
        objectB.val = 20;
        Console.WriteLine("objectA.val = {0}", objectA.val);
        Console.WriteLine("objectB.val = {0}", objectB.val);
        Console.ReadKey();
    }
}

output:

objectA.val = 10

objectB.val = 20               

WCF Service Client: The content type text/html; charset=utf-8 of the response message does not match the content type of the binding

Hy, In my case this error appeared because the Application pool of the webservice had the wrong 32/64 bit setting. So this error needed the following fix: you go to the IIS, select the site of the webservice , go to Advanced setting and get the application pool. Then go to Application pools, select it, go to "Advanced settings..." , select the "Enable 32 bit applications" and make it Enable or Disable, according to the 32/64 bit type of your webservice. If the setting is True, it means that it only allows 32 bit applications, so for 64 bit apps you have to make it "Disable" (default).

what does this mean ? image/png;base64?

That is, you are referencing an image, but instead of providing an external url, the png image data is in the url itself, embedded in the style sheet. data:image/png;base64 tells the browser that the data is inline, is a png image and is in this case base64 encoded. The encoding is needed because png images can contain bytes that are invalid inside a HTML document (or within the HTTP protocol even).

Crystal Reports 13 And Asp.Net 3.5

I believe you are not the only one who has problems when trying to deploy Crystal Report for VS 2010. Based on the error message you had, have you checked:

  1. Please make sure you just have one CR version installed on your system. If you do have other CR version installed, consider to uninstall it so that your application is not "confused" about the CR version.

  2. You need to make sure you download the correct CR version. Since you are using VS 2010, you need to refer to CRforVS_redist_install_64bit_13_0_1.zip (for 64 bit machine) or CRforVS_redist_install_32bit_13_0_1.zip (for 32 bit machine). These two are the redistributable packages. You can download full package from the below link as well: CRforVS_13_0_1.exe Note: It is sometimes necessary to install 32bit CR runtime even on 64bit OS

  3. Make sure you setup FULL TRUST permission on your root folder

  4. The LOCAL SERVICE permission must be setup on your application pool

  5. Make sure the aspnet_client folder exists on your root folder.

If you can make sure all the 5 points above, your Crystal Report should work without any fuss.

Another important thing to note down here is that if you host your Crystal Report with a shared host, you need to check it with them of whether they really support Crystal Report. If you still have problems, you can switch to http://www.asphostcentral.com, who provides Crystal Report support.

Good luck!

Trying to get property of non-object - CodeIgniter

In my case, I was looping through a series of objects from an XML file, but some of the instances apparently were not objects which was causing the error. Checking if the object was empty before processing it fixed the problem.

In other words, without checking if the object was empty, the script would error out on any empty object with the error as given below.

Trying to get property of non-object

For Example:

if (!empty($this->xml_data->thing1->thing2))
{
   foreach ($this->xml_data->thing1->thing2 as $thing)
   {

   }
}

In HTML5, should the main navigation be inside or outside the <header> element?

@IanDevlin is correct. MDN's rules say the following:

"The HTML Header Element "" defines a page header — typically containing the logo and name of the site and possibly a horizontal menu..."

The word "possibly" there is key. It goes on to say that the header doesn't necessarily need to be a site header. For instance you could include a "header" on a pop-up modal or on other modular parts of the document where there is a header and it would be helpful for a user on a screen reader to know about it.

It terms of the implicit use of NAV you can use it anywhere there is grouped site navigation, although it's usually omitted from the "footer" section for mini-navs / important site links.

Really it comes down to personal / team choice. Decide what you and your team feel is more semantic and more important and the try to be consistent. For me, if the nav is inline with the logo and the main site's "h1" then it makes sense to put it in the "header" but if you have a different design choice then decide on a case by case basis.

Most importantly check out the docs and be sure if you choose to omit or include you understand why you are making that particular decision.

Plotting time-series with Date labels on x-axis

I like ggplot too.

Here's one example:

df1 = data.frame(
date_id = c('2017-08-01', '2017-08-02', '2017-08-03', '2017-08-04'),          
nation = c('China', 'USA', 'China', 'USA'), 
value = c(4.0, 5.0, 6.0, 5.5))

ggplot(df1, aes(date_id, value, group=nation, colour=nation))+geom_line()+xlab(label='dates')+ylab(label='value')

enter image description here

Best way to find the months between two dates

You can use the below code to get month between two dates:

OrderedDict(((start_date + timedelta(_)).strftime(date_format), None) for _ in xrange((end_date - start_date).days)).keys()

where start_date and end_date must be proper date and date_format is the format in which you want your result of date..

In your case, date_format will be %b %Y.

Edit Crystal report file without Crystal Report software

If this is something you are only going to need to do once, have you considered downloading a demo version of Crystal? There's a 30-day trial version available here: http://www.developers.net/businessobjectsshowcase/view/3154

Of course, if you need to edit these files after the 30 day period is over, you would be better off buying Crystal.

Alternatively, if all you need to do is replace a few static literal words, have you tried doing a search and replace in a text editor? (Don't forget to save the original files somewhere safe first!)

Ruby String to Date Conversion

You can try https://rubygems.org/gems/dates_from_string:

Find date in structure:

text = "get car from repair 2015-02-02 23:00:10"
dates_from_string = DatesFromString.new
dates_from_string.find_date(text)

=> ["2015-02-02 23:00:10"]

How to round the minute of a datetime object

def get_rounded_datetime(self, dt, freq, nearest_type='inf'):

    if freq.lower() == '1h':
        round_to = 3600
    elif freq.lower() == '3h':
        round_to = 3 * 3600
    elif freq.lower() == '6h':
        round_to = 6 * 3600
    else:
        raise NotImplementedError("Freq %s is not handled yet" % freq)

    # // is a floor division, not a comment on following line:
    seconds_from_midnight = dt.hour * 3600 + dt.minute * 60 + dt.second
    if nearest_type == 'inf':
        rounded_sec = int(seconds_from_midnight / round_to) * round_to
    elif nearest_type == 'sup':
        rounded_sec = (int(seconds_from_midnight / round_to) + 1) * round_to
    else:
        raise IllegalArgumentException("nearest_type should be  'inf' or 'sup'")

    dt_midnight = datetime.datetime(dt.year, dt.month, dt.day)

    return dt_midnight + datetime.timedelta(0, rounded_sec)

Python strptime() and timezones?

Your time string is similar to the time format in rfc 2822 (date format in email, http headers). You could parse it using only stdlib:

>>> from email.utils import parsedate_tz
>>> parsedate_tz('Tue Jun 22 07:46:22 EST 2010')
(2010, 6, 22, 7, 46, 22, 0, 1, -1, -18000)

See solutions that yield timezone-aware datetime objects for various Python versions: parsing date with timezone from an email.

In this format, EST is semantically equivalent to -0500. Though, in general, a timezone abbreviation is not enough, to identify a timezone uniquely.

Change private static final field using Java reflection

If your field is simply private you can do this:

MyClass myClass= new MyClass();
Field aField= myClass.getClass().getDeclaredField("someField");
aField.setAccessible(true);
aField.set(myClass, "newValueForAString");

and throw/handle NoSuchFieldException

How can I compare a date and a datetime in Python?

I am trying to compare date which are in string format like '20110930'

benchMark = datetime.datetime.strptime('20110701', "%Y%m%d") 

actualDate = datetime.datetime.strptime('20110930', "%Y%m%d")

if actualDate.date() < benchMark.date():
    print True

How to Load RSA Private Key From File

You need to convert your private key to PKCS8 format using following command:

openssl pkcs8 -topk8 -inform PEM -outform DER -in private_key_file  -nocrypt > pkcs8_key

After this your java program can read it.

How to set character limit on the_content() and the_excerpt() in wordpress

just to help, if any one want to limit post length at home page .. then can use below code to do that..

the below code is simply a modification of @bfred.it Sir

add_filter("the_content", "break_text");

function limit_text($text){

  if(is_front_page())
  {
    $length = 250;
    if(strlen($text)<$length+10) return $text; //don't cut if too short
    $break_pos = strpos($text, ' ', $length); //find next space after desired length
    $visible = substr($text, 0, $break_pos);
    return balanceTags($visible) . "... <a href='".get_permalink()."'>read more</a>";
  }else{
    return $text;
  }

}

Is there anyway to exclude artifacts inherited from a parent POM?

When you call a package but do not want some of its dependencies you can do a thing like this (in this case I did not want the old log4j to be added because I needed to use the newer one):

<dependency>
  <groupId>package</groupId>
  <artifactId>package-pk</artifactId>
  <version>${package-pk.version}</version>

  <exclusions>
    <exclusion>
      <groupId>org.apache.logging.log4j</groupId>
      <artifactId>log4j-core</artifactId>
    </exclusion>
    <exclusion>
      <groupId>org.apache.logging.log4j</groupId>
      <artifactId>log4j-api</artifactId>
    </exclusion>
  </exclusions>
</dependency>

<!-- LOG4J -->
<dependency>
  <groupId>org.apache.logging.log4j</groupId>
  <artifactId>log4j-core</artifactId>
  <version>2.5</version>
</dependency>
<dependency>
  <groupId>org.apache.logging.log4j</groupId>
  <artifactId>log4j-api</artifactId>
  <version>2.5</version>
</dependency>

This works for me... but I am pretty new to java/maven so it is maybe not optimum.

How to resolve Error listenerStart when deploying web-app in Tomcat 5.5?

/var/lib/tomcat5.5/webapps/spaghetti/WEB-INF/lib/jsp-api-6.0.16.jar
/var/lib/tomcat5.5/webapps/spaghetti/WEB-INF/lib/servlet-api-6.0.16.jar

You should not have any server-specific libraries in the /WEB-INF/lib. Leave them in the appserver's own library. It would only lead to collisions in the classpath. Get rid of all appserver-specific libraries in /WEB-INF/lib (and also in JRE/lib and JRE/lib/ext if you have placed any of them there).

A common cause that the appserver-specific libraries are included in the webapp's library is that starters think that it is the right way to fix compilation errors of among others the javax.servlet classes not being resolveable. Putting them in webapp's library is the wrong solution. You should reference them in the classpath during compilation, i.e. javac -cp /path/to/server/lib/servlet.jar and so on, or if you're using an IDE, you should integrate the server in the IDE and associate the web project with the server. The IDE will then automatically take server-specific libraries in the classpath (buildpath) of the webapp project.

Java JRE 64-bit download for Windows?

Might this be the download you are looking for?

  1. Go to the Java SE Downloads Page.
  2. Scroll down a tad look for the main table with the header of "Java Platform, Standard Edition"
  3. Click the JRE Download Button (JRE is the runtime component. JDK is the developer's kit).
  4. Select the appropriate download (all platforms and 32/64 bit downloads are listed)

How can I account for period (AM/PM) using strftime?

>>> from datetime import datetime
>>> print(datetime.today().strftime("%H:%M %p"))
15:31 AM

Try replacing %I with %H.

How do I translate an ISO 8601 datetime string into a Python datetime object?

import datetime, time
def convert_enddate_to_seconds(self, ts):
    """Takes ISO 8601 format(string) and converts into epoch time."""
    dt = datetime.datetime.strptime(ts[:-7],'%Y-%m-%dT%H:%M:%S.%f')+\
                datetime.timedelta(hours=int(ts[-5:-3]),
                minutes=int(ts[-2:]))*int(ts[-6:-5]+'1')
    seconds = time.mktime(dt.timetuple()) + dt.microsecond/1000000.0
    return seconds

This also includes the milliseconds and time zone.

If the time is '2012-09-30T15:31:50.262-08:00', this will convert into epoch time.

>>> import datetime, time
>>> ts = '2012-09-30T15:31:50.262-08:00'
>>> dt = datetime.datetime.strptime(ts[:-7],'%Y-%m-%dT%H:%M:%S.%f')+ datetime.timedelta(hours=int(ts[-5:-3]), minutes=int(ts[-2:]))*int(ts[-6:-5]+'1')
>>> seconds = time.mktime(dt.timetuple()) + dt.microsecond/1000000.0
>>> seconds
1348990310.26

What does the servlet <load-on-startup> value signify

As stated on other answer and this load-on-startup article zero is acceptable and in the absent of any other servlet this will take priority on loading and loaded during deployment. Best use of load-on statup is to load servlets which takes longer time to initialize well before first request come like servlets which creates connection pool or make network call or hold bulky resource, this will significantly reduce response time for first few request.

How can I parse a time string containing milliseconds in it with python?

Python 2.6 added a new strftime/strptime macro %f, which does microseconds. Not sure if this is documented anywhere. But if you're using 2.6 or 3.0, you can do this:

time.strptime('30/03/09 16:31:32.123', '%d/%m/%y %H:%M:%S.%f')

Edit: I never really work with the time module, so I didn't notice this at first, but it appears that time.struct_time doesn't actually store milliseconds/microseconds. You may be better off using datetime, like this:

>>> from datetime import datetime
>>> a = datetime.strptime('30/03/09 16:31:32.123', '%d/%m/%y %H:%M:%S.%f')
>>> a.microsecond
123000

Easiest way to flip a boolean value?

Clearly you need a factory pattern!

KeyFactory keyFactory = new KeyFactory();
KeyObj keyObj = keyFactory.getKeyObj(wParam);
keyObj.doStuff();


class VK_F11 extends KeyObj {
   boolean val;
   public void doStuff() {
      val = !val;
   }
}

class VK_F12 extends KeyObj {
   boolean val;
   public void doStuff() {
      val = !val;
   }
}

class KeyFactory {
   public KeyObj getKeyObj(int param) {
      switch(param) {
         case VK_F11:
            return new VK_F11();
         case VK_F12:
            return new VK_F12();
      }
      throw new KeyNotFoundException("Key " + param + " was not found!");
   }
}

:D

</sarcasm>

Make code in LaTeX look *nice*

For simple document, I sometimes use verbatim, but listing is nice for big chunk of code.

Is JavaScript a pass-by-reference or pass-by-value language?

In JavaScript, the type of the value solely controls whether that value will be assigned by value-copy or by reference-copy.

Primitive values are always assigned/passed by value-copy:

  • null
  • undefined
  • string
  • number
  • boolean
  • symbol in ES6

Compound values are always assigned/passed by reference-copy

  • objects
  • arrays
  • function

For example

var a = 2;
var b = a; // `b` is always a copy of the value in `a`
b++;
a; // 2
b; // 3

var c = [1,2,3];
var d = c; // `d` is a reference to the shared `[1,2,3]` value
d.push( 4 );
c; // [1,2,3,4]
d; // [1,2,3,4]

In the above snippet, because 2 is a scalar primitive, a holds one initial copy of that value, and b is assigned another copy of the value. When changing b, you are in no way changing the value in a.

But both c and d are separate references to the same shared value [1,2,3], which is a compound value. It's important to note that neither c nor d more "owns" the [1,2,3] value -- both are just equal peer references to the value. So, when using either reference to modify (.push(4)) the actual shared array value itself, it's affecting just the one shared value, and both references will reference the newly modified value [1,2,3,4].

var a = [1,2,3];
var b = a;
a; // [1,2,3]
b; // [1,2,3]

// later
b = [4,5,6];
a; // [1,2,3]
b; // [4,5,6]

When we make the assignment b = [4,5,6], we are doing absolutely nothing to affect where a is still referencing ([1,2,3]). To do that, b would have to be a pointer to a rather than a reference to the array -- but no such capability exists in JS!

function foo(x) {
    x.push( 4 );
    x; // [1,2,3,4]

    // later
    x = [4,5,6];
    x.push( 7 );
    x; // [4,5,6,7]
}

var a = [1,2,3];

foo( a );

a; // [1,2,3,4]  not  [4,5,6,7]

When we pass in the argument a, it assigns a copy of the a reference to x. x and a are separate references pointing at the same [1,2,3] value. Now, inside the function, we can use that reference to mutate the value itself (push(4)). But when we make the assignment x = [4,5,6], this is in no way affecting where the initial reference a is pointing -- still points at the (now modified) [1,2,3,4] value.

To effectively pass a compound value (like an array) by value-copy, you need to manually make a copy of it, so that the reference passed doesn't still point to the original. For example:

foo( a.slice() );

Compound value (object, array, etc) that can be passed by reference-copy

function foo(wrapper) {
    wrapper.a = 42;
}

var obj = {
    a: 2
};

foo( obj );

obj.a; // 42

Here, obj acts as a wrapper for the scalar primitive property a. When passed to foo(..), a copy of the obj reference is passed in and set to the wrapperparameter. We now can use the wrapper reference to access the shared object, and update its property. After the function finishes, obj.a will see the updated value 42.

Source

Converting date between DD/MM/YYYY and YYYY-MM-DD?

Your example code is wrong. This works:

import datetime

datetime.datetime.strptime("21/12/2008", "%d/%m/%Y").strftime("%Y-%m-%d")

The call to strptime() parses the first argument according to the format specified in the second, so those two need to match. Then you can call strftime() to format the result into the desired final format.

What can I use for good quality code coverage for C#/.NET?

There are pre-release (beta) versions of NCover available for free. They work fine for most cases, especially when combined with NCoverExplorer.

How do I parse an ISO 8601-formatted date?

import re,datetime
s="2008-09-03T20:56:35.450686Z"
d=datetime.datetime(*map(int, re.split('[^\d]', s)[:-1]))

What is the newline character in the C language: \r or \n?

'\r' = carriage return and '\n' = line feed.

In fact, there are some different behaviors when you use them in different OSes. On Unix it is '\n', but it is '\r''\n' on Windows.

How to enable LogCat/Console in Eclipse for Android?

In Eclipse, Goto Window-> Show View -> Other -> Android-> Logcat.

Logcat is nothing but a console of your Emulator or Device.

System.out.println does not work in Android. So you have to handle every thing in Logcat. More Info Look out this Documentation.

Edit 1: System.out.println is working on Logcat. If you use that the Tag will be like System.out and Message will be your message.

How do I know which version of Javascript I'm using?

Wikipedia (or rather, the community on Wikipedia) keeps a pretty good up-to-date list here.

  • Most browsers are on 1.5 (though they have features of later versions)
  • Mozilla progresses with every dot release (they maintain the standard so that's not surprising)
  • Firefox 4 is on JavaScript 1.8.5
  • The other big off-the-beaten-path one is IE9 - it implements ECMAScript 5, but doesn't implement all the features of JavaScript 1.8.5 (not sure what they're calling this version of JScript, engine codenamed Chakra, yet).

Styling input buttons for iPad and iPhone

I had the same issue today using primefaces (primeng) and angular 7. Add the following to your style.css

p-button {
   -webkit-appearance: none !important;
}

i am also using a bit of bootstrap which has a reboot.css, that overrides it with (thats why i had to add !important)

button {
  -webkit-appearance: button;

}

Get a filtered list of files in a directory

You can use pathlib that is available in Python standard library 3.4 and above.

from pathlib import Path

files = [f for f in Path.cwd().iterdir() if f.match("145592*.jpg")]

JAXB: How to ignore namespace during unmarshalling XML document?

Another way to add a default namespace to an XML Document before feeding it to JAXB is to use JDom:

  1. Parse XML to a Document
  2. Iterate through and set namespace on all Elements
  3. Unmarshall using a JDOMSource

Like this:

public class XMLObjectFactory {
    private static Namespace DEFAULT_NS = Namespace.getNamespace("http://tempuri.org/");

    public static Object createObject(InputStream in) {
        try {
            SAXBuilder sb = new SAXBuilder(false);
            Document doc = sb.build(in);
            setNamespace(doc.getRootElement(), DEFAULT_NS, true);
            Source src = new JDOMSource(doc);
            JAXBContext context = JAXBContext.newInstance("org.tempuri");
            Unmarshaller unmarshaller = context.createUnmarshaller();
            JAXBElement root = unmarshaller.unmarshal(src);
            return root.getValue();
        } catch (Exception e) {
            throw new RuntimeException("Failed to create Object", e);
        }
    }

    private static void setNamespace(Element elem, Namespace ns, boolean recurse) {
        elem.setNamespace(ns);
        if (recurse) {
            for (Object o : elem.getChildren()) {
                setNamespace((Element) o, ns, recurse);
            }
        }
    }

How do I print a double value with full precision using cout?

The iostreams way is kind of clunky. I prefer using boost::lexical_cast because it calculates the right precision for me. And it's fast, too.

#include <string>
#include <boost/lexical_cast.hpp>

using boost::lexical_cast;
using std::string;

double d = 3.14159265358979;
cout << "Pi: " << lexical_cast<string>(d) << endl;

Output:

Pi: 3.14159265358979

How do relative file paths work in Eclipse?

This is really similar to another question. How should I load files into my Java application?

How should I load my files into my Java Application?

You do not want to load your files in by:

C:\your\project\file.txt

this is bad!

You should use getResourceAsStream.

InputStream inputStream = YourClass.class.getResourceAsStream(“file.txt”);

And also you should use File.separator; which is the system-dependent name-separator character, represented as a string for convenience.

how to import csv data into django models

something like this:

f = open('data.txt', 'r')  
for line in f:  
   line =  line.split(';')  
   product = Product()  
   product.name = line[2] + '(' + line[1] + ')'  
   product.description = line[4]  
   product.price = '' #data is missing from file  
   product.save()  

f.close()  

Simulate CREATE DATABASE IF NOT EXISTS for PostgreSQL?

If you don't care about the data, you can drop database first and then recreate it:

DROP DATABASE IF EXISTS dbname;
CREATE DATABASE dbname;

How to disable the resize grabber of <textarea>?

Just use resize: none

textarea {
   resize: none;
}

You can also decide to resize your textareas only horizontal or vertical, this way:

textarea { resize: vertical; }

textarea { resize: horizontal; }

Finally, resize: both enables the resize grabber.

Catching errors in Angular HttpClient

For Angular 6+ , .catch doesn't work directly with Observable. You have to use

.pipe(catchError(this.errorHandler))

Below code:

import { IEmployee } from './interfaces/employee';
import { Injectable } from '@angular/core';
import { HttpClient, HttpErrorResponse } from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { catchError } from 'rxjs/operators';

@Injectable({
  providedIn: 'root'
})
export class EmployeeService {

  private url = '/assets/data/employee.json';

  constructor(private http: HttpClient) { }

  getEmployees(): Observable<IEmployee[]> {
    return this.http.get<IEmployee[]>(this.url)
                    .pipe(catchError(this.errorHandler));  // catch error
  }

  /** Error Handling method */

  errorHandler(error: HttpErrorResponse) {
    if (error.error instanceof ErrorEvent) {
      // A client-side or network error occurred. Handle it accordingly.
      console.error('An error occurred:', error.error.message);
    } else {
      // The backend returned an unsuccessful response code.
      // The response body may contain clues as to what went wrong,
      console.error(
        `Backend returned code ${error.status}, ` +
        `body was: ${error.error}`);
    }
    // return an observable with a user-facing error message
    return throwError(
      'Something bad happened; please try again later.');
  }
}

For more details, refer to the Angular Guide for Http

javascript function wait until another function to finish

Following answer can help in this and other similar situations like synchronous AJAX call -

Working example

waitForMe().then(function(intentsArr){
  console.log('Finally, I can execute!!!');
},
function(err){
  console.log('This is error message.');
})

function waitForMe(){
    // Returns promise
    console.log('Inside waitForMe');
    return new Promise(function(resolve, reject){
        if(true){ // Try changing to 'false'
            setTimeout(function(){
                console.log('waitForMe\'s function succeeded');
                resolve();
            }, 2500);
        }
        else{
            setTimeout(function(){
                console.log('waitForMe\'s else block failed');
                resolve();
            }, 2500);
        }
    });
}

What does the SQL Server Error "String Data, Right Truncation" mean and how do I fix it?

Either the parameter supplied for ZIP_CODE is larger (in length) than ZIP_CODEs column width or the parameter supplied for CITY is larger (in length) than CITYs column width.

It would be interesting to know the values supplied for the two ? placeholders.

Dynamically add child components in React

You need to pass your components as children, like this:

var App = require('./App.js');
var SampleComponent = require('./SampleComponent.js');
ReactDOM.render(
    <App>
        <SampleComponent name="SomeName"/> 
    <App>, 
    document.body
);

And then append them in the component's body:

var App = React.createClass({
    render: function() {
        return (
            <div>
                <h1>App main component! </h1>
                {
                    this.props.children
                }
            </div>
        );
    }
});

You don't need to manually manipulate HTML code, React will do that for you. If you want to add some child components, you just need to change props or state it depends. For example:

var App = React.createClass({

    getInitialState: function(){
        return [
            {id:1,name:"Some Name"}
        ]
    },

    addChild: function() {
        // State change will cause component re-render
        this.setState(this.state.concat([
            {id:2,name:"Another Name"}
        ]))
    }

    render: function() {
        return (
            <div>
                <h1>App main component! </h1>
                <button onClick={this.addChild}>Add component</button>
                {
                    this.state.map((item) => (
                        <SampleComponent key={item.id} name={item.name}/>
                    ))
                }
            </div>
        );
    }

});

HTML Code for text checkbox '?'

?

this is a character . You can do copy/past without problem

Get IFrame's document, from JavaScript in main document

You should be able to access the document in the IFRAME using the following code:

document.getElementById('myframe').contentWindow.document

However, you will not be able to do this if the page in the frame is loaded from a different domain (such as google.com). THis is because of the browser's Same Origin Policy.

Reset/remove CSS styles for element only

For future readers. I think this is what was meant but currently isn't really wide supported (see below):

#someselector {
  all: initial;
  * {
    all: unset;
  }
}
  • Supported in (source): Chrome 37, Firefox 27, IE 11, Opera 24
  • Not supported: Safari

C# how to use enum with switch

All the other answers are correct, but you also need to call your method correctly:

Calculate(5, 5, Operator.PLUS))

And since you use int for left and right, the result will be int as well (3/2 will result in 1). you could cast to double before calculating the result or modify your parameters to accept double

How to change identity column values programmatically?

Through the UI in SQL Server 2005 manager, change the column remove the autonumber (identity) property of the column (select the table by right clicking on it and choose "Design").

Then run your query:

UPDATE table SET Id = Id + 1

Then go and add the autonumber property back to the column.

swift 3.0 Data to String?

Swift 4 version of 4redwings's answer:

let testString = "This is a test string"
let somedata = testString.data(using: String.Encoding.utf8)
let backToString = String(data: somedata!, encoding: String.Encoding.utf8)

differences in application/json and application/x-www-form-urlencoded

webRequest.ContentType = "application/x-www-form-urlencoded";

  1. Where does application/x-www-form-urlencoded's name come from?

    If you send HTTP GET request, you can use query parameters as follows:

    http://example.com/path/to/page?name=ferret&color=purple

    The content of the fields is encoded as a query string. The application/x-www-form- urlencoded's name come from the previous url query parameter but the query parameters is in where the body of request instead of url.

    The whole form data is sent as a long query string.The query string contains name- value pairs separated by & character

    e.g. field1=value1&field2=value2

  2. It can be simple request called simple - don't trigger a preflight check

    Simple request must have some properties. You can look here for more info. One of them is that there are only three values allowed for Content-Type header for simple requests

    • application/x-www-form-urlencoded
    • multipart/form-data
    • text/plain

3.For mostly flat param trees, application/x-www-form-urlencoded is tried and tested.

request.ContentType = "application/json; charset=utf-8";

  1. The data will be json format.

axios and superagent, two of the more popular npm HTTP libraries, work with JSON bodies by default.

{
  "id": 1,
  "name": "Foo",
  "price": 123,
  "tags": [
    "Bar",
    "Eek"
  ],
  "stock": {
    "warehouse": 300,
    "retail": 20
  }
}
  1. "application/json" Content-Type is one of the Preflighted requests.

Now, if the request isn't simple request, the browser automatically sends a HTTP request before the original one by OPTIONS method to check whether it is safe to send the original request. If itis ok, Then send actual request. You can look here for more info.

  1. application/json is beginner-friendly. URL encoded arrays can be a nightmare!

jQuery / Javascript code check, if not undefined

$.fn.attr(attributeName) returns the attribute value as string, or undefined when the attribute is not present.

Since "", and undefined are both falsy (evaluates to false when coerced to boolean) values in JavaScript, in this case I would write the check as below:

if (wlocation) { ... }

React: "this" is undefined inside a component function

I ran into a similar bind in a render function and ended up passing the context of this in the following way:

{someList.map(function(listItem) {
  // your code
}, this)}

I've also used:

{someList.map((listItem, index) =>
    <div onClick={this.someFunction.bind(this, listItem)} />
)}

how to start the tomcat server in linux?

Go to your Tomcat Directory with : cd/home/user/apache-tomcat6.0

  • sh bin/startup.sh.>> tail -f logs/catelina.out.>>

FCM getting MismatchSenderId

You will have a server key something like this AIzaSyDiTEVq4Li1pj7IyraRlyRU9adc-49-KVY available in the Settings section of firebase console console.firebase.google.com/project/project-XXXXXXXXXXXXX/settings/cloudmessaging.

Specify the correct key with your code and try again.

Unable to execute dex: method ID not in [0, 0xffff]: 65536

Your project is too large. You have too many methods. There can only be 65536 methods per application. see here https://code.google.com/p/android/issues/detail?id=7147#c6

PHP - SSL certificate error: unable to get local issuer certificate

Another reason this error can occur is if a CA bundle has been removed from your system (and is no longer available in ca-certificates).

This is currently the situation with the GeoTrust Global CA which (among other things) is used to sign Apple's certificate for APNS used for Push Notifications.

Additional details can be found on the bug report here: https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=962596

You can manually add the GeoTrust Global CA certificate on your machine as suggested by Carlos Alberto Lopez Perez:

wget --no-check-certificate -c https://www.geotrust.com/resources/root_certificates/certificates/GeoTrust_Global_CA.pem   \
&& mkdir /usr/local/share/ca-certificates/extra                                                                       \
&& mv GeoTrust_Global_CA.pem /usr/local/share/ca-certificates/extra/GeoTrust_Global_CA.crt                            \
&& update-ca-certificates

How should I edit an Entity Framework connection string?

Follow the next steps:

  1. Open the app.config and comment on the connection string (save file)
  2. Open the edmx (go to properties, the connection string should be blank), close the edmx file again
  3. Open the app.config and uncomment the connection string (save file)
  4. Open the edmx, go to properties, you should see the connection string uptated!!

installation app blocked by play protect

the only solution worked for me was using java keytool and generating a .keystore file the command line and then use that .keystore file to sign my app

you can find the java keytool at this directory C:\Program Files\Java\jre7\bin

open a command window and switch to that directory and enter a command like this

keytool -genkey -v -keystore my-release-key.keystore -alias alias_name -keyalg RSA -keysize 2048 -validity 10000

Keytool prompts you to provide passwords for the keystore, your name , company etc . note that at the last prompt you need to enter yes.

It then generates the keystore as a file called my-release-key.keystore in the directory you're in. The keystore and key are protected by the passwords you entered. The keystore contains a single key, valid for 10000 days. The alias is a name that you — will use later, to refer to this keystore when signing your application.

For more information about Keytool, see the documentation at: http://docs.oracle.com/javase/6/docs/technotes/tools/windows/keytool.html

and for more information on signing Android apps go here: http://developer.android.com/tools/publishing/app-signing.html

How to force DNS refresh for a website?

So if the issue is you just created a website and your clients or any given ISP DNS is cached and doesn't show new site yet. Yes all the other stuff applies ipconfig reset browser etc. BUT here's an Idea and something I do from time to time. You can set an alternate network ISP's DNS in the tcpip properties on the NIC properties. So if your ISP is say telstra and it hasn't propagated or updated you can specify an alternate service providers dns there. if that isp dns is updated before your native one hey presto you will see new site.But there is lots of other tricks you can do to determine propagation and get mail to work prior to the DNS updating. drop me a line if any one wants to chat.

Loading basic HTML in Node.js

I just found one way using the fs library. I'm not certain if it's the cleanest though.

var http = require('http'),
    fs = require('fs');


fs.readFile('./index.html', function (err, html) {
    if (err) {
        throw err; 
    }       
    http.createServer(function(request, response) {  
        response.writeHeader(200, {"Content-Type": "text/html"});  
        response.write(html);  
        response.end();  
    }).listen(8000);
});

The basic concept is just raw file reading and dumping the contents. Still open to cleaner options, though!

Unable to set variables in bash script

here's your amended script

#!/bin/bash    
folder="ABC" #no spaces between assignment    
useracct='test'    
day=$(date "+%d") # use $() to assign return value of date command to variable    
month=$(date "+%B")     
year=$(date "+%Y")    
folderToBeMoved="/users/$useracct/Documents/Archive/Primetime.eyetv"    
newfoldername="/Volumes/Media/Network/$folder/$month$day$year"    
ECHO "Network is $network" $network    
ECHO "day is $day"    
ECHO "Month is $month"    
ECHO "YEAR is $year"    
ECHO "source is $folderToBeMoved"    
ECHO "dest is $newfoldername"    

mkdir "$newfoldername"    
cp -R "$folderToBeMoved" "$newfoldername"
if [ -f "$newfoldername/Primetime.eyetv" ]; then # <-- put a space at square brackets and quote your variables.
 rm "$folderToBeMoved";
fi

Bash command to sum a column of numbers

Does two lines count?

awk '{ sum += $1; }
     END { print sum; }' "$@"

You can then use it without the superfluous 'cat':

sum < FileWithColumnOfNumbers.txt
sum   FileWithColumnOfNumbers.txt

FWIW: on MacOS X, you can do it with a one-liner:

awk '{ sum += $1; } END { print sum; }' "$@"

What is the best/safest way to reinstall Homebrew?

Update 10/11/2020 to reflect the latest brew changes.

Brew already provide a command to uninstall itself (this will remove everything you installed with Homebrew):

/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/uninstall.sh)"

If you failed to run this command due to permission (like run as second user), run again with sudo

Then you can install again:

/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install.sh)"

Get current user id in ASP.NET Identity 2.0

GetUserId() is an extension method on IIdentity and it is in Microsoft.AspNet.Identity.IdentityExtensions. Make sure you have added the namespace with using Microsoft.AspNet.Identity;.

ImportError: No module named 'selenium'

If you have pip installed you can install selenium like so.

pip install selenium

or depending on your permissions:

sudo pip install selenium

For python3:

sudo pip3 install selenium

As you can see from this question pip vs easy_install pip is a more reliable package installer as it was built to improve easy_install.

I would also suggest that when creating new projects you do so in virtual environments, even a simple selenium project. You can read more about virtual environments here. In fact pip is included out of the box with virtualenv!

How to use UIVisualEffectView to Blur Image?

You can also use the interface builder to create these effects easily for simple situations. Since the z-values of the views will depend on the order they are listed in the Document Outline, you can drag a UIVisualEffectView onto the document outline before the view you want to blur. This automatically creates a nested UIView, which is the contentView property of the given UIVisualEffectView. Nest things within this view that you want to appear on top of the blur.

XCode6 beta5

You can also easily take advantage of the vibrancy UIVisualEffect, which will automatically create another nested UIVisualEffectView in the document outline with vibrancy enabled by default. You can then add a label or text view to the nested UIView (again, the contentView property of the UIVisualEffectView), to achieve the same effect that the "> slide to unlock" UI element.

enter image description here

unresolved external symbol __imp__fprintf and __imp____iob_func, SDL2

This can happen when you link to msvcrt.dll instead of msvcr10.dll (or similar), which is a good plan. Because it will free you up to redistribute your Visual Studio's runtime library inside your final software package.

That workaround helps me (at Visual Studio 2008):

#if _MSC_VER >= 1400
#undef stdin
#undef stdout
#undef stderr
extern "C" _CRTIMP extern FILE _iob[];
#define stdin   _iob
#define stdout  (_iob+1)
#define stderr  (_iob+2)
#endif

This snippet is not needed for Visual Studio 6 and its compiler. Therefore the #ifdef.

How do I set session timeout of greater than 30 minutes

Setting the timeout in the web.xml is the correct way to set the timeout.

Set object property using reflection

Yes, you can use Type.InvokeMember():

using System.Reflection;
MyObject obj = new MyObject();
obj.GetType().InvokeMember("Name",
    BindingFlags.Instance | BindingFlags.Public | BindingFlags.SetProperty,
    Type.DefaultBinder, obj, "Value");

This will throw an exception if obj doesn't have a property called Name, or it can't be set.

Another approach is to get the metadata for the property, and then set it. This will allow you to check for the existence of the property, and verify that it can be set:

using System.Reflection;
MyObject obj = new MyObject();
PropertyInfo prop = obj.GetType().GetProperty("Name", BindingFlags.Public | BindingFlags.Instance);
if(null != prop && prop.CanWrite)
{
    prop.SetValue(obj, "Value", null);
}

How to change colour of blue highlight on select box dropdown

To both style the hover color and avoid the OS default color in Firefox, you need to add a box-shadow to both the select option and select option:hover declarations, setting the color of the box-shadow on "select option" to the menu background color.

select option {
  background: #f00; 
  color: #fff; 
  box-shadow: inset 20px 20px #f00
} 

select option:hover {
  color: #000; 
  box-shadow: inset 20px 20px #00f;
}

How to safely call an async method in C# without await

You should first consider making GetStringData an async method and have it await the task returned from MyAsyncMethod.

If you're absolutely sure that you don't need to handle exceptions from MyAsyncMethod or know when it completes, then you can do this:

public string GetStringData()
{
  var _ = MyAsyncMethod();
  return "hello world";
}

BTW, this is not a "common problem". It's very rare to want to execute some code and not care whether it completes and not care whether it completes successfully.

Update:

Since you're on ASP.NET and wanting to return early, you may find my blog post on the subject useful. However, ASP.NET was not designed for this, and there's no guarantee that your code will run after the response is returned. ASP.NET will do its best to let it run, but it can't guarantee it.

So, this is a fine solution for something simple like tossing an event into a log where it doesn't really matter if you lose a few here and there. It's not a good solution for any kind of business-critical operations. In those situations, you must adopt a more complex architecture, with a persistent way to save the operations (e.g., Azure Queues, MSMQ) and a separate background process (e.g., Azure Worker Role, Win32 Service) to process them.

applying css to specific li class

The CSS you have applies color #c1c1c1 to all <a> elements.

And it also applies color #c1c1c1 to the first <li> element.

Perhaps the code you posted is missing something because I don't see any other colors being defined.

Deleting a local branch with Git

Ran into this today and switching to another branch didn't help. It turned out that somehow my worktree information had gotten corrupted and there was a worktree with the same folder path as my working directory with a HEAD pointing at the branch (git worktree list). I deleted the .git/worktree/ folder that was referencing it and git branch -d worked.

Get Android Device Name

@hbhakhra's answer will do.

If you're interested in detailed explanation, it is useful to look into Android Compatibility Definition Document. (3.2.2 Build Parameters)

You will find:

DEVICE - A value chosen by the device implementer containing the development name or code name identifying the configuration of the hardware features and industrial design of the device. The value of this field MUST be encodable as 7-bit ASCII and match the regular expression “^[a-zA-Z0-9_-]+$”.

MODEL - A value chosen by the device implementer containing the name of the device as known to the end user. This SHOULD be the same name under which the device is marketed and sold to end users. There are no requirements on the specific format of this field, except that it MUST NOT be null or the empty string ("").

MANUFACTURER - The trade name of the Original Equipment Manufacturer (OEM) of the product. There are no requirements on the specific format of this field, except that it MUST NOT be null or the empty string ("").

How to select first child with jQuery?

Use the :first-child selector.

In your example...

$('div.alldivs div:first-child')

This will also match any first child descendents that meet the selection criteria.

While :first matches only a single element, the :first-child selector can match more than one: one for each parent. This is equivalent to :nth-child(1).

For the first matched only, use the :first selector.

Alternatively, Felix Kling suggested using the direct descendent selector to get only direct children...

$('div.alldivs > div:first-child')

jquery if div id has children

Another option, just for the heck of it would be:

if ( $('#myFav > *').length > 0 ) {
     // do something
}

May actually be the fastest since it strictly uses the Sizzle engine and not necessarily any jQuery, as it were. Could be wrong though. Nevertheless, it works.

Embedding a media player in a website using HTML

I found the that either IE or Chrome choked on most of these, or they required external libraries. I just wanted to play an MP3, and I found the page http://www.w3schools.com/html/html_sounds.asp very helpful.

<audio controls>
  <source src="horse.mp3" type="audio/mpeg">
  <embed height="50" width="100" src="horse.mp3">
</audio>

Worked for me in the browsers I tried, but I didn't have some of the old ones around at this time.

How to get a matplotlib Axes instance to plot to?

Use the gca ("get current axes") helper function:

ax = plt.gca()

Example:

import matplotlib.pyplot as plt
import matplotlib.finance
quotes = [(1, 5, 6, 7, 4), (2, 6, 9, 9, 6), (3, 9, 8, 10, 8), (4, 8, 8, 9, 8), (5, 8, 11, 13, 7)]
ax = plt.gca()
h = matplotlib.finance.candlestick(ax, quotes)
plt.show()

enter image description here

d3 add text to circle

Extended the example above to fit the actual requirements, where circled is filled with solid background color, then with striped pattern & after that text node is placed on the center of the circle.

_x000D_
_x000D_
var width = 960,_x000D_
  height = 500,_x000D_
  json = {_x000D_
    "nodes": [{_x000D_
      "x": 100,_x000D_
      "r": 20,_x000D_
      "label": "Node 1",_x000D_
      "color": "red"_x000D_
    }, {_x000D_
      "x": 200,_x000D_
      "r": 25,_x000D_
      "label": "Node 2",_x000D_
      "color": "blue"_x000D_
    }, {_x000D_
      "x": 300,_x000D_
      "r": 30,_x000D_
      "label": "Node 3",_x000D_
      "color": "green"_x000D_
    }]_x000D_
  };_x000D_
_x000D_
var svg = d3.select("body").append("svg")_x000D_
  .attr("width", width)_x000D_
  .attr("height", height)_x000D_
_x000D_
svg.append("defs")_x000D_
  .append("pattern")_x000D_
  .attr({_x000D_
    "id": "stripes",_x000D_
    "width": "8",_x000D_
    "height": "8",_x000D_
    "fill": "red",_x000D_
    "patternUnits": "userSpaceOnUse",_x000D_
    "patternTransform": "rotate(60)"_x000D_
  })_x000D_
  .append("rect")_x000D_
  .attr({_x000D_
    "width": "4",_x000D_
    "height": "8",_x000D_
    "transform": "translate(0,0)",_x000D_
    "fill": "grey"_x000D_
  });_x000D_
_x000D_
function plotChart(json) {_x000D_
  /* Define the data for the circles */_x000D_
  var elem = svg.selectAll("g myCircleText")_x000D_
    .data(json.nodes)_x000D_
_x000D_
  /*Create and place the "blocks" containing the circle and the text */_x000D_
  var elemEnter = elem.enter()_x000D_
    .append("g")_x000D_
    .attr("class", "node-group")_x000D_
    .attr("transform", function(d) {_x000D_
      return "translate(" + d.x + ",80)"_x000D_
    })_x000D_
_x000D_
  /*Create the circle for each block */_x000D_
  var circleInner = elemEnter.append("circle")_x000D_
    .attr("r", function(d) {_x000D_
      return d.r_x000D_
    })_x000D_
    .attr("stroke", function(d) {_x000D_
      return d.color;_x000D_
    })_x000D_
    .attr("fill", function(d) {_x000D_
      return d.color;_x000D_
    });_x000D_
_x000D_
  var circleOuter = elemEnter.append("circle")_x000D_
    .attr("r", function(d) {_x000D_
      return d.r_x000D_
    })_x000D_
    .attr("stroke", function(d) {_x000D_
      return d.color;_x000D_
    })_x000D_
    .attr("fill", "url(#stripes)");_x000D_
_x000D_
  /* Create the text for each block */_x000D_
  elemEnter.append("text")_x000D_
    .text(function(d) {_x000D_
      return d.label_x000D_
    })_x000D_
    .attr({_x000D_
      "text-anchor": "middle",_x000D_
      "font-size": function(d) {_x000D_
        return d.r / ((d.r * 10) / 100);_x000D_
      },_x000D_
      "dy": function(d) {_x000D_
        return d.r / ((d.r * 25) / 100);_x000D_
      }_x000D_
    });_x000D_
};_x000D_
_x000D_
plotChart(json);
_x000D_
.node-group {_x000D_
  fill: #ffffff;_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
_x000D_
_x000D_
_x000D_

Output:

enter image description here

Below is the link to codepen also:

See the Pen D3-Circle-Pattern-Text by Manish Kumar (@mkdudeja) on CodePen.

Thanks, Manish Kumar

SQL Server : login success but "The database [dbName] is not accessible. (ObjectExplorer)"

I just restarted my SQL Server (MSSQLSERVER) with which my SQL Server Agent (MSSQLSERVER) also got restarted. Now am able to access the SQL SERVER 2008 R2 database instance through SSMS with my login.

CSS endless rotation animation

@keyframes rotate {
    100% {
        transform: rotate(1turn);
    }
}

div{
   animation: rotate 4s linear infinite;
}

How do I make a placeholder for a 'select' box?

Here I have modified David's answer (accepted answer). On his answer, he put disabled and selected attribute on the option tag, but when we also put hidden tag then it will look much better.

By adding an extra hidden attribute on the option tag, it will prevent the "Select your option" option from being re-selecting after the "Durr" option is selected.

_x000D_
_x000D_
<select>_x000D_
    <option value="" disabled selected hidden>Select your option</option>_x000D_
    <option value="hurr">Durr</option>_x000D_
</select>
_x000D_
_x000D_
_x000D_

How to fetch all Git branches

Make sure all the remote branches are fetchable in .git/config file.

In this example, only the origin/production branch is fetchable, even if you try to do git fetch --all nothing will happen but fetching the production branch:

[origin]
fetch = +refs/heads/production:refs/remotes/origin/production

This line should be replaced by:

[origin]
fetch = +refs/heads/*:refs/remotes/origin/*

Then run git fetch etc...

How to download a Nuget package without nuget.exe or Visual Studio extension?

Either make an account on the Nuget.org website, then log in, browse to the package you want and click on the Download link on the left menu.


Or guess the URL. They have the following format:

https://www.nuget.org/api/v2/package/{packageID}/{packageVersion}

Then simply unzip the .nupkg file and extract the contents you need.

How to set JAVA_HOME in Mac permanently?

Declare two export inside your .bashrc or .zshrc:

export JAVA_8_HOME=$(/usr/libexec/java_home -v1.8) 
export JAVA_11_HOME=$(/usr/libexec/java_home -v11)

Add alias for quick change:

alias java8='export JAVA_HOME=$JAVA_8_HOME'
alias java11='export JAVA_HOME=$JAVA_11_HOME'

set default to Java 11

java11

export PATH

export PATH=$JAVA_HOME/bin:$PATH

you could change java11 by java8 inside your .bashrc/zshrc file to change permanently your java version

Hard reset of a single file

To revert to upstream/master do:

git checkout upstream/master -- myfile.txt

Reporting Services permissions on SQL Server R2 SSRS

This did the trick for me. http://thecodeattic.wordpress.com/category/ssrs/. Go down to step 35 to see the error you are getting. Paraphrasing:

Once you're able to log in to YourServer/Reports as an administrator, click Home in the top-right corner, then Folder Settings and New Role Assignment. Enter your user name and check a box for each role you want to grant yourself. Finally, click OK. You should now be able to browse folders without launching your browser with elevated privileges.

Don't forget to set the security at the site level **AND ** at the folder level. I hope that helps.

Rick

How can I change the class of an element with jQuery>

To set a class completely, instead of adding one or removing one, use this:

$(this).attr("class","newclass");

Advantage of this is that you'll remove any class that might be set in there and reset it to how you like. At least this worked for me in one situation.

How do I get the Session Object in Spring?

Your friend here is org.springframework.web.context.request.RequestContextHolder

// example usage
public static HttpSession session() {
    ServletRequestAttributes attr = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
    return attr.getRequest().getSession(true); // true == allow create
}

This will be populated by the standard spring mvc dispatch servlet, but if you are using a different web framework you have add org.springframework.web.filter.RequestContextFilter as a filter in your web.xml to manage the holder.

EDIT: just as a side issue what are you actually trying to do, I'm not sure you should need access to the HttpSession in the retieveUser method of a UserDetailsService. Spring security will put the UserDetails object in the session for you any how. It can be retrieved by accessing the SecurityContextHolder:

public static UserDetails currentUserDetails(){
    SecurityContext securityContext = SecurityContextHolder.getContext();
    Authentication authentication = securityContext.getAuthentication();
    if (authentication != null) {
        Object principal = authentication.getPrincipal();
        return principal instanceof UserDetails ? (UserDetails) principal : null;
    }
    return null;
}

jQuery count number of divs with a certain class?

<!DOCTYPE html>
    <html>
    <head>
        <title></title>
        <style type="text/css">
            .test {
                background: #ff4040;
                color: #fff;
                display: block;
                font-size: 15px;
            }
        </style>
    </head>
    <body>
        <div class="test"> one </div>
        <div class="test"> two </div>
        <div class="test"> three </div>
        <div class="test"> four </div>
        <div class="test"> five </div>
        <div class="test"> six </div>
        <div class="test"> seven </div>
        <div class="test"> eight </div>
        <div class="test"> nine </div>
        <div class="test"> ten </div>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
        <script type="text/javascript">
        $(document).ready(function () {
            //get total length by class
            var numItems = $('.test').length;
            //get last three count
            var numItems3=numItems-3;         


            var i = 0;
            $('.test').each(function(){
                i++;
                if(i>numItems3)
                {

                    $(this).attr("class","");
                }
            })
        });
    </script>
    </body>
    </html>

I have never set any passwords to my keystore and alias, so how are they created?

Keystore name: "debug.keystore"

Keystore password: "android"

Key alias: "androiddebugkey"

Key password: "android"

I use this information and successfully generate Signed APK.

How can I create a keystore?

I was crazy looking how to generate a .keystore using in the shell a single line command, so I could run it from another application. This is the way:

echo y | keytool -genkeypair -dname "cn=Mark Jones, ou=JavaSoft, o=Sun, c=US" -alias business -keypass kpi135 -keystore /working/android.keystore -storepass ab987c -validity 20000
  • dname is a unique identifier for the application in the .keystore

    • cn the full name of the person or organization that generates the .keystore
    • ou Organizational Unit that creates the project, its a subdivision of the Organization that creates it. Ex. android.google.com
    • o Organization owner of the whole project. Its a higher scope than ou. Ex.: google.com
    • c The country short code. Ex: For United States is "US"
  • alias Identifier of the app as an single entity inside the .keystore (it can have many)

  • keypass Password for protecting that specific alias.
  • keystore Path where the .keystore file shall be created (the standard extension is actually .ks)
  • storepass Password for protecting the whole .keystore content.
  • validity Amout of days the app will be valid with this .keystore

It worked really well for me, it doesnt ask for anything else in the console, just creates the file. For more information see keytool - Key and Certificate Management Tool.

How can I pass request headers with jQuery's getJSON() method?

I think you could set the headers and still use getJSON() like this:

$.ajaxSetup({
  headers : {
    'Authorization' : 'Basic faskd52352rwfsdfs',
    'X-PartnerKey' : '3252352-sdgds-sdgd-dsgs-sgs332fs3f'
  }
});
$.getJSON('http://localhost:437/service.svc/logins/jeffrey/house/fas6347/devices?format=json', function(json) { alert("Success"); }); 

LD_LIBRARY_PATH vs LIBRARY_PATH

LIBRARY_PATH is used by gcc before compilation to search directories containing static and shared libraries that need to be linked to your program.

LD_LIBRARY_PATH is used by your program to search directories containing shared libraries after it has been successfully compiled and linked.

EDIT: As pointed below, your libraries can be static or shared. If it is static then the code is copied over into your program and you don't need to search for the library after your program is compiled and linked. If your library is shared then it needs to be dynamically linked to your program and that's when LD_LIBRARY_PATH comes into play.

Get Selected value of a Combobox

Maybe you'll be able to set the event handlers programmatically, using something like (pseudocode)

sub myhandler(eventsource)
  process(eventsource.value)
end sub

for each cell
  cell.setEventHandler(myHandler)

But i dont know the syntax for achieving this in VB/VBA, or if is even possible.

CSS div element - how to show horizontal scroll bars only?

you can also make it overflow: auto and give a maximum fixed height and width that way, when the text or whatever is in there, overflows it'll show only the required scrollbar

Markdown and including multiple files

You can actually use the Markdown Preprocessor (MarkdownPP). Running with the hypothetical book example from the other answers, you would create .mdpp files representing your chapters. The .mdpp files can then use the !INCLUDE "path/to/file.mdpp" directive, which operates recursively replacing the directive with the contents of the referenced file in the final output.

chapters/preface.mdpp
chapters/introduction.mdpp
chapters/why_markdown_is_useful.mdpp
chapters/limitations_of_markdown.mdpp
chapters/conclusions.mdpp

You would then need an index.mdpp that contained the following:

!INCLUDE "chapters/preface.mdpp"
!INCLUDE "chapters/introduction.mdpp"
!INCLUDE "chapters/why_markdown_is_useful.mdpp"
!INCLUDE "chapters/limitations_of_markdown.mdpp"
!INCLUDE "chapters/conclusions.mdpp"

To render your book you simply run the preprocessor on index.mdpp:

$ markdown-pp.py index.mdpp mybook.md

Don't forget to look at the readme.mdpp in the MarkdownPP repository for an exposition of preprocessor features suited for larger documentation projects.

Sort JavaScript object by key

Maybe a bit more elegant form:

_x000D_
_x000D_
 /**_x000D_
     * Sorts a key-value object by key, maintaining key to data correlations._x000D_
     * @param {Object} src  key-value object_x000D_
     * @returns {Object}_x000D_
     */_x000D_
var ksort = function ( src ) {_x000D_
      var keys = Object.keys( src ),_x000D_
          target = {};_x000D_
      keys.sort();_x000D_
      keys.forEach(function ( key ) {_x000D_
        target[ key ] = src[ key ];_x000D_
      });_x000D_
      return target;_x000D_
    };_x000D_
_x000D_
_x000D_
// Usage_x000D_
console.log(ksort({_x000D_
  a:1,_x000D_
  c:3,_x000D_
  b:2  _x000D_
}));
_x000D_
_x000D_
_x000D_

P.S. and the same with ES6+ syntax:

function ksort( src ) {
  const keys = Object.keys( src );
  keys.sort();
  return keys.reduce(( target, key ) => {
        target[ key ] = src[ key ];
        return target;
  }, {});
};

How to disable keypad popup when on edittext?

Simple,Just Remove "" tag from the xml file

Fetch API request timeout?

If you haven't configured timeout in your code, It will be the default request timeout of your browser.

1) Firefox - 90 seconds

Type about:config in Firefox URL field. Find the value corresponding to key network.http.connection-timeout

2) Chrome - 300 seconds

Source

How do you get the "object reference" of an object in java when toString() and hashCode() have been overridden?

What exactly are you planning on doing with it (what you want to do makes a difference with what you will need to call).

hashCode, as defined in the JavaDocs, says:

As much as is reasonably practical, the hashCode method defined by class Object does return distinct integers for distinct objects. (This is typically implemented by converting the internal address of the object into an integer, but this implementation technique is not required by the Java™ programming language.)

So if you are using hashCode() to find out if it is a unique object in memory that isn't a good way to do it.

System.identityHashCode does the following:

Returns the same hash code for the given object as would be returned by the default method hashCode(), whether or not the given object's class overrides hashCode(). The hash code for the null reference is zero.

Which, for what you are doing, sounds like what you want... but what you want to do might not be safe depending on how the library is implemented.

How can I toggle word wrap in Visual Studio?

In Visual Studio 2005 Pro:

Ctrl + E, Ctrl + W

Or menu Edit ? Advanced ? Word Wrap.

C# - How to convert string to char?

var theString = "TEST";
char[] myChar = theString.ToCharArray();

I tested this in the C# interactive window of Visual Studio 2019 and got:

char[4] { 'T', 'E', 'S', 'T' }

Can't access 127.0.0.1

If it's a DNS problem, you could try:

  • ipconfig /flushdns
  • ipconfig /registerdns

If this doesn't fix it, you could try editing the hosts file located here:

C:\Windows\System32\drivers\etc\hosts

And ensure that this line (and no other line referencing localhost) is in there:

127.0.0.1 localhost

Python sys.argv lists and indexes

sys.argv is the list of arguments passed to the Python program. The first argument, sys.argv[0], is actually the name of the program as it was invoked. That's not a Python thing, but how most operating systems work. The reason sys.argv[0] exists is so you can change your program's behaviour depending on how it was invoked. sys.argv[1] is thus the first argument you actually pass to the program.

Because lists (like most sequences) in Python start indexing at 0, and because indexing past the end of the list is an error, you need to check if the list has length 2 or longer before you can access sys.argv[1].

org.json.simple.JSONArray cannot be cast to org.json.simple.JSONObject

If you want to re-filter the json data you can use following method. Given example is getting all document data from couchdb.

{
    Gson gson = new Gson();
    String resultJson = restTemplate.getForObject(url+"_all_docs?include_docs=true", String.class);
    JSONObject object =  (JSONObject) new JSONParser().parse(resultJson);
    JSONArray rowdata = (JSONArray) object.get("rows");   
    List<Object>list=new ArrayList<Object>();   
    for(int i=0;i<rowdata.size();i++) {
        JSONObject index = (JSONObject) rowdata.get(i);
        JSONObject data = (JSONObject) index.get("doc");
        list.add(data);      
    }
    // convert your list to json
    String devicelist = gson.toJson(list);
    return devicelist;
}

Convert dataframe column to 1 or 0 for "true"/"false" values and assign to dataframe

can you try if.else

> col2=ifelse(df1$col=="true",1,0)
> df1
$col
[1] "true"  "false"

> cbind(df1$col)
     [,1]   
[1,] "true" 
[2,] "false"
> cbind(df1$col,col2)
             col2
[1,] "true"  "1" 
[2,] "false" "0" 

Best way to load module/class from lib folder in Rails 3?

# Autoload lib/ folder including all subdirectories
config.autoload_paths += Dir["#{config.root}/lib/**/"]

Source: Rails 3 Quicktip: Autoload lib directory including all subdirectories, avoid lazy loading

Please mind that files contained in the lib folder are only loaded when the server is started. If you want the comfort to autoreload those files, read: Rails 3 Quicktip: Auto reload lib folders in development mode. Be aware that this is not meant for a production environment since the permanent reload slows down the machine.

React hooks useState Array

To expand on Ryan's answer:

Whenever setStateValues is called, React re-renders your component, which means that the function body of the StateSelector component function gets re-executed.

React docs:

setState() will always lead to a re-render unless shouldComponentUpdate() returns false.

Essentially, you're setting state with:

setStateValues(allowedState);

causing a re-render, which then causes the function to execute, and so on. Hence, the loop issue.

To illustrate the point, if you set a timeout as like:

  setTimeout(
    () => setStateValues(allowedState),
    1000
  )

Which ends the 'too many re-renders' issue.

In your case, you're dealing with a side-effect, which is handled with UseEffectin your component functions. You can read more about it here.

How to read/write from/to file using Go?

Using io.Copy

package main

import (
    "io"
    "log"
    "os"
)

func main () {
    // open files r and w
    r, err := os.Open("input.txt")
    if err != nil {
        panic(err)
    }
    defer r.Close()

    w, err := os.Create("output.txt")
    if err != nil {
        panic(err)
    }
    defer w.Close()

    // do the actual work
    n, err := io.Copy(w, r)
    if err != nil {
        panic(err)
    }
    log.Printf("Copied %v bytes\n", n)
}

If you don't feel like reinventing the wheel, the io.Copy and io.CopyN may serve you well. If you check the source of the io.Copy function, it is nothing but one of the Mostafa's solutions (the 'basic' one, actually) packaged in the Go library. They are using a significantly larger buffer than he is, though.

How to set Oracle's Java as the default Java in Ubuntu?

See this; run

sudo  update-java-alternatives --list

to list off all the Java installations on a machine by name and directory, and then run

sudo  update-java-alternatives --set [JDK/JRE name e.g. java-8-oracle]

to choose which JRE/JDK to use.

If you want to use different JDKs/JREs for each Java task, you can run update-alternatives to configure one java executable at a time; you can run

sudo  update-alternatives --config java[Tab]

to see the Java commands that can be configured (java, javac, javah, javaws, etc). And then

sudo  update-alternatives --config [javac|java|javadoc|etc.]

will associate that Java task/command to a particular JDK/JRE.

You may also need to set JAVA_HOME for some applications: from this answer you can use

export JAVA_HOME=$(readlink -f /usr/bin/java | sed "s:bin/java::")

for JREs, or

export JAVA_HOME=$(readlink -f /usr/bin/java | sed "s:jre/bin/java::")

for JDKs.

How to create materialized views in SQL Server?

You might need a bit more background on what a Materialized View actually is. In Oracle these are an object that consists of a number of elements when you try to build it elsewhere.

An MVIEW is essentially a snapshot of data from another source. Unlike a view the data is not found when you query the view it is stored locally in a form of table. The MVIEW is refreshed using a background procedure that kicks off at regular intervals or when the source data changes. Oracle allows for full or partial refreshes.

In SQL Server, I would use the following to create a basic MVIEW to (complete) refresh regularly.

First, a view. This should be easy for most since views are quite common in any database Next, a table. This should be identical to the view in columns and data. This will store a snapshot of the view data. Then, a procedure that truncates the table, and reloads it based on the current data in the view. Finally, a job that triggers the procedure to start it's work.

Everything else is experimentation.

How does one target IE7 and IE8 with valid CSS?

The actual problem is not IE8, but the hacks that you use for earlier versions of IE.

IE8 is pretty close to be standards compliant, so you shouldn't need any hacks at all for it, perhaps only some tweaks. The problem is if you are using some hacks for IE6 and IE7; you will have to make sure that they only apply to those versions and not IE8.

I made the web site of our company compatible with IE8 a while ago. The only thing that I actually changed was adding the meta tag that tells IE that the pages are IE8 compliant...

How can bcrypt have built-in salts?

This is bcrypt:

Generate a random salt. A "cost" factor has been pre-configured. Collect a password.

Derive an encryption key from the password using the salt and cost factor. Use it to encrypt a well-known string. Store the cost, salt, and cipher text. Because these three elements have a known length, it's easy to concatenate them and store them in a single field, yet be able to split them apart later.

When someone tries to authenticate, retrieve the stored cost and salt. Derive a key from the input password, cost and salt. Encrypt the same well-known string. If the generated cipher text matches the stored cipher text, the password is a match.

Bcrypt operates in a very similar manner to more traditional schemes based on algorithms like PBKDF2. The main difference is its use of a derived key to encrypt known plain text; other schemes (reasonably) assume the key derivation function is irreversible, and store the derived key directly.


Stored in the database, a bcrypt "hash" might look something like this:

$2a$10$vI8aWBnW3fID.ZQ4/zo1G.q1lRps.9cGLcZEiGDMVr5yUP1KUOYTa

This is actually three fields, delimited by "$":

  • 2a identifies the bcrypt algorithm version that was used.
  • 10 is the cost factor; 210 iterations of the key derivation function are used (which is not enough, by the way. I'd recommend a cost of 12 or more.)
  • vI8aWBnW3fID.ZQ4/zo1G.q1lRps.9cGLcZEiGDMVr5yUP1KUOYTa is the salt and the cipher text, concatenated and encoded in a modified Base-64. The first 22 characters decode to a 16-byte value for the salt. The remaining characters are cipher text to be compared for authentication.

This example is taken from the documentation for Coda Hale's ruby implementation.

C# importing class into another class doesn't work

using is used for importing namespaces not classes.

So if your class is in namespace X

namespace X
{
    public class MyClass {
         void stuff() {

         }
    }
}

then to use it in another namespace where you want it

using System;
using X;

public class MyMainClass {
    static void Main() {
        MyClass test = new MyClass();
    }
}

How to install Android SDK on Ubuntu?

Option 1:

sudo apt update && sudo apt install android-sdk

The location of Android SDK on Linux can be any of the following:

  • /home/AccountName/Android/Sdk

  • /usr/lib/android-sdk

  • /Library/Android/sdk/

  • /Users/[USER]/Library/Android/sdk

Option 2:

  • Download the Android Studio.

  • Extract downloaded .zip file.

    The extracted folder name will read somewhat like android-studio

To keep navigation easy, move this folder to Home directory.

  • After moving, copy the moved folder by right clicking it. This action will place folder's location to clipboard.

  • Use Ctrl Alt T to open a terminal

  • Go to this folder's directory using cd /home/(USER NAME)/android-studio/bin/

  • Type this command to make studio.sh executable: chmod +x studio.sh

  • Type ./studio.sh

A pop up will be shown asking for installation settings. In my particular case, it is a fresh install so I'll go with selecting I do not have a previous version of Studio or I do not want to import my settings.

If you choose to import settings anyway, you may need to close any old project which is opened in order to get a working Android SDK.

./studio.sh popup

From now onwards, setup wizard will guide you.

Android studio setup wizard

Android Studio can work with both Open JDK and Oracle's JDK (recommended). Incase, Open JDK is installed the wizard will recommend installing Oracle Java JDK because some UI and performance issues are reported while using OpenJDK.

The downside with Oracle's JDK is that it won't update with the rest of your system like OpenJDK will.

The wizard may also prompt about the input problems with IDEA .

Select install type

Select Android studio install type

Verify installation settings

Verify Android studio installation settings

An emulator can also be configured as needed.

Android studio emulator configuration prompt

The wizard will start downloading the necessary SDK tools

The wizard may also show an error about Linux 32 Bit Libraries, which can be solved by using the below command:

sudo apt-get install libc6:i386 libncurses5:i386 libstdc++6:i386 lib32z1

After this, all the required components will be downloaded and installed automatically.

After everything is upto the mark, just click finish

Completed installation of Android studio

To make a Desktop icon, go to 'Configure' and then click 'Create Desktop Entry'

Creating Android studio desktop icon

Creating Android studio desktop icon for one or multiple users

source

How can I use the HTML5 canvas element in IE?

The page is using excanvas - a JS library that simulates the canvas element using IE's VML renderer.

Note that in Internet Explorer 9, the canvas tag is supported natively! See MSDN docs for details...

Adding external library in Android studio

To reference an external lib project without copy, just do this: - Insert this 2 lines on setting.gradle:

  include ':your-lib-name'
  project(':your-lib-name').projectDir = new File('/path-to-your-lib/your-lib-name)

Insert this line on on dependencies part of build.gradle file:

compile project(':your-lib-name')

Sync project

cannot call member function without object

If you want to call them like that, you should declare them static.

How to replace ${} placeholders in a text file?

I found this thread while wondering the same thing. It inspired me to this (careful with the backticks)

$ echo $MYTEST
pass!
$ cat FILE
hello $MYTEST world
$ eval echo `cat FILE`
hello pass! world

How to get the last N records in mongodb?

If I understand your question, you need to sort in ascending order.

Assuming you have some id or date field called "x" you would do ...

.sort()


db.foo.find().sort({x:1});

The 1 will sort ascending (oldest to newest) and -1 will sort descending (newest to oldest.)

If you use the auto created _id field it has a date embedded in it ... so you can use that to order by ...

db.foo.find().sort({_id:1});

That will return back all your documents sorted from oldest to newest.

Natural Order


You can also use a Natural Order mentioned above ...

db.foo.find().sort({$natural:1});

Again, using 1 or -1 depending on the order you want.

Use .limit()


Lastly, it's good practice to add a limit when doing this sort of wide open query so you could do either ...

db.foo.find().sort({_id:1}).limit(50);

or

db.foo.find().sort({$natural:1}).limit(50);

How to printf a 64-bit integer as hex?

Edit: Use printf("val = 0x%" PRIx64 "\n", val); instead.

Try printf("val = 0x%llx\n", val);. See the printf manpage:

ll (ell-ell). A following integer conversion corresponds to a long long int or unsigned long long int argument, or a following n conversion corresponds to a pointer to a long long int argument.

Edit: Even better is what @M_Oehm wrote: There is a specific macro for that, because unit64_t is not always a unsigned long long: PRIx64 see also this stackoverflow answer

How to check if an excel cell is empty using Apache POI?

Cell cell = row.getCell(x, Row.CREATE_NULL_AS_BLANK);

This trick helped me a lot, see if it's useful for you

Content Type text/xml; charset=utf-8 was not supported by service

I was also facing the same problem recently. after struggling a couple of hours,finally a solution came out by addition to

Factory="System.ServiceModel.Activation.WebServiceHostFactory"
to your SVC markup file. e.g.
ServiceHost Language="C#" Debug="true" Service="QuiznetOnline.Web.UI.WebServices.LogService" 
Factory="System.ServiceModel.Activation.WebServiceHostFactory" 

and now you can compile & run your application successfully.

npm WARN enoent ENOENT: no such file or directory, open 'C:\Users\Nuwanst\package.json'

If you're trying to npm install on a folder that's being rsync'd from somewhere else, remember to add this to your rsync --exclude

yourpath/node_modules

Otherwise, NPM will try to add node_modules and rsync will remove it immediately, causing many npm WARN enoent ENOENT: no such file or directory, open errors.

Check if string is in a pandas dataframe

a['Names'].str.contains('Mel') will return an indicator vector of boolean values of size len(BabyDataSet)

Therefore, you can use

mel_count=a['Names'].str.contains('Mel').sum()
if mel_count>0:
    print ("There are {m} Mels".format(m=mel_count))

Or any(), if you don't care how many records match your query

if a['Names'].str.contains('Mel').any():
    print ("Mel is there")

Is there a way to detect if an image is blurry?

Answers above elucidated many things, but I think it is useful to make a conceptual distinction.

What if you take a perfectly on-focus picture of a blurred image?

The blurring detection problem is only well posed when you have a reference. If you need to design, e.g., an auto-focus system, you compare a sequence of images taken with different degrees of blurring, or smoothing, and you try to find the point of minimum blurring within this set. I other words you need to cross reference the various images using one of the techniques illustrated above (basically--with various possible levels of refinement in the approach--looking for the one image with the highest high-frequency content).

How to print number with commas as thousands separators?

From the comments to activestate recipe 498181 I reworked this:

import re
def thous(x, sep=',', dot='.'):
    num, _, frac = str(x).partition(dot)
    num = re.sub(r'(\d{3})(?=\d)', r'\1'+sep, num[::-1])[::-1]
    if frac:
        num += dot + frac
    return num

It uses the regular expressions feature: lookahead i.e. (?=\d) to make sure only groups of three digits that have a digit 'after' them get a comma. I say 'after' because the string is reverse at this point.

[::-1] just reverses a string.

Is there a download function in jsFiddle?

The best way is:

  1. Right-click on the output panel.
  2. Choose view frame source, then the whole code will appear.

After that you can copy that code, and paste it in your computer.

Excel VBA select range at last row and column

The simplest modification (to the code in your question) is this:

    Range("A" & Rows.Count).End(xlUp).Select
    Selection.EntireRow.Delete

Which can be simplified to:

    Range("A" & Rows.Count).End(xlUp).EntireRow.Delete

Doctrine findBy 'does not equal'

There is now a an approach to do this, using Doctrine's Criteria.

A full example can be seen in How to use a findBy method with comparative criteria, but a brief answer follows.

use \Doctrine\Common\Collections\Criteria;

// Add a not equals parameter to your criteria
$criteria = new Criteria();
$criteria->where(Criteria::expr()->neq('prize', 200));

// Find all from the repository matching your criteria
$result = $entityRepository->matching($criteria);

UDP vs TCP, how much faster is it?

There has been some work done to allow the programmer to have the benefits of both worlds.

SCTP

It is an independent transport layer protolol, but it can be used as a library providing additional layer over UDP. The basic unit of communication is a message (mapped to one or more UDP packets). There is congestion control built in. The protocol has knobs and twiddles to switch on

  • in order delivery of messages
  • automatic retransmission of lost messages, with user defined parameters

if any of this is needed for your particular application.

One issue with this is that the connection establishment is a complicated (and therefore slow process)

Other similar stuff

One more similar proprietary experimental thing

This also tries to improve on the triple way handshake of TCP and change the congestion control to better deal with fast lines.

How can I get list of values from dict?

You can use * operator to unpack dict_values:

>>> d = {1: "a", 2: "b"}
>>> [*d.values()]
['a', 'b']

or list object

>>> d = {1: "a", 2: "b"}
>>> list(d.values())
['a', 'b']

Get immediate first child element

Both these will give you the first child node:

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

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

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

Edit

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

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

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

java comparator, how to sort by integer?

Simply changing

public int compare(Dog d, Dog d1) {
  return d.age - d1.age;
}

to

public int compare(Dog d, Dog d1) {
  return d1.age - d.age;
}

should sort them in the reverse order of age if that is what you are looking for.

Update:

@Arian is right in his comments, one of the accepted ways of declaring a comparator for a dog would be where you declare it as a public static final field in the class itself.

class Dog implements Comparable<Dog> {
    private String name;
    private int age;

    public static final Comparator<Dog> DESCENDING_COMPARATOR = new Comparator<Dog>() {
        // Overriding the compare method to sort the age
        public int compare(Dog d, Dog d1) {
            return d.age - d1.age;
        }
    };

    Dog(String n, int a) {
        name = n;
        age = a;
    }

    public String getDogName() {
        return name;
    }

    public int getDogAge() {
        return age;
    }

    // Overriding the compareTo method
    public int compareTo(Dog d) {
        return (this.name).compareTo(d.name);
    }

}

You could then use it any where in your code where you would like to compare dogs as follows:

// Sorts the array list using comparator
Collections.sort(list, Dog.DESCENDING_COMPARATOR);

Another important thing to remember when implementing Comparable is that it is important that compareTo performs consistently with equals. Although it is not required, failing to do so could result in strange behaviour on some collections such as some implementations of Sets. See this post for more information on sound principles of implementing compareTo.

Update 2: Chris is right, this code is susceptible to overflows for large negative values of age. The correct way to implement this in Java 7 and up would be Integer.compare(d.age, d1.age) instead of d.age - d1.age.

Update 3: With Java 8, your Comparator could be written a lot more succinctly as:

public static final Comparator<Dog> DESCENDING_COMPARATOR = 
    Comparator.comparing(Dog::getDogAge).reversed();

The syntax for Collections.sort stays the same, but compare can be written as

public int compare(Dog d, Dog d1) {
    return DESCENDING_COMPARATOR.compare(d, d1);
}

How to get the current time in milliseconds in C Programming

quick answer

#include<stdio.h>   
#include<time.h>   

int main()   
{   
    clock_t t1, t2;  
    t1 = clock();   
    int i;
    for(i = 0; i < 1000000; i++)   
    {   
        int x = 90;  
    }   

    t2 = clock();   

    float diff = ((float)(t2 - t1) / 1000000.0F ) * 1000;   
    printf("%f",diff);   

    return 0;   
}

Using grep to search for a string that has a dot in it

grep uses regexes; . means "any character" in a regex. If you want a literal string, use grep -F, fgrep, or escape the . to \..

Don't forget to wrap your string in double quotes. Or else you should use \\.

So, your command would need to be:

grep -r "0\.49" *

or

grep -r 0\\.49 *

or

grep -Fr 0.49 *

Unable to login to SQL Server + SQL Server Authentication + Error: 18456

You need to enable SQL Server Authentication:

  1. In the Object Explorer, right click on the server and click on "Properties"

DBMS Properties dialog

  1. In the "Server Properties" window click on "Security" in the list of pages on the left. Under "Server Authentication" choose the "SQL Server and Windows Authentication mode" radio option.

SQL Server Authentication dialog

  1. Restart the SQLEXPRESS service.

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

You could use PHP's array_reduce as well,

$a = ['Name' => 'Last Name'];

function acc($acc,$k)use($a){ return $acc .= $k.":".$a[$k].",";}

$imploded = array_reduce(array_keys($a), "acc");

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

How do I download/extract font from chrome developers tools?

Open chrome

Right click => inspect => navigate to application tab

In Frames section, all the statically available assets(resources) such as css, JavaScript, fonts are listed.

How can I display a pdf document into a Webview?

You can use the Mozilla pdf.js project. Basically it will show you the PDF. Take a look at their example.

I only use it on the browser (desktop and mobile) and it's working fine.

Java SSL: how to disable hostname verification

In case you're using apache's http-client 4:

SSLConnectionSocketFactory sslConnectionSocketFactory = 
    new SSLConnectionSocketFactory(sslContext,
             new String[] { "TLSv1.2" }, null, new HostnameVerifier() {
                    public boolean verify(String arg0, SSLSession arg1) {
                            return true;
            }
      });

Getting all names in an enum as a String[]

You can put enum values to list of strings and convert to array:

    List<String> stateList = new ArrayList<>();

            for (State state: State.values()) {
                stateList.add(state.toString());
            }

    String[] stateArray = new String[stateList.size()];
    stateArray = stateList.toArray(stateArray);

Comparing two NumPy arrays for equality, element-wise

Usually two arrays will have some small numeric errors,

You can use numpy.allclose(A,B), instead of (A==B).all(). This returns a bool True/False

add/remove active class for ul list with jquery?

Try this,

 $('.nav-list li').click(function() {

    $('.nav-list li.active').removeClass('active');
    $(this).addClass('active');
});

In your context $(this) will points to the UL element not the Li. Hence you are not getting the expected results.

How to import a class from default package

Create a new package And then move the classes of default package in new package and use those classes

Process escape sequences in a string in Python

The correct thing to do is use the 'string-escape' code to decode the string.

>>> myString = "spam\\neggs"
>>> decoded_string = bytes(myString, "utf-8").decode("unicode_escape") # python3 
>>> decoded_string = myString.decode('string_escape') # python2
>>> print(decoded_string)
spam
eggs

Don't use the AST or eval. Using the string codecs is much safer.

jQuery DataTable overflow and text-wrapping issues

The following CSS declaration works for me:

.td-limit {
    max-width: 70px;
    text-overflow: ellipsis;
    white-space: nowrap;
    overflow: hidden;
}

Copy tables from one database to another in SQL Server

You may go with this way: ( a general example )

insert into QualityAssuranceDB.dbo.Customers (columnA, ColumnB)
Select columnA, columnB from DeveloperDB.dbo.Customers

Also if you need to generate the column names as well to put in insert clause, use:

    select (name + ',') as TableColumns from sys.columns 
where object_id = object_id('YourTableName')

Copy the result and paste into query window to represent your table column names and even this will exclude the identity column as well:

    select (name + ',') as TableColumns from sys.columns 
where object_id = object_id('YourTableName') and is_identity = 0

Remember the script to copy rows will work if the databases belongs to the same location.


You can Try This.

select * into <Destination_table> from <Servername>.<DatabaseName>.dbo.<sourceTable>

Server name is optional if both DB is in same server.

Indent starting from the second line of a paragraph with CSS

I needed to indent two rows to allow for a larger first word in a para. A cumbersome one-off solution is to place text in an SVG element and position this the same as an <img>. Using float and the SVG's height tag defines how many rows will be indented e.g.

<p style="color: blue; font-size: large; padding-top: 4px;">
<svg height="44" width="260" style="float:left;margin-top:-8px;"><text x="0" y="36" fill="blue" font-family="Verdana" font-size="36">Lorum Ipsum</text></svg> 
dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat.</p>
  • SVG's height and width determine area blocked out.
  • Y=36 is the depth to the SVG text baseline and same as font-size
  • margin-top's allow for best alignment of the SVG text and para text
  • Used first two words here to remind care needed for descenders

Yes it is cumbersome but it is also independent of the width of the containing div.

The above answer was to my own query to allow the first word(s) of a para to be larger and positioned over two rows. To simply indent the first two lines of a para you could replace all the SVG tags with the following single pixel img:

<img src="data:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==" style="float:left;width:260px;height:44px;" />

exceeds the list view threshold 5000 items in Sharepoint 2010

SharePoint lists V: Techniques for managing large lists :

Tutorial By Microsoft

Level: Advanced

Length: 40 - 50 minutes

When a SharePoint list gets large, you might see warnings such as, “This list exceeds the list view threshold,” or “Displaying the newest results below.” Find out why these warnings occur, and learn ways to configure your large list so that it still provides useful information.

After completing this course you will be able to:

  • Learn what the List View Threshold is, and understand its benefits.
  • Create an index so that you can see more information in a view.
  • Create folders to better organize your large list.
  • Use Datasheet view for fast filtering and sorting of a large list.
  • Learn what the Daily Time Window for Large Queries is.
  • Use Key Filters for fast filtering within Standard view.
  • Sync a large list to SharePoint Workspace.
  • Export a large list to Excel. Link a large list in Access.

Difference between "Complete binary tree", "strict binary tree","full binary Tree"?

Wikipedia yielded

A full binary tree (sometimes proper binary tree or 2-tree or strictly binary tree) is a tree in which every node other than the leaves has two children.

So you have no nodes with only 1 child. Appears to be the same as strict binary tree.

Here is an image of a full/strict binary tree, from google:

enter image description here

A complete binary tree is a binary tree in which every level, except possibly the last, is completely filled, and all nodes are as far left as possible.

It seems to mean a balanced tree.

Here is an image of a complete binary tree, from google, full tree part of image is bonus.

enter image description here

Android - Using Custom Font

Since I was not satisfied with all the presented solutions on SO, I've come up with mine. It's based on a little trick with tags (i.e. you can't use tags in your code), I put the font path there. So when defining views, you can do either this:

<TextView
        android:id="@+id/textViewHello1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World 1"
        android:tag="fonts/Oswald-Regular.ttf"/>

or this:

<TextView
        android:id="@+id/textViewHello2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World 2"
        style="@style/OswaldTextAppearance"/>

<style name="OswaldTextAppearance">
        <item name="android:tag">fonts/Oswald-Regular.ttf</item>
        <item name="android:textColor">#000000</item>
</style>

Now you can either explicitly access / setup the view as:

TextView textView = TextViewHelper.setupTextView(this, R.id.textViewHello1).setText("blah");

or just setup everything via:

TextViewHelper.setupTextViews(this, (ViewGroup) findViewById(R.id.parentLayout)); // parentLayout is the root view group (relative layout in my case)

And what is the magic class you ask? Mostly glued from another SO posts, with helper methods for both activity and fragments:

import android.app.Activity;
import android.content.Context;
import android.graphics.Typeface;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import java.util.HashMap;
import java.util.Map;

public class TextViewHelper {
    private static final Map<String, Typeface> mFontCache = new HashMap<>();

    private static Typeface getTypeface(Context context, String fontPath) {
        Typeface typeface;
        if (mFontCache.containsKey(fontPath)) {
            typeface = mFontCache.get(fontPath);
        } else {
            typeface = Typeface.createFromAsset(context.getAssets(), fontPath);
            mFontCache.put(fontPath, typeface);
        }
        return typeface;
    }

    public static void setupTextViews(Context context, ViewGroup parent) {
        for (int i = parent.getChildCount() - 1; i >= 0; i--) {
            final View child = parent.getChildAt(i);
            if (child instanceof ViewGroup) {
                setupTextViews(context, (ViewGroup) child);
            } else {
                if (child != null) {
                    TextViewHelper.setupTextView(context, child);
                }
            }
        }
    }

    public static void setupTextView(Context context, View view) {
        if (view instanceof TextView) {
            if (view.getTag() != null) // also inherited from TextView's style
            {
                TextView textView = (TextView) view;
                String fontPath = (String) textView.getTag();
                Typeface typeface = getTypeface(context, fontPath);
                if (typeface != null) {
                    textView.setTypeface(typeface);
                }
            }
        }
    }

    public static TextView setupTextView(View rootView, int id) {
        TextView textView = (TextView) rootView.findViewById(id);
        setupTextView(rootView.getContext().getApplicationContext(), textView);
        return textView;
    }

    public static TextView setupTextView(Activity activity, int id) {
        TextView textView = (TextView) activity.findViewById(id);
        setupTextView(activity.getApplicationContext(), textView);
        return textView;
    }
}

Recover SVN password from local cache

In ~/.subversion/auth/svn.simple/ you should find a file with a long hexadecimal name. The password is in there in plaintext.

If there is more than one file you'll need to find that one that references the server you need the password for.

How to run the Python program forever?

for OS's that support select:

import select

# your code

select.select([], [], [])

How do I determine whether an array contains a particular value in Java?

If you don't want it to be case sensitive

Arrays.stream(VALUES).anyMatch(s::equalsIgnoreCase);

Running multiple async tasks and waiting for them all to complete

You can use WhenAll which will return an awaitable Task or WaitAll which has no return type and will block further code execution simular to Thread.Sleep until all tasks are completed, canceled or faulted.

enter image description here

Example

var tasks = new Task[] {
    TaskOperationOne(),
    TaskOperationTwo()
};

Task.WaitAll(tasks);
// or
await Task.WhenAll(tasks);

If you want to run the tasks in a praticular order you can get inspiration form this anwser.

JavaScript or jQuery browser back button click detector

In my case I am using jQuery .load() to update DIVs in a SPA (single page [web] app) .

Being new to working with $(window).on('hashchange', ..) event listener , this one proved challenging and took a bit to hack on. Thanks to reading a lot of answers and trying different variations, finally figured out how to make it work in the following manner. Far as I can tell, it is looking stable so far.

In summary - there is the variable globalCurrentHash that should be set each time you load a view.

Then when $(window).on('hashchange', ..) event listener runs, it checks the following:

  • If location.hash has the same value, it means Going Forward
  • If location.hash has different value, it means Going Back

I realize using global vars isn't the most elegant solution, but doing things OO in JS seems tricky to me so far. Suggestions for improvement/refinement certainly appreciated


Set Up:

  1. Define a global var :
    var globalCurrentHash = null;
  1. When calling .load() to update the DIV, update the global var as well :

    function loadMenuSelection(hrefVal) {
      $('#layout_main').load(nextView);
      globalCurrentHash = hrefVal;
    }
    
  2. On page ready, set up the listener to check the global var to see if Back Button is being pressed:

    $(document).ready(function(){
      $(window).on('hashchange', function(){
          console.log( 'location.hash: ' + location.hash );
          console.log( 'globalCurrentHash: ' + globalCurrentHash );
    
          if (location.hash == globalCurrentHash) {
              console.log( 'Going fwd' );
          }
          else {
    
              console.log( 'Going Back' );
              loadMenuSelection(location.hash);
          }
        });
    
    });
    

Session TimeOut in web.xml

The docs says:

The session-timeout element defines the default session timeout interval for all sessions created in this web application. The specified timeout must be expressed in a whole number of minutes. If the timeout is 0 or less, the container ensures the default behaviour of sessions is never to time out. If this element is not specified, the container must set its default timeout period.

Design Android EditText to show error message as described by google

TextInputLayout til = (TextInputLayout)editText.getParent();
til.setErrorEnabled(true);
til.setError("some error..");

Convert Text to Uppercase while typing in Text box

Edit (for ASP.NET)

After you edited your question it's cler you're using ASP.NET. Things are pretty different there (because in that case a roundtrip to server is pretty discouraged). You can do same things with JavaScript (but to handle globalization with toUpperCase() may be a pain) or you can use CSS classes (relying on browsers implementation). Simply declare this CSS rule:

.upper-case
{
    text-transform: uppercase
}

And add upper-case class to your text-box:

<asp:TextBox ID="TextBox1" CssClass="upper-case" runat="server"/>

General (Old) Answer

but it capitalize characters after pressing Enter key.

It depends where you put that code. If you put it in, for example, TextChanged event it'll make upper case as you type.

You have a property that do exactly what you need: CharacterCasing:

TextBox1.CharacterCasing = CharacterCasing.Upper;

It works more or less but it doesn't handle locales very well. For example in German language ß is SS when converted in upper case (Institut für Deutsche Sprache) and this property doesn't handle that.

You may mimic CharacterCasing property adding this code in KeyPress event handler:

e.KeyChar = Char.ToUpper(e.KeyChar);

Unfortunately .NET framework doesn't handle this properly and upper case of sharp s character is returned unchanged. An upper case version of ß exists and it's ? and it may create some confusion, for example a word containing "ss" and another word containing "ß" can't be distinguished if you convert in upper case using "SS"). Don't forget that:

However, in 2010 the use of the capital sharp s became mandatory in official documentation when writing geographical names in all-caps.

There isn't much you can do unless you add proper code for support this (and others) subtle bugs in .NET localization. Best advice I can give you is to use a custom dictionary per each culture you need to support.

Finally don't forget that this transformation may be confusing for your users: in Turkey, for example, there are two different versions of i upper case letter.

If text processing is important in your application you can solve many issues using specialized DLLs for each locale you support like Word Processors do.

What I usually do is to do not use standard .NET functions for strings when I have to deal with culture specific issues (I keep them only for text in invariant culture). I create a Unicode class with static methods for everything I need (character counting, conversions, comparison) and many specialized derived classes for each supported language. At run-time that static methods will user current thread culture name to pick proper implementation from a dictionary and to delegate work to that. A skeleton may be something like this:

abstract class Unicode
{
    public static string ToUpper(string text)
    {
        return GetConcreteClass().ToUpperCore(text);
    }

    protected virtual string ToUpperCore(string text)
    {
        // Default implementation, overridden in derived classes if needed
        return text.ToUpper();
    }

    private Dictionary<string, Unicode> _implementations;

    private Unicode GetConcreteClass()
    {
        string cultureName = Thread.Current.CurrentCulture.Name;

        // Check if concrete class has been loaded and put in dictionary
        ...

        return _implementations[cultureName];
    }
}

I'll then have an implementation specific for German language:

sealed class German : Unicode
{
    protected override string ToUpperCore(string text)
    {
        // Very naive implementation, just to provide an example
        return text.ToUpper().Replace("ß", "?");
    }
}

True implementation may be pretty more complicate (not all OSes supports upper case ?) but take as a proof of concept. See also this post for other details about Unicode issues on .NET.

REST URI convention - Singular or plural name of resource while creating it

My two cents: methods who spend their time changing from plural to singular or viceversa are a waste of CPU cycles. I may be old-school, but in my time like things were called the same. How do I look up methods concerning people? No regular expresion will cover both person and people without undesirable side effects.

English plurals can be very arbitrary and they encumber the code needlessly. Stick to one naming convention. Computer languages were supposed to be about mathematical clarity, not about mimicking natural language.

How to show imageView full screen on imageView click?

Actually there are three ways to enable full screnn, visit : https://developer.android.com/training/system-ui/immersive

but if you wanna get full screen when the activity is opened, just put this code in your_activity.java

@Override
public void onWindowFocusChanged(boolean hasFocus) {
    super.onWindowFocusChanged(hasFocus);
    if (hasFocus) {
        hideSystemUI();
    }
}

private void hideSystemUI() {
    // Enables regular immersive mode.
    // For "lean back" mode, remove SYSTEM_UI_FLAG_IMMERSIVE.
    // Or for "sticky immersive," replace it with SYSTEM_UI_FLAG_IMMERSIVE_STICKY
    View decorView = getWindow().getDecorView();
    decorView.setSystemUiVisibility(
            View.SYSTEM_UI_FLAG_IMMERSIVE
            // Set the content to appear under the system bars so that the
            // content doesn't resize when the system bars hide and show.
            | View.SYSTEM_UI_FLAG_LAYOUT_STABLE
            | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
            | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
            // Hide the nav bar and status bar
            | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
            | View.SYSTEM_UI_FLAG_FULLSCREEN);
}

// Shows the system bars by removing all the flags
// except for the ones that make the content appear under the system bars.
private void showSystemUI() {
    View decorView = getWindow().getDecorView();
    decorView.setSystemUiVisibility(
            View.SYSTEM_UI_FLAG_LAYOUT_STABLE
            | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
            | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
}

Logcat not displaying my log calls

None of the other answers worked for me, but this did:

I removed my project from my workspace, then deleted anything that started with a dot (.settings, .project, etc.) from the project folder. Then I re-imported the projected. I'm missing some settings and breakpoints but at least it works.

how to use concatenate a fixed string and a variable in Python

variable=" Hello..."  
print (variable)  
print("This is the Test File "+variable)  

for integer type ...

variable="  10"  
print (variable)  
print("This is the Test File "+str(variable))  

Java command not found on Linux

You can add one of the Java path to PATH variable using the following command.

export PATH=$PATH:/usr/java/jre1.6.0_24/bin/

You can add this line to .bashrc file in your home directory. Adding this to .bashrc will ensure everytime you open bash it will be PATH variable is updated.

while-else-loop

boolean entered = false, last;
while (( entered |= last = ( condition ) )) {
        // Do while
} if ( !entered ) {
        // Else
}

You'r welcome.

ldap_bind: Invalid Credentials (49)

I don't see an obvious problem with the above.

It's possible your ldap.conf is being overridden, but the command-line options will take precedence, ldapsearch will ignore BINDDN in the main ldap.conf, so the only parameter that could be wrong is the URI. (The order is ETCDIR/ldap.conf then ~/ldaprc or ~/.ldaprc and then ldaprc in the current directory, though there environment variables which can influence this too, see man ldapconf.)

Try an explicit URI:

ldapsearch -x -W -D 'cn=Manager,dc=example,dc=com' -b "" -s base -H ldap://localhost

or prevent defaults with:

LDAPNOINIT=1 ldapsearch -x -W -D 'cn=Manager,dc=example,dc=com' -b "" -s base

If that doesn't work, then some troubleshooting (you'll probably need the full path to the slapd binary for these):

  • make sure your slapd.conf is being used and is correct (as root)

    slapd -T test -f slapd.conf -d 65535

    You may have a left-over or default slapd.d configuration directory which takes preference over your slapd.conf (unless you specify your config explicitly with -f, slapd.conf is officially deprecated in OpenLDAP-2.4). If you don't get several pages of output then your binaries were built without debug support.

  • stop OpenLDAP, then manually start slapd in a separate terminal/console with debug enabled (as root, ^C to quit)

    slapd -h ldap://localhost -d 481

    then retry the search and see if you can spot the problem (there will be a lot of schema noise in the start of the output unfortunately). (Note: running slapd without the -u/-g options can change file ownerships which can cause problems, you should usually use those options, probably -u ldap -g ldap )

  • if debug is enabled, then try also

    ldapsearch -v -d 63 -W -D 'cn=Manager,dc=example,dc=com' -b "" -s base

SQL how to check that two tables has exactly the same data?

To compare T1(PK, A, B) and T2(PK, A, B).

First compare primary key sets to look for missing key values on either side:

SELECT T1.*, T2.* FROM T1 FULL OUTER JOIN T2 ON T1.PK=T2.PK WHERE T1.PK IS NULL OR T2.PK IS NULL;

Then list all value mismatch:

SELECT T1.PK, 'A' AS columnName, T1.A AS leftValue, T2.A AS rightValue FROM T1 JOIN T2 ON T1.PK=T2.PK WHERE COALESCE(T1.A,0) != COALESCE(T2.A,0)
UNION ALL
SELECT T1.PK, 'B' AS columnName, T1.B AS leftValue, T2.B AS rightValue FROM T1 JOIN T2 ON T1.PK=T2.PK WHERE COALESCE(T1.B,0) != COALESCE(T2.B,0)

A and B must be of same type. You can use INFORMATION SCHEMA to generate the SELECT. Don't forget the COALESCE to also include IS NULL results. You could also use FULL OUTER JOIN and COALESCE(T1.PK,0)=COALESCE(T2.PK,0).

For example for columns of type varchar:

SELECT concat('SELECT T1.PK, ''', COLUMN_NAME, ''' AS columnName, T1.', COLUMN_NAME, ' AS leftValue, T2.', COLUMN_NAME, ' AS rightValue FROM T1 JOIN T2 ON T1.PK=T2.PK WHERE COALESCE(T1.',COLUMN_NAME, ',0)!=COALESCE(T2.', COLUMN_NAME, ',0)')
FROM INFORMATION_SCHEMA.COLUMNS 
WHERE TABLE_NAME='T1' AND DATA_TYPE IN ('nvarchar','varchar');

Best way to update data with a RecyclerView adapter

Found following solution working for my similar problem:

private ExtendedHashMap mData = new ExtendedHashMap();
private  String[] mKeys;

public void setNewData(ExtendedHashMap data) {
    mData.putAll(data);
    mKeys = data.keySet().toArray(new String[data.size()]);
    notifyDataSetChanged();
}

Using the clear-command

mData.clear()

is not nessescary

How to count the number of set bits in a 32-bit integer?

If you happen to be using Java, the built-in method Integer.bitCount will do that.

Convert String with Dot or Comma as decimal separator to number in JavaScript

Do a replace first:

parseFloat(str.replace(',','.').replace(' ',''))

HTML Agility pack - parsing tables

Line from above answer:

HtmlDocument doc = new HtmlDocument();

This doesn't work in VS 2015 C#. You cannot construct an HtmlDocument any more.

Another MS "feature" that makes things more difficult to use. Try HtmlAgilityPack.HtmlWeb and check out this link for some sample code.

System.Collections.Generic.List does not contain a definition for 'Select'

This question's bit old, but, there's a tricky scenario which also leads to this error:

In controller:

ViewBag.id = //id from querystring
List<string> = GrabDataFromDBByID(ViewBag.id).Select(a=>a.ToString());

The above code will lead to an error in this part: .Select(a=>a.ToString()) because of the below reason: You're passing a ViewBag.id to a method which in compiler, it doesn't know the type, so there might be several methods with the same name and different parameters let's say:

GrabDataFromDBByID(string)
GrabDataFromDBByID(int)
GrabDataFromDBByID(whateverType)

So to prevent this case, either explicitly cast the ViewBag or create another variable storing it.

Array Length in Java

To find length of an array A you should use the length property. It is as A.length, do not use A.length() its mainly used for size of string related objects.

enter image description here

The length property will always show the total allocated space to the array during initialization.

If you ever have any of these kind of problems the simple way is to run it. Happy Programming!

How to check whether Kafka Server is running?

The good option is to use AdminClient as below before starting to produce or consume the messages

private static final int ADMIN_CLIENT_TIMEOUT_MS = 5000;           
 try (AdminClient client = AdminClient.create(properties)) {
            client.listTopics(new ListTopicsOptions().timeoutMs(ADMIN_CLIENT_TIMEOUT_MS)).listings().get();
        } catch (ExecutionException ex) {
            LOG.error("Kafka is not available, timed out after {} ms", ADMIN_CLIENT_TIMEOUT_MS);
            return;
        }

Fatal error: Call to undefined function mysql_connect()

My solution is here (I needed just to remove the last slash (NB: backward slashes) from PHPIniDir 'c:\PHP\'): Fatal error: Call to undefined function mysql_connect() cannot solve

Is there a Mutex in Java?

Any object in Java can be used as a lock using a synchronized block. This will also automatically take care of releasing the lock when an exception occurs.

Object someObject = ...;

synchronized (someObject) {
  ...
}

You can read more about this here: Intrinsic Locks and Synchronization

Should I make HTML Anchors with 'name' or 'id'?

The whole "named anchor" concept uses the name attribute, by definition. You should just stick to using the name, but the ID attribute might be handy for some javascript situations.

As in the comments, you could always use both to hedge your bets.

How add unique key to existing table (with non uniques rows)

The proper syntax would be - ALTER TABLE Table_Name ADD UNIQUE (column_name)

Example

ALTER TABLE  0_value_addition_setup ADD UNIQUE (`value_code`)

Nginx location "not equal to" regex

According to nginx documentation

there is no syntax for NOT matching a regular expression. Instead, match the target regular expression and assign an empty block, then use location / to match anything else

So you could define something like

location ~ (dir1|file2\.php) { 
    # empty
}

location / {
    rewrite ^/(.*) http://example.com/$1 permanent; 
}

DIV height set as percentage of screen?

Try using Viewport Height

div {
    height:100vh; 
}

It is already discussed here in detail

Starting the week on Monday with isoWeekday()

thought I would add this for any future peeps. It will always make sure that its monday if needed, can also be used to always ensure sunday. For me I always need monday, but local is dependant on the machine being used, and this is an easy fix:

var begin = moment().isoWeekday(1).startOf('week');
var begin2 = moment().startOf('week');
// could check to see if day 1 = Sunday  then add 1 day
// my mac on bst still treats day 1 as sunday    

var firstDay = moment().startOf('week').format('dddd') === 'Sunday' ?     
moment().startOf('week').add('d',1).format('dddd DD-MM-YYYY') : 
moment().startOf('week').format('dddd DD-MM-YYYY');

document.body.innerHTML = '<b>could be monday or sunday depending on client: </b><br />' + 
begin.format('dddd DD-MM-YYYY') + 
'<br /><br /> <b>should be monday:</b> <br>' + firstDay + 
'<br><br> <b>could also be sunday or monday </b><br> ' + 
begin2.format('dddd DD-MM-YYYY');

Create empty file using python

There is no way to create a file without opening it There is os.mknod("newfile.txt") (but it requires root privileges on OSX). The system call to create a file is actually open() with the O_CREAT flag. So no matter how, you'll always open the file.

So the easiest way to simply create a file without truncating it in case it exists is this:

open(x, 'a').close()

Actually you could omit the .close() since the refcounting GC of CPython will close it immediately after the open() statement finished - but it's cleaner to do it explicitely and relying on CPython-specific behaviour is not good either.

In case you want touch's behaviour (i.e. update the mtime in case the file exists):

import os
def touch(path):
    with open(path, 'a'):
        os.utime(path, None)

You could extend this to also create any directories in the path that do not exist:

basedir = os.path.dirname(path)
if not os.path.exists(basedir):
    os.makedirs(basedir)

How to directly initialize a HashMap (in a literal way)?

If you allow 3rd party libs, you can use Guava's ImmutableMap to achieve literal-like brevity:

Map<String, String> test = ImmutableMap.of("k1", "v1", "k2", "v2");

This works for up to 5 key/value pairs, otherwise you can use its builder:

Map<String, String> test = ImmutableMap.<String, String>builder()
    .put("k1", "v1")
    .put("k2", "v2")
    ...
    .build();


  • note that Guava's ImmutableMap implementation differs from Java's HashMap implementation (most notably it is immutable and does not permit null keys/values)
  • for more info, see Guava's user guide article on its immutable collection types

Response Content type as CSV

Try one of these other mime-types (from here: http://filext.com/file-extension/CSV )

  • text/comma-separated-values
  • text/csv
  • application/csv
  • application/excel
  • application/vnd.ms-excel
  • application/vnd.msexcel

Also, the mime-type might be case sensitive...

How to do multiple conditions for single If statement

Use the 'And' keyword for a logical and. Like this:

If Not ((filename = testFileName) And (fileName <> "")) Then

How to give credentials in a batch script that copies files to a network location?

Try using the net use command in your script to map the share first, because you can provide it credentials. Then, your copy command should use those credentials.

net use \\<network-location>\<some-share> password /USER:username

Don't leave a trailing \ at the end of the

How to build minified and uncompressed bundle with webpack?

You can run webpack twice with different arguments:

$ webpack --minimize

then check command line arguments in webpack.config.js:

var path = require('path'),
  webpack = require('webpack'),
  minimize = process.argv.indexOf('--minimize') !== -1,
  plugins = [];

if (minimize) {
  plugins.push(new webpack.optimize.UglifyJsPlugin());
}

...

example webpack.config.js

Passing arrays as url parameter

please escape your variables when outputting (urlencode).

and you can’t just print an array, you have to build your url using a loop in some way

$url = 'http://example.com/index.php?'
$first = true;
foreach($aValues as $key => $value) {
  if(!$first) $url .= '&amp';
  else $first = false;
  $url .= 'aValues['.urlencode($key).']='.urlencode($value);
}

Install NuGet via PowerShell script

None of the above solutions worked for me, I found an article that explained the issue. The security protocols on the system were deprecated and therefore displayed an error message that no match was found for the ProviderPackage.

Here is a the basic steps for upgrading your security protocols:

Run both cmdlets to set .NET Framework strong cryptography registry keys. After that, restart PowerShell and check if the security protocol TLS 1.2 is added. As of last, install the PowerShellGet module.

The first cmdlet is to set strong cryptography on 64 bit .Net Framework (version 4 and above).

[PS] C:\>Set-ItemProperty -Path 'HKLM:\SOFTWARE\Wow6432Node\Microsoft\.NetFramework\v4.0.30319' -Name 'SchUseStrongCrypto' -Value '1' -Type DWord
1
[PS] C:\>Set-ItemProperty -Path 'HKLM:\SOFTWARE\Wow6432Node\Microsoft\.NetFramework\v4.0.30319' -Name 'SchUseStrongCrypto' -Value '1' -Type DWord
The second cmdlet is to set strong cryptography on 32 bit .Net Framework (version 4 and above).

[PS] C:\>Set-ItemProperty -Path 'HKLM:\SOFTWARE\Microsoft\.NetFramework\v4.0.30319' -Name 'SchUseStrongCrypto' -Value '1' -Type DWord
1
[PS] C:\>Set-ItemProperty -Path 'HKLM:\SOFTWARE\Microsoft\.NetFramework\v4.0.30319' -Name 'SchUseStrongCrypto' -Value '1' -Type DWord
Restart Powershell and check for supported security protocols.

[PS] C:\>[Net.ServicePointManager]::SecurityProtocol
Tls, Tls11, Tls12
1
2
[PS] C:\>[Net.ServicePointManager]::SecurityProtocol
Tls, Tls11, Tls12
Run the command Install-Module PowershellGet -Force and press Y to install NuGet provider, follow with Enter.

[PS] C:\>Install-Module PowershellGet -Force
 
NuGet provider is required to continue
PowerShellGet requires NuGet provider version '2.8.5.201' or newer to interact with NuGet-based repositories. The NuGet provider must be available in 'C:\Program Files\PackageManagement\ProviderAssemblies' or
'C:\Users\administrator.EXOIP\AppData\Local\PackageManagement\ProviderAssemblies'. You can also install the NuGet provider by running 'Install-PackageProvider -Name NuGet -MinimumVersion 2.8.5.201 -Force'. Do you want PowerShellGet to install
and import the NuGet provider now?
[Y] Yes  [N] No  [S] Suspend  [?] Help (default is "Y"): Y

[PS] C:\>Install-Module PowershellGet -Force
 
NuGet provider is required to continue
PowerShellGet requires NuGet provider version '2.8.5.201' or newer to interact with NuGet-based repositories. The NuGet provider must be available in 'C:\Program Files\PackageManagement\ProviderAssemblies' or
'C:\Users\administrator.EXOIP\AppData\Local\PackageManagement\ProviderAssemblies'. You can also install the NuGet provider by running 'Install-PackageProvider -Name NuGet -MinimumVersion 2.8.5.201 -Force'. Do you want PowerShellGet to install
and import the NuGet provider now?
[Y] Yes  [N] No  [S] Suspend  [?] Help (default is "Y"): Y

Disallow Twitter Bootstrap modal window from closing

Well, this is another solution that some of you guys might be looking for (as I was..)

My problem was similar, the modal box was closing while the iframe I had inside was loading, so I had to disable the modal dismiss until the Iframe finishes loading, then re-enable.

The solutions presented here were not working 100%.

My solution was this:

showLocationModal = function(loc){

    var is_loading = true;

    if(is_loading === true) {

        is_loading  = false;
        var $modal   = $('#locationModal');

        $modal.modal({show:true});

        // prevent Modal to close before the iframe is loaded
        $modal.on("hide", function (e) {
            if(is_loading !== true) {
                e.preventDefault();
                return false
            }
        });

        // populate Modal
        $modal.find('.modal-body iframe').hide().attr('src', location.link).load(function(){

            is_loading = true;
     });
}};

So I temporarily prevent the Modal from closing with:

$modal.on("hide", function (e) {
    if(is_loading !== true) {
        e.preventDefault();
        return false
    }
});

But ith the var is_loading that will re enable closing after the Iframe has loaded.

Apache is downloading php files instead of displaying them

This might be happening due to the missing modules required for your php. Assuming you have php7 installed, search available php7 modules using

sudo apt-cache search php7-*

Above command will list all available PHP7 modules for installation. You can begin installation of modules like,

sudo apt-get install libapache2-mod-php7.0 php7.0-mysql php7.0-curl php7.0-json

Capturing console output from a .NET application (C#)

Use ProcessInfo.RedirectStandardOutput to redirect the output when creating your console process.

Then you can use Process.StandardOutput to read the program output.

The second link has a sample code how to do it.

Can we pass parameters to a view in SQL?

I have an idea that I haven't tried yet. You can do:

CREATE VIEW updated_customers AS
SELECT * FROM customer as aa
LEFT JOIN customer_rec as bb
ON aa.id = bb.customer_id
WHERE aa.updated_at between (SELECT start_date FROM config WHERE active = 1) 
and (SELECT end_date FROM config WHERE active = 1)

Your parameters will be saved and changed in the Config table.

Get value (String) of ArrayList<ArrayList<String>>(); in Java

A cleaner way of iterating the lists is:

// initialise the collection
collection = new ArrayList<ArrayList<String>>();
// iterate
for (ArrayList<String> innerList : collection) {
    for (String string : innerList) {
        // do stuff with string
    }
}

How to efficiently build a tree from a flat structure?

one elegant way to do this is to represent items in the list as string holding a dot separated list of parents, and finally a value:

server.port=90
server.hostname=localhost
client.serverport=90
client.database.port=1234
client.database.host=localhost

When assembling a tree, you would end up with something like:

server:
  port: 90
  hostname: localhost
client:
  serverport=1234
  database:
    port: 1234
    host: localhost

I have a configuration library that implements this override configuration (tree) from command line arguments (list). The algorithm to add a single item to the list to a tree is here.

Difference between break and continue statement

A break statement results in the termination of the statement to which it applies (switch, for, do, or while).

A continue statement is used to end the current loop iteration and return control to the loop statement.

Sorting arraylist in alphabetical order (case insensitive)

Based on the above mentioned answers, I managed to compare my custom Class Objects like this:

ArrayList<Item> itemList = new ArrayList<>();
...
Collections.sort(itemList, new Comparator<Item>() {
            @Override
            public int compare(Item item, Item t1) {
                String s1 = item.getTitle();
                String s2 = t1.getTitle();
                return s1.compareToIgnoreCase(s2);
            }

        });

How to set the image from drawable dynamically in android?

See below code this is working for me

iv.setImageResource(getResources().getIdentifier(
                "imagename", "drawable", "com.package.application"));

How to Get a Sublist in C#

With LINQ:

List<string> l = new List<string> { "1", "2", "3" ,"4","5"};
List<string> l2 = l.Skip(1).Take(2).ToList();

If you need foreach, then no need for ToList:

foreach (string s in l.Skip(1).Take(2)){}

Advantage of LINQ is that if you want to just skip some leading element,you can :

List<string> l2 = l.Skip(1).ToList();
foreach (string s in l.Skip(1)){}

i.e. no need to take care of count/length, etc.

MySQL export into outfile : CSV escaping chars

I think your statement should look like:

SELECT id, 
   client,
   project,
   task,
   description, 
   time,
   date  
  INTO OUTFILE '/path/to/file.csv'
  FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"'
  LINES TERMINATED BY '\n'
  FROM ts

Mainly without the FIELDS ESCAPED BY '""' option, OPTIONALLY ENCLOSED BY '"' will do the trick for description fields etc and your numbers will be treated as numbers in Excel (not strings comprising of numerics)

Also try calling:

SET NAMES utf8;

before your outfile select, that might help getting the character encodings inline (all UTF8)

Let us know how you get on.

Check whether specific radio button is checked

$("input[@name='<%=test2.ClientID%>']:checked");

use this and here ClientID fetch random id created by .net.

Subtracting Dates in Oracle - Number or Interval Datatype?

Ok, I don't normally answer my own questions but after a bit of tinkering, I have figured out definitively how Oracle stores the result of a DATE subtraction.

When you subtract 2 dates, the value is not a NUMBER datatype (as the Oracle 11.2 SQL Reference manual would have you believe). The internal datatype number of a DATE subtraction is 14, which is a non-documented internal datatype (NUMBER is internal datatype number 2). However, it is actually stored as 2 separate two's complement signed numbers, with the first 4 bytes used to represent the number of days and the last 4 bytes used to represent the number of seconds.

An example of a DATE subtraction resulting in a positive integer difference:

select date '2009-08-07' - date '2008-08-08' from dual;

Results in:

DATE'2009-08-07'-DATE'2008-08-08'
---------------------------------
                              364

select dump(date '2009-08-07' - date '2008-08-08') from dual;

DUMP(DATE'2009-08-07'-DATE'2008
-------------------------------
Typ=14 Len=8: 108,1,0,0,0,0,0,0

Recall that the result is represented as a 2 seperate two's complement signed 4 byte numbers. Since there are no decimals in this case (364 days and 0 hours exactly), the last 4 bytes are all 0s and can be ignored. For the first 4 bytes, because my CPU has a little-endian architecture, the bytes are reversed and should be read as 1,108 or 0x16c, which is decimal 364.

An example of a DATE subtraction resulting in a negative integer difference:

select date '1000-08-07' - date '2008-08-08' from dual;

Results in:

DATE'1000-08-07'-DATE'2008-08-08'
---------------------------------
                          -368160

select dump(date '1000-08-07' - date '2008-08-08') from dual;

DUMP(DATE'1000-08-07'-DATE'2008-08-0
------------------------------------
Typ=14 Len=8: 224,97,250,255,0,0,0,0

Again, since I am using a little-endian machine, the bytes are reversed and should be read as 255,250,97,224 which corresponds to 11111111 11111010 01100001 11011111. Now since this is in two's complement signed binary numeral encoding, we know that the number is negative because the leftmost binary digit is a 1. To convert this into a decimal number we would have to reverse the 2's complement (subtract 1 then do the one's complement) resulting in: 00000000 00000101 10011110 00100000 which equals -368160 as suspected.

An example of a DATE subtraction resulting in a decimal difference:

select to_date('08/AUG/2004 14:00:00', 'DD/MON/YYYY HH24:MI:SS'
 - to_date('08/AUG/2004 8:00:00', 'DD/MON/YYYY HH24:MI:SS') from dual;

TO_DATE('08/AUG/200414:00:00','DD/MON/YYYYHH24:MI:SS')-TO_DATE('08/AUG/20048:00:
--------------------------------------------------------------------------------
                                                                             .25

The difference between those 2 dates is 0.25 days or 6 hours.

select dump(to_date('08/AUG/2004 14:00:00', 'DD/MON/YYYY HH24:MI:SS')
 - to_date('08/AUG/2004 8:00:00', 'DD/MON/YYYY HH24:MI:SS')) from dual;

DUMP(TO_DATE('08/AUG/200414:00:
-------------------------------
Typ=14 Len=8: 0,0,0,0,96,84,0,0

Now this time, since the difference is 0 days and 6 hours, it is expected that the first 4 bytes are 0. For the last 4 bytes, we can reverse them (because CPU is little-endian) and get 84,96 = 01010100 01100000 base 2 = 21600 in decimal. Converting 21600 seconds to hours gives you 6 hours which is the difference which we expected.

Hope this helps anyone who was wondering how a DATE subtraction is actually stored.


You get the syntax error because the date math does not return a NUMBER, but it returns an INTERVAL:

SQL> SELECT DUMP(SYSDATE - start_date) from test;

DUMP(SYSDATE-START_DATE)
-------------------------------------- 
Typ=14 Len=8: 188,10,0,0,223,65,1,0

You need to convert the number in your example into an INTERVAL first using the NUMTODSINTERVAL Function

For example:

SQL> SELECT (SYSDATE - start_date) DAY(5) TO SECOND from test;

(SYSDATE-START_DATE)DAY(5)TOSECOND
----------------------------------
+02748 22:50:04.000000

SQL> SELECT (SYSDATE - start_date) from test;

(SYSDATE-START_DATE)
--------------------
           2748.9515

SQL> select NUMTODSINTERVAL(2748.9515, 'day') from dual;

NUMTODSINTERVAL(2748.9515,'DAY')
--------------------------------
+000002748 22:50:09.600000000

SQL>

Based on the reverse cast with the NUMTODSINTERVAL() function, it appears some rounding is lost in translation.

Error:could not create the Java Virtual Machine Error:A fatal exception has occured.Program will exit

--version is a valid option from JDK 9 and it is not a valid option until JDK 8 hence you get the below:

Unrecognized option: --version
Error: Could not create the Java Virtual Machine.
Error: A fatal exception has occurred. Program will exit.

You can try installing JDK 9 or any version later and check for java --version it will work.

Alternately, from the installed JDK 9 or later versions you can see from java -help the below two options will be available:

    -version      print product version to the error stream and exit
    --version     print product version to the output stream and exit

where as in JDK 8 you will only have below when you execute java -help

    -version      print product version and exit

I hope it answers your question.

Get Locale Short Date Format using javascript

Short date patterns:

const shortDatePatterns = {
'aa-DJ': "dd/MM/yyyy",
'aa-ER': "dd/MM/yyyy",
'aa-ET': "dd/MM/yyyy",
'af': "yyyy-MM-dd",
'af-NA': "yyyy-MM-dd",
'af-ZA': "yyyy-MM-dd",
'agq-CM': "d/M/yyyy",
'ak-GH': "yyyy/MM/dd",
'am': "dd/MM/yyyy",
'am-ET': "dd/MM/yyyy",
'ar': "dd/MM/yy",
'ar-001': "d/M/yyyy",
'ar-AE': "dd/MM/yyyy",
'ar-BH': "dd/MM/yyyy",
'ar-DJ': "d/M/yyyy",
'ar-DZ': "dd-MM-yyyy",
'ar-EG': "dd/MM/yyyy",
'ar-ER': "d/M/yyyy",
'ar-IL': "d/M/yyyy",
'ar-IQ': "dd/MM/yyyy",
'ar-JO': "dd/MM/yyyy",
'ar-KM': "d/M/yyyy",
'ar-KW': "dd/MM/yyyy",
'ar-LB': "dd/MM/yyyy",
'ar-LY': "dd/MM/yyyy",
'ar-MA': "dd-MM-yyyy",
'ar-MR': "d/M/yyyy",
'ar-OM': "dd/MM/yyyy",
'ar-PS': "d/M/yyyy",
'ar-QA': "dd/MM/yyyy",
'ar-SA': "dd/MM/yy",
'ar-SD': "d/M/yyyy",
'ar-SO': "d/M/yyyy",
'ar-SS': "d/M/yyyy",
'ar-SY': "dd/MM/yyyy",
'ar-TD': "d/M/yyyy",
'ar-TN': "dd-MM-yyyy",
'ar-YE': "dd/MM/yyyy",
'arn-CL': "dd-MM-yyyy",
'as': "dd-MM-yyyy",
'as-IN': "dd-MM-yyyy",
'asa-TZ': "dd/MM/yyyy",
'ast-ES': "d/M/yyyy",
'az': "dd.MM.yyyy",
'az-Cyrl-AZ': "dd.MM.yyyy",
'az-Latn-AZ': "dd.MM.yyyy",
'ba': "dd.MM.yy",
'ba-RU': "dd.MM.yy",
'bas-CM': "d/M/yyyy",
'be': "dd.MM.yy",
'be-BY': "dd.MM.yy",
'bem-ZM': "dd/MM/yyyy",
'bez-TZ': "dd/MM/yyyy",
'bg': "d.M.yyyy '?.'",
'bg-BG': "d.M.yyyy '?.'",
'bin-NG': "d/M/yyyy",
'bm': "d/M/yyyy",
'bm-Latn-ML': "d/M/yyyy",
'bn': "d/M/yyyy",
'bn-BD': "d/M/yyyy",
'bn-IN': "dd-MM-yy",
'bo': "yyyy/M/d",
'bo-CN': "yyyy/M/d",
'bo-IN': "yyyy-MM-dd",
'br': "dd/MM/yyyy",
'br-FR': "dd/MM/yyyy",
'brx-IN': "M/d/yyyy",
'bs': "d.M.yyyy.",
'bs-Cyrl-BA': "d.M.yyyy",
'bs-Latn-BA': "d.M.yyyy.",
'byn-ER': "dd/MM/yyyy",
'ca': "d/M/yyyy",
'ca-AD': "d/M/yyyy",
'ca-ES': "d/M/yyyy",
'ca-ES-valencia': "d/M/yyyy",
'ca-FR': "d/M/yyyy",
'ca-IT': "d/M/yyyy",
'ce-RU': "yyyy-MM-dd",
'cgg-UG': "dd/MM/yyyy",
'chr-Cher-US': "M/d/yyyy",
'co': "dd/MM/yyyy",
'co-FR': "dd/MM/yyyy",
'cs-CZ': "dd.MM.yyyy",
'cu': "yyyy.MM.dd",
'cu-RU': "yyyy.MM.dd",
'cy': "dd/MM/yyyy",
'cy-GB': "dd/MM/yyyy",
'da-DK': "dd-MM-yyyy",
'da-GL': "dd/MM/yyyy",
'dav-KE': "dd/MM/yyyy",
'de': "dd.MM.yyyy",
'de-AT': "dd.MM.yyyy",
'de-BE': "dd.MM.yyyy",
'de-CH': "dd.MM.yyyy",
'de-DE': "dd.MM.yyyy",
'de-IT': "dd.MM.yyyy",
'de-LI': "dd.MM.yyyy",
'de-LU': "dd.MM.yyyy",
'dje-NE': "d/M/yyyy",
'dsb-DE': "d. M. yyyy",
'dua-CM': "d/M/yyyy",
'dv-MV': "dd/MM/yy",
'dyo-SN': "d/M/yyyy",
'dz': "yyyy-MM-dd",
'dz-BT': "yyyy-MM-dd",
'ebu-KE': "dd/MM/yyyy",
'ee': "M/d/yyyy",
'ee-GH': "M/d/yyyy",
'ee-TG': "M/d/yyyy",
'el-CY': "d/M/yyyy",
'el-GR': "d/M/yyyy",
'en-001': "dd/MM/yyyy",
'en-029': "dd/MM/yyyy",
'en-150': "dd/MM/yyyy",
'en-AG': "dd/MM/yyyy",
'en-AI': "dd/MM/yyyy",
'en-AS': "M/d/yyyy",
'en-AT': "dd/MM/yyyy",
'en-AU': "d/MM/yyyy",
'en-BB': "dd/MM/yyyy",
'en-BE': "dd/MM/yyyy",
'en-BI': "M/d/yyyy",
'en-BM': "dd/MM/yyyy",
'en-BS': "dd/MM/yyyy",
'en-BW': "dd/MM/yyyy",
'en-BZ': "dd/MM/yyyy",
'en-CA': "yyyy-MM-dd",
'en-CC': "dd/MM/yyyy",
'en-CH': "dd/MM/yyyy",
'en-CK': "dd/MM/yyyy",
'en-CM': "dd/MM/yyyy",
'en-CX': "dd/MM/yyyy",
'en-CY': "dd/MM/yyyy",
'en-DE': "dd/MM/yyyy",
'en-DK': "dd/MM/yyyy",
'en-DM': "dd/MM/yyyy",
'en-ER': "dd/MM/yyyy",
'en-FI': "dd/MM/yyyy",
'en-FJ': "dd/MM/yyyy",
'en-FK': "dd/MM/yyyy",
'en-FM': "dd/MM/yyyy",
'en-GB': "dd/MM/yyyy",
'en-GD': "dd/MM/yyyy",
'en-GG': "dd/MM/yyyy",
'en-GH': "dd/MM/yyyy",
'en-GI': "dd/MM/yyyy",
'en-GM': "dd/MM/yyyy",
'en-GU': "M/d/yyyy",
'en-GY': "dd/MM/yyyy",
'en-HK': "d/M/yyyy",
'en-ID': "dd/MM/yyyy",
'en-IE': "dd/MM/yyyy",
'en-IL': "dd/MM/yyyy",
'en-IM': "dd/MM/yyyy",
'en-IN': "dd-MM-yyyy",
'en-IO': "dd/MM/yyyy",
'en-JE': "dd/MM/yyyy",
'en-JM': "d/M/yyyy",
'en-KE': "dd/MM/yyyy",
'en-KI': "dd/MM/yyyy",
'en-KN': "dd/MM/yyyy",
'en-KY': "dd/MM/yyyy",
'en-LC': "dd/MM/yyyy",
'en-LR': "dd/MM/yyyy",
'en-LS': "dd/MM/yyyy",
'en-MG': "dd/MM/yyyy",
'en-MH': "M/d/yyyy",
'en-MO': "dd/MM/yyyy",
'en-MP': "M/d/yyyy",
'en-MS': "dd/MM/yyyy",
'en-MT': "dd/MM/yyyy",
'en-MU': "dd/MM/yyyy",
'en-MW': "dd/MM/yyyy",
'en-MY': "d/M/yyyy",
'en-NA': "dd/MM/yyyy",
'en-NF': "dd/MM/yyyy",
'en-NG': "dd/MM/yyyy",
'en-NL': "dd/MM/yyyy",
'en-NR': "dd/MM/yyyy",
'en-NU': "dd/MM/yyyy",
'en-NZ': "d/MM/yyyy",
'en-PG': "dd/MM/yyyy",
'en-PH': "dd/MM/yyyy",
'en-PK': "dd/MM/yyyy",
'en-PN': "dd/MM/yyyy",
'en-PR': "M/d/yyyy",
'en-PW': "dd/MM/yyyy",
'en-RW': "dd/MM/yyyy",
'en-SB': "dd/MM/yyyy",
'en-SC': "dd/MM/yyyy",
'en-SD': "dd/MM/yyyy",
'en-SE': "yyyy-MM-dd",
'en-SG': "d/M/yyyy",
'en-SH': "dd/MM/yyyy",
'en-SI': "dd/MM/yyyy",
'en-SL': "dd/MM/yyyy",
'en-SS': "dd/MM/yyyy",
'en-SX': "dd/MM/yyyy",
'en-SZ': "dd/MM/yyyy",
'en-TC': "dd/MM/yyyy",
'en-TK': "dd/MM/yyyy",
'en-TO': "dd/MM/yyyy",
'en-TT': "dd/MM/yyyy",
'en-TV': "dd/MM/yyyy",
'en-TZ': "dd/MM/yyyy",
'en-UG': "dd/MM/yyyy",
'en-UM': "M/d/yyyy",
'en-US': "M/d/yyyy",
'en-VC': "dd/MM/yyyy",
'en-VG': "dd/MM/yyyy",
'en-VI': "M/d/yyyy",
'en-VU': "dd/MM/yyyy",
'en-WS': "dd/MM/yyyy",
'en-ZA': "yyyy/MM/dd",
'en-ZM': "dd/MM/yyyy",
'en-ZW': "d/M/yyyy",
'eo-001': "yyyy-MM-dd",
'es': "dd/MM/yyyy",
'es-419': "d/M/yyyy",
'es-AR': "d/M/yyyy",
'es-BO': "d/M/yyyy",
'es-BR': "d/M/yyyy",
'es-BZ': "d/M/yyyy",
'es-CL': "dd-MM-yyyy",
'es-CO': "d/MM/yyyy",
'es-CR': "d/M/yyyy",
'es-CU': "d/M/yyyy",
'es-DO': "d/M/yyyy",
'es-EC': "d/M/yyyy",
'es-ES': "dd/MM/yyyy",
'es-GQ': "d/M/yyyy",
'es-GT': "d/MM/yyyy",
'es-HN': "d/M/yyyy",
'es-MX': "dd/MM/yyyy",
'es-NI': "d/M/yyyy",
'es-PA': "MM/dd/yyyy",
'es-PE': "d/MM/yyyy",
'es-PH': "d/M/yyyy",
'es-PR': "MM/dd/yyyy",
'es-PY': "d/M/yyyy",
'es-SV': "d/M/yyyy",
'es-US': "M/d/yyyy",
'es-UY': "d/M/yyyy",
'es-VE': "d/M/yyyy",
'et': "dd.MM.yyyy",
'et-EE': "dd.MM.yyyy",
'eu-ES': "yyyy/M/d",
'ewo-CM': "d/M/yyyy",
'fa-IR': "dd/MM/yyyy",
'ff-CM': "d/M/yyyy",
'ff-GN': "d/M/yyyy",
'ff-Latn-SN': "dd/MM/yyyy",
'ff-MR': "d/M/yyyy",
'ff-NG': "d/M/yyyy",
'fi': "d.M.yyyy",
'fi-FI': "d.M.yyyy",
'fil-PH': "M/d/yyyy",
'fo': "dd.MM.yyyy",
'fo-DK': "dd.MM.yyyy",
'fo-FO': "dd.MM.yyyy",
'fr': "dd/MM/yyyy",
'fr-029': "dd/MM/yyyy",
'fr-BE': "dd-MM-yy",
'fr-BF': "dd/MM/yyyy",
'fr-BI': "dd/MM/yyyy",
'fr-BJ': "dd/MM/yyyy",
'fr-BL': "dd/MM/yyyy",
'fr-CA': "yyyy-MM-dd",
'fr-CD': "dd/MM/yyyy",
'fr-CF': "dd/MM/yyyy",
'fr-CG': "dd/MM/yyyy",
'fr-CH': "dd.MM.yyyy",
'fr-CI': "dd/MM/yyyy",
'fr-CM': "dd/MM/yyyy",
'fr-DJ': "dd/MM/yyyy",
'fr-DZ': "dd/MM/yyyy",
'fr-FR': "dd/MM/yyyy",
'fr-GA': "dd/MM/yyyy",
'fr-GF': "dd/MM/yyyy",
'fr-GN': "dd/MM/yyyy",
'fr-GP': "dd/MM/yyyy",
'fr-GQ': "dd/MM/yyyy",
'fr-HT': "dd/MM/yyyy",
'fr-KM': "dd/MM/yyyy",
'fr-LU': "dd/MM/yyyy",
'fr-MA': "dd/MM/yyyy",
'fr-MC': "dd/MM/yyyy",
'fr-MF': "dd/MM/yyyy",
'fr-MG': "dd/MM/yyyy",
'fr-ML': "dd/MM/yyyy",
'fr-MQ': "dd/MM/yyyy",
'fr-MR': "dd/MM/yyyy",
'fr-MU': "dd/MM/yyyy",
'fr-NC': "dd/MM/yyyy",
'fr-NE': "dd/MM/yyyy",
'fr-PF': "dd/MM/yyyy",
'fr-PM': "dd/MM/yyyy",
'fr-RE': "dd/MM/yyyy",
'fr-RW': "dd/MM/yyyy",
'fr-SC': "dd/MM/yyyy",
'fr-SN': "dd/MM/yyyy",
'fr-SY': "dd/MM/yyyy",
'fr-TD': "dd/MM/yyyy",
'fr-TG': "dd/MM/yyyy",
'fr-TN': "dd/MM/yyyy",
'fr-VU': "dd/MM/yyyy",
'fr-WF': "dd/MM/yyyy",
'fr-YT': "dd/MM/yyyy",
'fur-IT': "dd/MM/yyyy",
'fy-NL': "dd-MM-yyyy",
'ga': "dd/MM/yyyy",
'ga-IE': "dd/MM/yyyy",
'gd': "dd/MM/yyyy",
'gd-GB': "dd/MM/yyyy",
'gl': "dd/MM/yyyy",
'gl-ES': "dd/MM/yyyy",
'gn': "dd/MM/yyyy",
'gn-PY': "dd/MM/yyyy",
'gsw-CH': "dd.MM.yyyy",
'gsw-FR': "dd/MM/yyyy",
'gsw-LI': "dd.MM.yyyy",
'gu': "dd-MM-yy",
'gu-IN': "dd-MM-yy",
'guz-KE': "dd/MM/yyyy",
'gv-IM': "dd/MM/yyyy",
'ha-Latn-GH': "d/M/yyyy",
'ha-Latn-NE': "d/M/yyyy",
'ha-Latn-NG': "d/M/yyyy",
'haw-US': "d/M/yyyy",
'he-IL': "dd/MM/yyyy",
'hi-IN': "dd-MM-yyyy",
'hr': "d.M.yyyy.",
'hr-BA': "d. M. yyyy.",
'hr-HR': "d.M.yyyy.",
'hsb-DE': "d.M.yyyy",
'hu': "yyyy. MM. dd.",
'hu-HU': "yyyy. MM. dd.",
'hy-AM': "dd.MM.yyyy",
'ia-001': "yyyy/MM/dd",
'ia-FR': "yyyy/MM/dd",
'ibb-NG': "d/M/yyyy",
'id': "dd/MM/yyyy",
'id-ID': "dd/MM/yyyy",
'ig-NG': "dd/MM/yyyy",
'ii-CN': "yyyy/M/d",
'is': "d.M.yyyy",
'is-IS': "d.M.yyyy",
'it': "dd/MM/yyyy",
'it-CH': "dd.MM.yyyy",
'it-IT': "dd/MM/yyyy",
'it-SM': "dd/MM/yyyy",
'it-VA': "dd/MM/yyyy",
'iu-Cans-CA': "d/M/yyyy",
'iu-Latn-CA': "d/MM/yyyy",
'ja-JP': "yyyy/MM/dd",
'jgo-CM': "yyyy-MM-dd",
'jmc-TZ': "dd/MM/yyyy",
'jv-Java-ID': "dd/MM/yyyy",
'jv-Latn-ID': "dd/MM/yyyy",
'ka-GE': "dd.MM.yyyy",
'kab-DZ': "d/M/yyyy",
'kam-KE': "dd/MM/yyyy",
'kde-TZ': "dd/MM/yyyy",
'kea-CV': "d/M/yyyy",
'khq-ML': "d/M/yyyy",
'ki': "dd/MM/yyyy",
'ki-KE': "dd/MM/yyyy",
'kk-KZ': "dd.MM.yyyy",
'kkj-CM': "dd/MM yyyy",
'kl-GL': "dd-MM-yyyy",
'kln-KE': "dd/MM/yyyy",
'km': "dd/MM/yy",
'km-KH': "dd/MM/yy",
'kn': "dd-MM-yy",
'kn-IN': "dd-MM-yy",
'ko-KP': "yyyy. M. d.",
'ko-KR': "yyyy-MM-dd",
'kok-IN': "dd-MM-yyyy",
'kr': "d/M/yyyy",
'kr-NG': "d/M/yyyy",
'ks-Arab-IN': "M/d/yyyy",
'ks-Deva-IN': "dd-MM-yyyy",
'ksb-TZ': "dd/MM/yyyy",
'ksf-CM': "d/M/yyyy",
'ksh-DE': "d. M. yyyy",
'ku-Arab-IQ': "yyyy/MM/dd",
'ku-Arab-IR': "dd/MM/yyyy",
'kw': "dd/MM/yyyy",
'kw-GB': "dd/MM/yyyy",
'ky': "d-MMM yy",
'ky-KG': "d-MMM yy",
'la': "dd/MM/yyyy",
'la-001': "dd/MM/yyyy",
'lag-TZ': "dd/MM/yyyy",
'lb': "dd.MM.yy",
'lb-LU': "dd.MM.yy",
'lg-UG': "dd/MM/yyyy",
'lkt-US': "M/d/yyyy",
'ln-AO': "d/M/yyyy",
'ln-CD': "d/M/yyyy",
'ln-CF': "d/M/yyyy",
'ln-CG': "d/M/yyyy",
'lo-LA': "d/M/yyyy",
'lrc-IQ': "yyyy-MM-dd",
'lrc-IR': "dd/MM/yyyy",
'lt': "yyyy-MM-dd",
'lt-LT': "yyyy-MM-dd",
'lu': "d/M/yyyy",
'lu-CD': "d/M/yyyy",
'luo-KE': "dd/MM/yyyy",
'luy-KE': "dd/MM/yyyy",
'lv': "dd.MM.yyyy",
'lv-LV': "dd.MM.yyyy",
'mas-KE': "dd/MM/yyyy",
'mas-TZ': "dd/MM/yyyy",
'mer-KE': "dd/MM/yyyy",
'mfe-MU': "d/M/yyyy",
'mg': "yyyy-MM-dd",
'mg-MG': "yyyy-MM-dd",
'mgh-MZ': "dd/MM/yyyy",
'mgo-CM': "yyyy-MM-dd",
'mi-NZ': "dd/MM/yyyy",
'mk': "dd.M.yyyy",
'mk-MK': "dd.M.yyyy",
'ml': "d/M/yyyy",
'ml-IN': "d/M/yyyy",
'mn': "yyyy.MM.dd",
'mn-MN': "yyyy.MM.dd",
'mn-Mong-CN': "yyyy/M/d",
'mn-Mong-MN': "yyyy/M/d",
'mni-IN': "dd/MM/yyyy",
'moh-CA': "M/d/yyyy",
'mr': "dd-MM-yyyy",
'mr-IN': "dd-MM-yyyy",
'ms': "d/MM/yyyy",
'ms-BN': "d/MM/yyyy",
'ms-MY': "d/MM/yyyy",
'ms-SG': "d/MM/yyyy",
'mt': "dd/MM/yyyy",
'mt-MT': "dd/MM/yyyy",
'mua-CM': "d/M/yyyy",
'my': "dd-MM-yyyy",
'my-MM': "dd-MM-yyyy",
'mzn-IR': "dd/MM/yyyy",
'naq-NA': "dd/MM/yyyy",
'nb-NO': "dd.MM.yyyy",
'nb-SJ': "dd.MM.yyyy",
'nd-ZW': "dd/MM/yyyy",
'nds-DE': "d.MM.yyyy",
'nds-NL': "d.MM.yyyy",
'ne': "M/d/yyyy",
'ne-IN': "yyyy/M/d",
'ne-NP': "M/d/yyyy",
'nl': "d-M-yyyy",
'nl-AW': "dd-MM-yyyy",
'nl-BE': "d/MM/yyyy",
'nl-BQ': "dd-MM-yyyy",
'nl-CW': "dd-MM-yyyy",
'nl-NL': "d-M-yyyy",
'nl-SR': "dd-MM-yyyy",
'nl-SX': "dd-MM-yyyy",
'nmg-CM': "d/M/yyyy",
'nn-NO': "dd.MM.yyyy",
'nnh-CM': "dd/MM/yyyy",
'no': "dd.MM.yyyy",
'nqo-GN': "dd/MM/yyyy",
'nr': "yyyy-MM-dd",
'nr-ZA': "yyyy-MM-dd",
'nso-ZA': "yyyy-MM-dd",
'nus-SS': "d/MM/yyyy",
'nyn-UG': "dd/MM/yyyy",
'oc-FR': "dd/MM/yyyy",
'om': "dd/MM/yyyy",
'om-ET': "dd/MM/yyyy",
'om-KE': "dd/MM/yyyy",
'or-IN': "dd-MM-yy",
'os-GE': "dd.MM.yyyy",
'os-RU': "dd.MM.yyyy",
'pa': "dd-MM-yy",
'pa-Arab-PK': "dd-MM-yy",
'pa-IN': "dd-MM-yy",
'pap-029': "d-M-yyyy",
'pl': "dd.MM.yyyy",
'pl-PL': "dd.MM.yyyy",
'prg-001': "dd.MM.yyyy",
'prs-AF': "yyyy/M/d",
'ps': "yyyy/M/d",
'ps-AF': "yyyy/M/d",
'pt': "dd/MM/yyyy",
'pt-AO': "dd/MM/yyyy",
'pt-BR': "dd/MM/yyyy",
'pt-CH': "dd/MM/yyyy",
'pt-CV': "dd/MM/yyyy",
'pt-GQ': "dd/MM/yyyy",
'pt-GW': "dd/MM/yyyy",
'pt-LU': "dd/MM/yyyy",
'pt-MO': "dd/MM/yyyy",
'pt-MZ': "dd/MM/yyyy",
'pt-PT': "dd/MM/yyyy",
'pt-ST': "dd/MM/yyyy",
'pt-TL': "dd/MM/yyyy",
'quc-Latn-GT': "dd/MM/yyyy",
'quz-BO': "dd/MM/yyyy",
'quz-EC': "dd/MM/yyyy",
'quz-PE': "dd/MM/yyyy",
'rm-CH': "dd-MM-yyyy",
'rn-BI': "d/M/yyyy",
'ro': "dd.MM.yyyy",
'ro-MD': "dd.MM.yyyy",
'ro-RO': "dd.MM.yyyy",
'rof-TZ': "dd/MM/yyyy",
'ru': "dd.MM.yyyy",
'ru-BY': "dd.MM.yyyy",
'ru-KG': "dd.MM.yyyy",
'ru-KZ': "dd.MM.yyyy",
'ru-MD': "dd.MM.yyyy",
'ru-RU': "dd.MM.yyyy",
'ru-UA': "dd.MM.yyyy",
'rw': "yyyy-MM-dd",
'rw-RW': "yyyy-MM-dd",
'rwk-TZ': "dd/MM/yyyy",
'sa': "dd-MM-yyyy",
'sa-IN': "dd-MM-yyyy",
'sah-RU': "dd.MM.yyyy",
'saq-KE': "dd/MM/yyyy",
'sbp-TZ': "dd/MM/yyyy",
'sd': "dd/MM/yyyy",
'sd-Arab-PK': "dd/MM/yyyy",
'sd-Deva-IN': "dd/MM/yyyy",
'se': "yyyy-MM-dd",
'se-FI': "d.M.yyyy",
'se-NO': "yyyy-MM-dd",
'se-SE': "yyyy-MM-dd",
'seh-MZ': "d/M/yyyy",
'ses-ML': "d/M/yyyy",
'sg': "d/M/yyyy",
'sg-CF': "d/M/yyyy",
'shi-Latn-MA': "d/M/yyyy",
'shi-Tfng-MA': "d/M/yyyy",
'si': "yyyy-MM-dd",
'si-LK': "yyyy-MM-dd",
'sk': "d. M. yyyy",
'sk-SK': "d. M. yyyy",
'sl': "d. MM. yyyy",
'sl-SI': "d. MM. yyyy",
'sma-NO': "dd.MM.yyyy",
'sma-SE': "yyyy-MM-dd",
'smj-NO': "dd.MM.yyyy",
'smj-SE': "yyyy-MM-dd",
'smn-FI': "d.M.yyyy",
'sms-FI': "d.M.yyyy",
'sn': "yyyy-MM-dd",
'sn-Latn-ZW': "yyyy-MM-dd",
'so': "dd/MM/yyyy",
'so-DJ': "dd/MM/yyyy",
'so-ET': "dd/MM/yyyy",
'so-KE': "dd/MM/yyyy",
'so-SO': "dd/MM/yyyy",
'sq-AL': "d.M.yyyy",
'sq-MK': "d.M.yyyy",
'sq-XK': "d.M.yyyy",
'sr': "d.M.yyyy.",
'sr-Cyrl-BA': "d.M.yyyy.",
'sr-Cyrl-ME': "d.M.yyyy.",
'sr-Cyrl-RS': "dd.MM.yyyy.",
'sr-Cyrl-XK': "d.M.yyyy.",
'sr-Latn-BA': "d.M.yyyy.",
'sr-Latn-ME': "d.M.yyyy.",
'sr-Latn-RS': "d.M.yyyy.",
'sr-Latn-XK': "d.M.yyyy.",
'ss': "yyyy-MM-dd",
'ss-SZ': "yyyy-MM-dd",
'ss-ZA': "yyyy-MM-dd",
'ssy-ER': "dd/MM/yyyy",
'st': "yyyy-MM-dd",
'st-LS': "yyyy-MM-dd",
'st-ZA': "yyyy-MM-dd",
'sv': "yyyy-MM-dd",
'sv-AX': "yyyy-MM-dd",
'sv-FI': "dd-MM-yyyy",
'sv-SE': "yyyy-MM-dd",
'sw-CD': "dd/MM/yyyy",
'sw-KE': "dd/MM/yyyy",
'sw-TZ': "dd/MM/yyyy",
'sw-UG': "dd/MM/yyyy",
'syr-SY': "dd/MM/yyyy",
'ta-IN': "dd-MM-yyyy",
'ta-LK': "d/M/yyyy",
'ta-MY': "d/M/yyyy",
'ta-SG': "d/M/yyyy",
'te-IN': "dd-MM-yy",
'teo-KE': "dd/MM/yyyy",
'teo-UG': "dd/MM/yyyy",
'tg': "dd.MM.yyyy",
'tg-Cyrl-TJ': "dd.MM.yyyy",
'th': "d/M/yyyy",
'th-TH': "d/M/yyyy",
'ti-ER': "dd/MM/yyyy",
'ti-ET': "dd/MM/yyyy",
'tig-ER': "dd/MM/yyyy",
'tk': "dd.MM.yy 'ý.'",
'tk-TM': "dd.MM.yy 'ý.'",
'tn': "yyyy-MM-dd",
'tn-BW': "yyyy-MM-dd",
'tn-ZA': "yyyy-MM-dd",
'to': "d/M/yyyy",
'to-TO': "d/M/yyyy",
'tr': "d.MM.yyyy",
'tr-CY': "d.MM.yyyy",
'tr-TR': "d.MM.yyyy",
'ts-ZA': "yyyy-MM-dd",
'tt': "dd.MM.yyyy",
'tt-RU': "dd.MM.yyyy",
'twq-NE': "d/M/yyyy",
'tzm-Arab-MA': "d/M/yyyy",
'tzm-Latn-DZ': "dd-MM-yyyy",
'tzm-Latn-MA': "dd/MM/yyyy",
'tzm-Tfng-MA': "dd-MM-yyyy",
'ug': "yyyy-M-d",
'ug-CN': "yyyy-M-d",
'uk-UA': "dd.MM.yyyy",
'ur-IN': "d/M/yy",
'ur-PK': "dd/MM/yyyy",
'uz': "dd/MM/yyyy",
'uz-Arab-AF': "dd/MM yyyy",
'uz-Cyrl-UZ': "dd/MM/yyyy",
'uz-Latn-UZ': "dd/MM/yyyy",
'vai-Latn-LR': "dd/MM/yyyy",
'vai-Vaii-LR': "dd/MM/yyyy",
've': "yyyy-MM-dd",
've-ZA': "yyyy-MM-dd",
'vi': "dd/MM/yyyy",
'vi-VN': "dd/MM/yyyy",
'vo-001': "yyyy-MM-dd",
'vun-TZ': "dd/MM/yyyy",
'wae-CH': "yyyy-MM-dd",
'wal-ET': "dd/MM/yyyy",
'wo-SN': "dd/MM/yyyy",
'xh-ZA': "yyyy-MM-dd",
'xog-UG': "dd/MM/yyyy",
'yav-CM': "d/M/yyyy",
'yi-001': "dd/MM/yyyy",
'yo-BJ': "dd/MM/yyyy",
'yo-NG': "dd/MM/yyyy",
'zgh-Tfng-MA': "d/M/yyyy",
'zh-CN': "yyyy/M/d",
'zh-Hans-HK': "d/M/yyyy",
'zh-Hans-MO': "d/M/yyyy",
'zh-HK': "d/M/yyyy",
'zh-MO': "d/M/yyyy",
'zh-SG': "d/M/yyyy",
'zh-TW': "yyyy/M/d",
'zu-ZA': "M/d/yyyy",
};

How to download PDF automatically using js?

Use the download attribute.

var link = document.createElement('a');
link.href = url;
link.download = 'file.pdf';
link.dispatchEvent(new MouseEvent('click'));

JQuery Validate Dropdown list

The documentation for required() states:

To force a user to select an option from a select box, provide an empty options like <option value="">Choose...</option>

By having value="none" in your <option> tag, you are preventing the validation call from ever being made. You can also remove your custom validation rule, simplifying your code. Here's a jsFiddle showing it in action:

http://jsfiddle.net/Kn3v5/

If you can't change the value attribute to the empty string, I don't know what to tell you...I couldn't find any way to get it to validate otherwise.

Inserting a string into a list without getting split into characters

To add to the end of the list:

list.append('foo')

To insert at the beginning:

list.insert(0, 'foo')

How can I check the size of a collection within a Django template?

I need the collection length to decide whether I should render table <thead></thead>

but don't know why @Django 2.1.7 the chosen answer will fail(empty) my forloop afterward.

I got to use {% if forloop.first %} {% endif %} to overcome:

<table>
    {% for record in service_list %}
        {% if forloop.first %}
            <thead>
            <tr>
                <th>??</th>
            </tr>
            </thead>
        {% endif %}
        <tbody>
        <tr>
            <td>{{ record.date }}</td>
        </tr>
    {% endfor %}
    </tbody>
</table>

How do I prompt a user for confirmation in bash script?

qnd: use

read VARNAME
echo $VARNAME

for a one line response without readline support. Then test $VARNAME however you want.

Connect to external server by using phpMyAdmin

at version 4.0 or above, we need to create one 'config.inc.php' or rename the 'config.sample.inc.php' to 'config.inc.php';

In my case, I also work with one mysql server for each environment (dev and production):

/* others code*/  
$whoIam = gethostname();
switch($whoIam) {
    case 'devHost':
        $cfg['Servers'][$i]['host'] = 'localhost';
        break;
    case 'MasterServer':
        $cfg['Servers'][$i]['host'] = 'masterMysqlServer';
        break;
} /* others code*/ 

Adding new files to a subversion repository

Before you can add files in an unversioned directory, you have to add the directory itself to the versioning:

svn add directory_name

will add the directory directory_name and all sub-directories: http://svnbook.red-bean.com/en/1.8/svn.ref.svn.c.add.html

Pass entire form as data in jQuery Ajax function

Use

serialize( )

var str = $("form").serialize();

Serialize a form to a query string, that could be sent to a server in an Ajax request.

PHP pass variable to include

Considering that an include statment in php at the most basic level takes the code from a file and pastes it into where you called it and the fact that the manual on include states the following:

When a file is included, the code it contains inherits the variable scope of the line on which the include occurs. Any variables available at that line in the calling file will be available within the called file, from that point forward.

These things make me think that there is a diffrent problem alltogether. Also Option number 3 will never work because you're not redirecting to second.php you're just including it and option number 2 is just a weird work around. The most basic example of the include statment in php is:

vars.php
<?php

$color = 'green';
$fruit = 'apple';

?>

test.php
<?php

echo "A $color $fruit"; // A

include 'vars.php';

echo "A $color $fruit"; // A green apple

?>

Considering that option number one is the closest to this example (even though more complicated then it should be) and it's not working, its making me think that you made a mistake in the include statement (the wrong path relative to the root or a similar issue).

Laravel Eloquent inner join with multiple conditions

//You may use this example. Might be help you...

$user = User::select("users.*","items.id as itemId","jobs.id as jobId")
        ->join("items","items.user_id","=","users.id")
        ->join("jobs",function($join){
            $join->on("jobs.user_id","=","users.id")
                ->on("jobs.item_id","=","items.id");
        })
        ->get();
print_r($user);

Null check in an enhanced for loop

You should better verify where you get that list from.

An empty list is all you need, because an empty list won't fail.

If you get this list from somewhere else and don't know if it is ok or not you could create a utility method and use it like this:

for( Object o : safe( list ) ) {
   // do whatever 
 }

And of course safe would be:

public static List safe( List other ) {
    return other == null ? Collections.EMPTY_LIST : other;
}

how to read xml file from url using php

you can get the data from the XML by using "simplexml_load_file" Function. Please refer this link

http://php.net/manual/en/function.simplexml-load-file.php

$url = "http://maps.google.com/maps/api/directions/xml?origin=Quentin+Road+Brooklyn%2C+New+York%2C+11234+United+States&destination=550+Madison+Avenue+New+York%2C+New+York%2C+10001+United+States&sensor=false";
$xml = simplexml_load_file($url);
print_r($xml);

How to find the UpgradeCode and ProductCode of an installed application in Windows 7

If anyone wants to get installed application package code, just execute below command with your application name in the command prompt. You will be getting product code along with package code.

wmic product where "Name like '%YOUR_APPLICATION_NAME%'" get IdentifyingNumber, PackageCode

Can jQuery check whether input content has changed?

I had to use this kind of code for a scanner that pasted stuff into the field

$(document).ready(function() {
  var tId,oldVal;
  $("#fieldId").focus(function() {
     oldVal = $("#fieldId").val();
     tId=setInterval(function() { 
      var newVal = $("#fieldId").val(); 
      if (oldVal!=newVal) oldVal=newVal;
      someaction() },100);
  });
  $("#fieldId").blur(function(){ clearInterval(tId)});
});

Not tested...

Is it ok having both Anacondas 2.7 and 3.5 installed in the same time?

I use both depending on who in my department I am helping (Some people prefer 2.7, others 3.5). Anyway, I use Anaconda and my default installation is 3.5. I use environments for other versions of python, packages, etc.. So for example, when I wanted to start using python 2.7 I ran:

 conda create -n Python27 python=2.7

This creates a new environment named Python27 and installs Python version 2.7. You can add arguments to that line for installing other packages by default or just start from scratch. The environment will automatically activate, to deactivate simply type deactivate (windows) or source deactivate (linux, osx) in the command line. To activate in the future type activate Python27 (windows) or source activate Python27 (linux, osx). I would recommend reading the documentation for Managing Environments in Anaconda, if you choose to take that route.

Update

As of conda version 4.6 you can now use conda activate and conda deactivate. The use of source is now deprecated and will eventually be removed.

how to query for a list<String> in jdbctemplate

To populate a List of String, you need not use custom row mapper. Implement it using queryForList.

List<String>data=jdbcTemplate.queryForList(query,String.class)

How to add to an existing hash in Ruby

You can use double splat operator which is available since Ruby 2.0:

h = { a: 1, b: 2 }
h = { **h, c: 3 }
p h
# => {:a=>1, :b=>2, :c=>3}

How to use classes from .jar files?

As workmad3 says, you need the jar file to be in your classpath. If you're compiling from the commandline, that will mean using the -classpath flag. (Avoid the CLASSPATH environment variable; it's a pain in the neck IMO.)

If you're using an IDE, please let us know which one and we can help you with the steps specific to that IDE.