Programs & Examples On #Windows server 2008 web

Drop-down menu that opens up/upward with pure css

Add bottom:100% to your #menu:hover ul li:hover ul rule

Demo 1

#menu:hover ul li:hover ul {
    position: absolute;
    margin-top: 1px;
    font: 10px;
    bottom: 100%; /* added this attribute */
}

Or better yet to prevent the submenus from having the same effect, just add this rule

Demo 2

#menu>ul>li:hover>ul { 
    bottom:100%;
}

Demo 3

source: http://jsfiddle.net/W5FWW/4/

And to get back the border you can add the following attribute

#menu>ul>li:hover>ul { 
    bottom:100%;
    border-bottom: 1px solid transparent
}

DateTime.ToString("MM/dd/yyyy HH:mm:ss.fff") resulted in something like "09/14/2013 07.20.31.371"

Is it because some culture format issue?

Yes. Your user must be in a culture where the time separator is a dot. Both ":" and "/" are interpreted in a culture-sensitive way in custom date and time formats.

How can I make sure the result string is delimited by colon instead of dot?

I'd suggest specifying CultureInfo.InvariantCulture:

string text = dateTime.ToString("MM/dd/yyyy HH:mm:ss.fff",
                                CultureInfo.InvariantCulture);

Alternatively, you could just quote the time and date separators:

string text = dateTime.ToString("MM'/'dd'/'yyyy HH':'mm':'ss.fff");

... but that will give you "interesting" results that you probably don't expect if you get users running in a culture where the default calendar system isn't the Gregorian calendar. For example, take the following code:

using System;
using System.Globalization;
using System.Threading;

class Test
{
    static void Main()        
    {
        DateTime now = DateTime.Now;
        CultureInfo culture = new CultureInfo("ar-SA"); // Saudi Arabia
        Thread.CurrentThread.CurrentCulture = culture;
        Console.WriteLine(now.ToString("yyyy-MM-ddTHH:mm:ss.fff"));
    }
} 

That produces output (on September 18th 2013) of:

11/12/1434 15:04:31.750

My guess is that your web service would be surprised by that!

I'd actually suggest not only using the invariant culture, but also changing to an ISO-8601 date format:

string text = dateTime.ToString("yyyy-MM-ddTHH:mm:ss.fff");

This is a more globally-accepted format - it's also sortable, and makes the month and day order obvious. (Whereas 06/07/2013 could be interpreted as June 7th or July 6th depending on the reader's culture.)

Facebook Post Link Image

I've noticed that Facebook does not take thumbnails from websites if they start with https, is that maybe your case?

How to compile and run C in sublime text 3?

Have you tried just writing out the whole command in a single string?

{
"cmd" : ["gcc $file_name -o ${file_base_name} && ./${file_base_name}"],
"selector" : "source.c",
"shell": true,
"working_dir" : "$file_path"
}

I believe (semi-speculation here), that ST3 takes the first argument as the "program" and passes the other strings in as "arguments". https://docs.python.org/2/library/subprocess.html#subprocess.Popen

Keep only first n characters in a string?

Use the string.substring(from, to) API. In your case, use string.substring(0,8).

How can I generate Unix timestamps?

If I want to print utc date time using date command I need to using -u argument with date command.

Example

date -u

Output

Fri Jun 14 09:00:42 UTC 2019

java.lang.OutOfMemoryError: Java heap space

  1. Local variables are located on the stack. Heap space is occupied by objects.

  2. You can use the -Xmx option.

  3. Basically heap space is used up everytime you allocate a new object with new and freed some time after the object is no longer referenced. So make sure that you don't keep references to objects that you no longer need.

Stretch image to fit full container width bootstrap

First of all if the size of the image is smaller than the container, then only "img-fluid" class will not solve your problem. you have to set the width of image to 100%, for that you can use Bootstrap class "w-100". keep in mind that "container-fluid" and "col-12" class sets left and right padding to 15px and "row" class sets left and right margin to "-15px" by default. make sure to set them to 0.

Note: "px-0" is a bootstrap class which sets left and right padding to 0 and
"mx-0" is a bootstrap class which sets left and right margin to 0

P.S. i am using Bootstrap 4.0 version.

 <div class="container-fluid px-0">
        <div class="row mx-0">
            <div class="col-12 px-0">
            <img src="images/top.jpg" class="img-fluid w-100">
            </div>
        </div>
    </div>

ANTLR: Is there a simple example?

ANTLR mega tutorial by Gabriele Tomassetti is very helpful

It has grammar examples, examples of visitors in different languages (Java, JavaScript, C# and Python) and many other things. Highly recommended.

EDIT: other useful articles by Gabriele Tomassetti on ANTLR

How to process images of a video, frame by frame, in video streaming using OpenCV and Python

The only solution I have found is not to set the index to a previous frame and wait (then OpenCV stops reading frames, anyway), but to initialize the capture one more time. So, it looks like this:

cap = cv2.VideoCapture(camera_url)
while True:
    ret, frame = cap.read()

    if not ret:
        cap = cv.VideoCapture(camera_url)
        continue

    # do your processing here

And it works perfectly!

SSL: CERTIFICATE_VERIFY_FAILED with Python3

When you are using a self signed cert urllib3 version 1.25.3 refuses to ignore the SSL cert

To fix remove urllib3-1.25.3 and install urllib3-1.24.3

pip3 uninstall urllib3

pip3 install urllib3==1.24.3

Tested on Linux MacOS and Window$

Iterate through Nested JavaScript Objects

Here is a solution using object-scan

_x000D_
_x000D_
// const objectScan = require('object-scan');

const cars = { label: 'Autos', subs: [ { label: 'SUVs', subs: [] }, { label: 'Trucks', subs: [ { label: '2 Wheel Drive', subs: [] }, { label: '4 Wheel Drive', subs: [ { label: 'Ford', subs: [] }, { label: 'Chevrolet', subs: [] } ] } ] }, { label: 'Sedan', subs: [] } ] };

const find = (haystack, label) => objectScan(['**.label'], {
  filterFn: ({ value }) => value === label,
  rtn: 'parent',
  abort: true
})(haystack);

console.log(find(cars, 'Sedan'));
// => { label: 'Sedan', subs: [] }
console.log(find(cars, 'SUVs'));
// => { label: 'SUVs', subs: [] }
_x000D_
.as-console-wrapper {max-height: 100% !important; top: 0}
_x000D_
<script src="https://bundle.run/[email protected]"></script>
_x000D_
_x000D_
_x000D_

Disclaimer: I'm the author of object-scan

Converting dictionary to JSON

json.dumps() converts a dictionary to str object, not a json(dict) object! So you have to load your str into a dict to use it by using json.loads() method

See json.dumps() as a save method and json.loads() as a retrieve method.

This is the code sample which might help you understand it more:

import json

r = {'is_claimed': 'True', 'rating': 3.5}
r = json.dumps(r)
loaded_r = json.loads(r)
loaded_r['rating'] #Output 3.5
type(r) #Output str
type(loaded_r) #Output dict

How to use and style new AlertDialog from appCompat 22.1 and above

    <item name="editTextColor">@color/white</item>
    <item name="android:textColor">@color/white</item>
    <item name="android:textColorHint">@color/gray</item>
    <item name="android:textColorPrimary">@color/gray</item>
    <item name="colorControlNormal">@color/gray</item>
    <item name="colorControlActivated">@color/white</item>
    <item name="colorControlHighlight">#30FFFFFF</item>

Redirect in Spring MVC

Also note that redirect: and forward: prefixes are handled by UrlBasedViewResolver, so you need to have at least one subclass of UrlBasedViewResolver among your view resolvers, such as InternalResourceViewResolver.

Calling a Sub and returning a value

You should be using a Property:

Private _myValue As String
Public Property MyValue As String
    Get
        Return _myValue
    End Get
    Set(value As String)
        _myValue = value
     End Set
End Property

Then use it like so:

MyValue = "Hello"
Console.write(MyValue)

How do I clone a subdirectory only of a Git repository?

EDIT: As of Git 2.19, this is finally possible, as can be seen in this answer.

Consider upvoting that answer.

Note: in Git 2.19, only client-side support is implemented, server-side support is still missing, so it only works when cloning local repositories. Also note that large Git hosters, e.g. GitHub, don't actually use the Git server, they use their own implementation, so even if support shows up in the Git server, it does not automatically mean that it works on Git hosters. (OTOH, since they don't use the Git server, they could implement it faster in their own implementations before it shows up in Git server.)


No, that's not possible in Git.

Implementing something like this in Git would be a substantial effort and it would mean that the integrity of the clientside repository could no longer be guaranteed. If you are interested, search for discussions on "sparse clone" and "sparse fetch" on the git mailinglist.

In general, the consensus in the Git community is that if you have several directories that are always checked out independently, then these are really two different projects and should live in two different repositories. You can glue them back together using Git Submodules.

Count character occurrences in a string in C++

You can find out occurrence of '_' in source string by using string functions. find() function takes 2 arguments , first - string whose occurrences we want to find out and second argument takes starting position.While loop is use to find out occurrence till the end of source string.

example:

string str2 = "_";
string strData = "bla_bla_blabla_bla_";

size_t pos = 0,pos2;

while ((pos = strData.find(str2, pos)) < strData.length()) 
{
    printf("\n%d", pos);
    pos += str2.length();
} 

Comparing two input values in a form validation with AngularJS

You have to look at the bigger problem. How to write the directives that solve one problem. You should try directive use-form-error. Would it help to solve this problem, and many others.

    <form name="ExampleForm">
  <label>Password</label>
  <input ng-model="password" required />
  <br>
   <label>Confirm password</label>
  <input ng-model="confirmPassword" required />
  <div use-form-error="isSame" use-error-expression="password && confirmPassword && password!=confirmPassword" ng-show="ExampleForm.$error.isSame">Passwords Do Not Match!</div>
</form>

Live example jsfiddle

How do I create an .exe for a Java program?

Launch4j perhaps? Can't say I've used it myself, but it sounds like what you're after.

The easiest way to transform collection to array?

Here's the final solution for the case in update section (with the help of Google Collections):

Collections2.transform (fooCollection, new Function<Foo, Bar>() {
    public Bar apply (Foo foo) {
        return new Bar (foo);
    }
}).toArray (new Bar[fooCollection.size()]);

But, the key approach here was mentioned in the doublep's answer (I forgot for toArray method).

Converting dd/mm/yyyy formatted string to Datetime

use DateTime.ParseExact

string strDate = "24/01/2013";
DateTime date = DateTime.ParseExact(strDate, "dd/MM/YYYY", null)

null will use the current culture, which is somewhat dangerous. Try to supply a specific culture

DateTime date = DateTime.ParseExact(strDate, "dd/MM/YYYY", CultureInfo.InvariantCulture)

How can I send an email by Java application using GMail, Yahoo, or Hotmail?

Something like this (sounds like you just need to change your SMTP server):

String host = "smtp.gmail.com";
String from = "user name";
Properties props = System.getProperties();
props.put("mail.smtp.host", host);
props.put("mail.smtp.user", from);
props.put("mail.smtp.password", "asdfgh");
props.put("mail.smtp.port", "587"); // 587 is the port number of yahoo mail
props.put("mail.smtp.auth", "true");

Session session = Session.getDefaultInstance(props, null);
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));

InternetAddress[] to_address = new InternetAddress[to.length];
int i = 0;
// To get the array of addresses
while (to[i] != null) {
    to_address[i] = new InternetAddress(to[i]);
    i++;
}
System.out.println(Message.RecipientType.TO);
i = 0;
while (to_address[i] != null) {

    message.addRecipient(Message.RecipientType.TO, to_address[i]);
    i++;
}
message.setSubject("sending in a group");
message.setText("Welcome to JavaMail");
// alternately, to send HTML mail:
// message.setContent("<p>Welcome to JavaMail</p>", "text/html");
Transport transport = session.getTransport("smtp");
transport.connect("smtp.mail.yahoo.co.in", "user name", "asdfgh");
transport.sendMessage(message, message.getAllRecipients());
transport.close();

How to show soft-keyboard when edittext is focused

According to this answer I used the setSoftInputMode method and overrided theese methods in DialogFragment:

@Override
public void onCancel(@NonNull DialogInterface dialog) {
    super.onCancel(dialog);
    requireDialog().getWindow().setSoftInputMode(InputMethodManager.HIDE_IMPLICIT_ONLY);
}

@Override
public void onStart() {
    super.onStart();
    requireDialog().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
}

@Override
public void onStop() {
    super.onStop();
    requireDialog().getWindow().setSoftInputMode(InputMethodManager.HIDE_IMPLICIT_ONLY);
}

I also made my own subclass of DialogFragment with theese methods, so when you create another dialog and inherit from this class, you have the soft keyboard showed automatically without any other edits. Hope it will be useful for someone.

Nginx location "not equal to" regex

i was looking for the same. and found this solution.

Use negative regex assertion:

location ~ ^/(?!(favicon\.ico|resources|robots\.txt)) { 
.... # your stuff 
} 

Source Negated Regular Expressions in location

Explanation of Regex :

If URL does not match any of the following path

example.com/favicon.ico
example.com/resources
example.com/robots.txt

Then it will go inside that location block and will process it.

Is it possible to use pip to install a package from a private GitHub repository?

It also works with Bitbucket:

pip install git+ssh://[email protected]/username/projectname.git

Pip will use your SSH keys in this case.

is inaccessible due to its protection level

The reason being you can not access protected member data through the instance of the class.

Reason why it is not allowed is explained in this blog

Display html text in uitextview

For Swift 4, Swift 4.2: and Swift 5

let htmlString = """
    <html>
        <head>
            <style>
                body {
                    background-color : rgb(230, 230, 230);
                    font-family      : 'Arial';
                    text-decoration  : none;
                }
            </style>
        </head>
        <body>
            <h1>A title</h1>
            <p>A paragraph</p>
            <b>bold text</b>
        </body>
    </html>
    """

let htmlData = NSString(string: htmlString).data(using: String.Encoding.unicode.rawValue)

let options = [NSAttributedString.DocumentReadingOptionKey.documentType: NSAttributedString.DocumentType.html]

let attributedString = try! NSAttributedString(data: htmlData!, options: options, documentAttributes: nil)

textView.attributedText = attributedString

For Swift 3:

let htmlString = """
    <html>
        <head>
            <style>
                body {
                    background-color : rgb(230, 230, 230);
                    font-family      : 'Arial';
                    text-decoration  : none;
                }
            </style>
        </head>
        <body>
            <h1>A title</h1>
            <p>A paragraph</p>
            <b>bold text</b>
        </body>
    </html>
    """

let htmlData = NSString(string: htmlString).data(using: String.Encoding.unicode.rawValue)

let attributedString = try! NSAttributedString(data: htmlData!, options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType], documentAttributes: nil)

textView.attributedText = attributedString

What's the difference between an id and a class?

Perhaps an analogy will help understanding the difference:

<student id="JonathanSampson" class="Biology Calculus" />
<student id="MarySmith" class="Biology Networking" />

Student ID cards are distinct. No two students on campus will have the same student ID card. However, many students can and will share at least one Class with each other.

It's okay to put multiple students under one Class title, such as Biology. But it's never acceptable to put multiple students under one student ID.

When giving Rules over the school intercom system, you can give Rules to a Class:

"Tomorrow, all students are to wear a red shirt to Biology class."

.Biology {
  color: red;
}

Or you can give rules to a Specific Student, by calling his unique ID:

"Jonathan Sampson is to wear a green shirt tomorrow."

#JonathanSampson {
  color: green;
}

In this case, Jonathan Sampson is receiving two commands: one as a student in the Biology class, and another as a direct requirement. Because Jonathan was told directly, via the id attribute, to wear a green shirt, he will disregard the earlier request to wear a red shirt.

The more specific selectors win.

How can I rebuild indexes and update stats in MySQL innoDB?

This is done with

ANALYZE TABLE table_name;

Read more about it here.

ANALYZE TABLE analyzes and stores the key distribution for a table. During the analysis, the table is locked with a read lock for MyISAM, BDB, and InnoDB. This statement works with MyISAM, BDB, InnoDB, and NDB tables.

MySQL error 2006: mysql server has gone away

In MAMP (non-pro version) I added

--max_allowed_packet=268435456

to ...\MAMP\bin\startMysql.sh

Credits and more details here

Left function in c#

use substring function:

yourString.Substring(0, length);

Favicon dimensions?

The simplest solution in 2021 is to use one(!) PNG image

Simply add this to the head of your document:

<link rel="shortcut icon" type="image/png" href="/img/icon-192x192.png">
<link rel="shortcut icon" sizes="192x192" href="/img/icon-192x192.png">
<link rel="apple-touch-icon" href="/img/icon-192x192.png">

The last link is for Apple (home screen), the second one for Android (home screen) and the first one for the rest.

Note that this solution does not support "tiles" in Windows 8/10. It does, however, support images in shortcuts, bookmarks and browser-tabs.

The size is exactly the size the Android home screen uses. The Apple home screen icon size is 60px (3x), so 180px and will be scaled down. Other platforms use the default shortcut icon, which will be scaled down too.

How to get div height to auto-adjust to background size?

The best solution i can think of is by specifying your width and height in percent . This will allow you to rezise your screen based on your monitor size. its more of responsive layout..

For an instance. you have

<br/>
<div> . //This you set the width percent to %100
    <div> //This you set the width percent to any amount . if you put it by 50% , it will be half
    </div>
 </div>

This is the best option if you would want a responsive layout, i wouldnt recommend float , in certain cases float is okay to use. but in most cases , we avoid using float as it will affect a quite of number of things when you are doing cross-browser testing.

Hope this helps :)

Creating a copy of an object in C#

There is no built-in way. You can have MyClass implement the IClonable interface (but it is sort of deprecated) or just write your own Copy/Clone method. In either case you will have to write some code.

For big objects you could consider Serialization + Deserialization (through a MemoryStream), just to reuse existing code.

Whatever the method, think carefully about what "a copy" means exactly. How deep should it go, are there Id fields to be excepted etc.

Catch error if iframe src fails to load . Error :-"Refused to display 'http://www.google.co.in/' in a frame.."

I solved it with window.length. But with this solution you can take current error (X-Frame or 404).

iframe.onload = event => {
   const isLoaded = event.target.contentWindow.window.length // 0 or 1
}

MSDN

How to get DataGridView cell value in messagebox?

You can use the DataGridViewCell.Value Property to retrieve the value stored in a particular cell.

So to retrieve the value of the 'first' selected Cell and display in a MessageBox, you can:

MessageBox.Show(dataGridView1.SelectedCells[0].Value.ToString());

The above probably isn't exactly what you need to do. If you provide more details we can provide better help.

how to set JAVA_OPTS for Tomcat in Windows?

Apparently the correct form is without the ""

As in

set JAVA_OPTS=-Xms512M -Xmx1024M

How to install a private NPM module without my own registry?

Update January 2016

In addition to other answers, there is sometimes the scenario where you wish to have private modules available in a team context.

Both Github and Bitbucket support the concept of generating a team API Key. This API key can be used as the password to perform API requests as this team.

In your private npm modules add

"private": true 

to your package.json

Then to reference the private module in another module, use this in your package.json

    {
        "name": "myapp",
        "dependencies": {
            "private-repo":
"git+https://myteamname:[email protected]/myprivate.git",
        }
    }

where team name = myteamname, and API Key = aQqtcplwFzlumj0mIDdRGCbsAq5d6Xg4

Here I reference a bitbucket repo, but it is almost identical using github too.

Finally, as an alternative, if you really don't mind paying $7 per month (as of writing) then you can now have private NPM modules out of the box.

Good Linux (Ubuntu) SVN client

Anjuta has a built in SVN plugin which is integrated with the IDE.

Failed to start mongod.service: Unit mongod.service not found

Try this: sudo systemctl start mongod and to check whether its running use sudo systemctl status mongod

Adding script tag to React/JSX

There is a very nice workaround using Range.createContextualFragment.

/**
 * Like React's dangerouslySetInnerHTML, but also with JS evaluation.
 * Usage:
 *   <div ref={setDangerousHtml.bind(null, html)}/>
 */
function setDangerousHtml(html, el) {
    if(el === null) return;
    const range = document.createRange();
    range.selectNodeContents(el);
    range.deleteContents();
    el.appendChild(range.createContextualFragment(html));
}

This works for arbitrary HTML and also retains context information such as document.currentScript.

How to set environment variables in Jenkins?

Try Environment Script Plugin (GitHub) which is very similar to EnvInject. It allows you to run a script before the build (after SCM checkout) that generates environment variables for it. E.g.

Jenkins Build - Regular job - Build Environment

and in your script, you can print e.g. FOO=bar to the standard output to set that variable.

Example to append to an existing PATH-style variable:

echo PATH+unique_identifier=/usr/local/bin

So you're free to do whatever you need in the script - either cat a file, or run a script in some other language from your project's source tree, etc.

CSS :: child set to change color on parent hover, but changes also when hovered itself

If you don't care about supporting old browsers, you can use :not() to exclude that element:

.parent:hover span:not(:hover) {
    border: 10px solid red;
}

Demo: http://jsfiddle.net/vz9A9/1/

If you do want to support them, the I guess you'll have to either use JavaScript or override the CSS properties again:

.parent span:hover {
    border: 10px solid green;
}

Inline style to act as :hover in CSS

I'm afraid it can't be done, the pseudo-class selectors can't be set in-line, you'll have to do it on the page or on a stylesheet.

I should mention that technically you should be able to do it according to the CSS spec, but most browsers don't support it

Edit: I just did a quick test with this:

<a href="test.html" style="{color: blue; background: white} 
            :visited {color: green}
            :hover {background: yellow}
            :visited:hover {color: purple}">Test</a>

And it doesn't work in IE7, IE8 beta 2, Firefox or Chrome. Can anyone else test in any other browsers?

How to get current SIM card number in Android?

I think sim serial Number and sim number is unique. You can try this for get sim serial number and get sim number and Don't forget to add permission in manifest file.

TelephonyManager telemamanger = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
String getSimSerialNumber = telemamanger.getSimSerialNumber();
String getSimNumber = telemamanger.getLine1Number();

And add below permission into your Androidmanifest.xml file.

<uses-permission android:name="android.permission.READ_PHONE_STATE"/>

Let me know if there is any issue.

Finding non-numeric rows in dataframe in pandas?

Already some great answers to this question, however here is a nice snippet that I use regularly to drop rows if they have non-numeric values on some columns:

# Eliminate invalid data from dataframe (see Example below for more context)

num_df = (df.drop(data_columns, axis=1)
         .join(df[data_columns].apply(pd.to_numeric, errors='coerce')))

num_df = num_df[num_df[data_columns].notnull().all(axis=1)]

The way this works is we first drop all the data_columns from the df, and then use a join to put them back in after passing them through pd.to_numeric (with option 'coerce', such that all non-numeric entries are converted to NaN). The result is saved to num_df.

On the second line we use a filter that keeps only rows where all values are not null.

Note that pd.to_numeric is coercing to NaN everything that cannot be converted to a numeric value, so strings that represent numeric values will not be removed. For example '1.25' will be recognized as the numeric value 1.25.

Disclaimer: pd.to_numeric was introduced in pandas version 0.17.0

Example:

In [1]: import pandas as pd

In [2]: df = pd.DataFrame({"item": ["a", "b", "c", "d", "e"],
   ...:                    "a": [1,2,3,"bad",5],
   ...:                    "b":[0.1,0.2,0.3,0.4,0.5]})

In [3]: df
Out[3]: 
     a    b item
0    1  0.1    a
1    2  0.2    b
2    3  0.3    c
3  bad  0.4    d
4    5  0.5    e

In [4]: data_columns = ['a', 'b']

In [5]: num_df = (df
   ...:           .drop(data_columns, axis=1)
   ...:           .join(df[data_columns].apply(pd.to_numeric, errors='coerce')))

In [6]: num_df
Out[6]: 
  item   a    b
0    a   1  0.1
1    b   2  0.2
2    c   3  0.3
3    d NaN  0.4
4    e   5  0.5

In [7]: num_df[num_df[data_columns].notnull().all(axis=1)]
Out[7]: 
  item  a    b
0    a  1  0.1
1    b  2  0.2
2    c  3  0.3
4    e  5  0.5

Static Final Variable in Java

For the primitive types, the 'final static' will be a proper declaration to declare a constant. A non-static final variable makes sense when it is a constant reference to an object. In this case each instance can contain its own reference, as shown in JLS 4.5.4.

See Pavel's response for the correct answer.

Bulk create model objects in django

for a single line implementation, you can use a lambda expression in a map

map(lambda x:MyModel.objects.get_or_create(name=x), items)

Here, lambda matches each item in items list to x and create a Database record if necessary.

Lambda Documentation

How do I set the default schema for a user in MySQL

There is no default database for user. There is default database for current session.

You can get it using DATABASE() function -

SELECT DATABASE();

And you can set it using USE statement -

USE database1;

You should set it manually - USE db_name, or in the connection string.

Write to CSV file and export it?

Here's a very simple free open-source CsvExport class for C#. There's an ASP.NET MVC example at the bottom.

https://github.com/jitbit/CsvExport

It takes care about line-breaks, commas, escaping quotes, MS Excel compatibilty... Just add one short .cs file to your project and you're good to go.

(disclaimer: I'm one of the contributors)

Place input box at the center of div

You can just use either of the following approaches:

_x000D_
_x000D_
.center-block {
  margin: auto;
  display: block;
}
_x000D_
<div>
  <input class="center-block">
</div>
_x000D_
_x000D_
_x000D_

_x000D_
_x000D_
.parent {
  display: grid;
  place-items: center;
}
_x000D_
<div class="parent">
  <input>
</div>
_x000D_
_x000D_
_x000D_

Git says local branch is behind remote branch, but it's not

You probably did some history rewriting? Your local branch diverged from the one on the server. Run this command to get a better understanding of what happened:

gitk HEAD @{u}

I would strongly recommend you try to understand where this error is coming from. To fix it, simply run:

git push -f

The -f makes this a “forced push” and overwrites the branch on the server. That is very dangerous when you are working in team. But since you are on your own and sure that your local state is correct this should be fine. You risk losing commit history if that is not the case.

Indenting code in Sublime text 2?

There is no default shortcut for reindenting a file. However you can create one by following eznme's answer above.

You can also use the Command Palette by pressing:

  1. Control+Shift+P (or ?+Shift+P on a Mac)
  2. Type the first few characters of Reindent e.g: rein
  3. Press Enter to run the command
    (The first command at the top should now show Indentation: Reindent Lines)

Connecting to Microsoft SQL server using Python

My version. Hope it helps.


import pandas.io.sql
import pyodbc
import sys

server = 'example'
db = 'NORTHWND'
db2 = 'example'

#Crear la conexión
conn = pyodbc.connect('DRIVER={SQL Server};SERVER=' + server +
                      ';DATABASE=' + db +
                      ';DATABASE=' + db2 +
                      ';Trusted_Connection=yes')
#Query db
sql = """SELECT [EmployeeID]
      ,[LastName]
      ,[FirstName]
      ,[Title]
      ,[TitleOfCourtesy]
      ,[BirthDate]
      ,[HireDate]
      ,[Address]
      ,[City]
      ,[Region]
      ,[PostalCode]
      ,[Country]
      ,[HomePhone]
      ,[Extension]
      ,[Photo]
      ,[Notes]
      ,[ReportsTo]
      ,[PhotoPath]
  FROM [NORTHWND].[dbo].[Employees] """
data_frame = pd.read_sql(sql, conn)
data_frame

ReactJS: Warning: setState(...): Cannot update during an existing state transition

From react docs Passing arguments to event handlers

<button onClick={(e) => this.deleteRow(id, e)}>Delete Row</button>
<button onClick={this.deleteRow.bind(this, id)}>Delete Row</button>

Retrieving JSON Object Literal from HttpServletRequest

This is simple method to get request data from HttpServletRequest using Java 8 Stream API:

String requestData = request.getReader().lines().collect(Collectors.joining());

Bootstrap modal: close current, open new

I use another way:

$('#showModal').on('hidden.bs.modal', function() {
        $('#easyModal').on('shown.bs.modal', function() {
            $('body').addClass('modal-open');
        });
    });

change the date format in laravel view page

In Laravel use Carbon its good

{{ \Carbon\Carbon::parse($user->from_date)->format('d/m/Y')}}

php error: Class 'Imagick' not found

Ubuntu

sudo apt-get install php5-dev pecl imagemagick libmagickwand-dev
sudo pecl install imagick
sudo apt-get install php5-imagick
sudo service apache2 restart

Some dependencies will probably already be met but excluding the Apache service, that's everything required for PHP to use the Imagick class.

How to use comparison operators like >, =, < on BigDecimal

Every object of the Class BigDecimal has a method compareTo you can use to compare it to another BigDecimal. The result of compareTo is then compared > 0, == 0 or < 0 depending on what you need. Read the documentation and you will find out.

The operators ==, <, > and so on can only be used on primitive data types like int, long, double or their wrapper classes like Integerand Double.

From the documentation of compareTo:

Compares this BigDecimal with the specified BigDecimal.

Two BigDecimal objects that are equal in value but have a different scale (like 2.0 and 2.00) are considered equal by this method. This method is provided in preference to individual methods for each of the six boolean comparison operators (<, ==, >, >=, !=, <=). The suggested idiom for performing these comparisons is: (x.compareTo(y) <op> 0), where <op> is one of the six comparison operators.

Returns: -1, 0, or 1 as this BigDecimal is numerically less than, equal to, or greater than val.

Memory errors and list limits?

First off, see How Big can a Python Array Get? and Numpy, problem with long arrays

Second, the only real limit comes from the amount of memory you have and how your system stores memory references. There is no per-list limit, so Python will go until it runs out of memory. Two possibilities:

  1. If you are running on an older OS or one that forces processes to use a limited amount of memory, you may need to increase the amount of memory the Python process has access to.
  2. Break the list apart using chunking. For example, do the first 1000 elements of the list, pickle and save them to disk, and then do the next 1000. To work with them, unpickle one chunk at a time so that you don't run out of memory. This is essentially the same technique that databases use to work with more data than will fit in RAM.

Getting the last argument passed to a shell script

This is Bash-only:

echo "${@: -1}"

Initialization of all elements of an array to one default value in C++?

The page you linked states

If an explicit array size is specified, but an shorter initiliazation list is specified, the unspecified elements are set to zero.

Speed issue: Any differences would be negligible for arrays this small. If you work with large arrays and speed is much more important than size, you can have a const array of the default values (initialized at compile time) and then memcpy them to the modifiable array.

How to search for an element in an stl list?

No, find() method is not a member of std::list. Instead, use std::find from <algorithm>

    std :: list < int > l;
    std :: list < int > :: iterator pos;

    l.push_back(1);
    l.push_back(2);
    l.push_back(3);
    l.push_back(4);
    l.push_back(5);
    l.push_back(6);

    int elem = 3;   
    pos = find(l.begin() , l.end() , elem);
    if(pos != l.end() )
        std :: cout << "Element is present. "<<std :: endl;
    else
        std :: cout << "Element is not present. "<<std :: endl;

In Linux, how to tell how much memory processes are using?

Getting right memory usage is trickier than one may think. The best way I could find is:

echo 0 $(awk '/TYPE/ {print "+", $2}' /proc/`pidof PROCESS`/smaps) | bc

Where "PROCESS" is the name of the process you want to inspect and "TYPE" is one of:

  • Rss: resident memory usage, all memory the process uses, including all memory this process shares with other processes. It does not include swap;
  • Shared: memory that this process shares with other processes;
  • Private: private memory used by this process, you can look for memory leaks here;
  • Swap: swap memory used by the process;
  • Pss: Proportional Set Size, a good overall memory indicator. It is the Rss adjusted for sharing: if a process has 1MiB private and 20MiB shared between other 10 processes, Pss is 1 + 20/10 = 3MiB

Other valid values are Size (i.e. virtual size, which is almost meaningless) and Referenced (the amount of memory currently marked as referenced or accessed).

You can use watch or some other bash-script-fu to keep an eye on those values for processes that you want to monitor.

For more informations about smaps: http://www.kernel.org/doc/Documentation/filesystems/proc.txt.

Conditional Formatting using Excel VBA code

I think I just discovered a way to apply overlapping conditions in the expected way using VBA. After hours of trying out different approaches I found that what worked was changing the "Applies to" range for the conditional format rule, after every single one was created!

This is my working example:

Sub ResetFormatting()
' ----------------------------------------------------------------------------------------
' Written by..: Julius Getz Mørk
' Purpose.....: If conditional formatting ranges are broken it might cause a huge increase
'               in duplicated formatting rules that in turn will significantly slow down
'               the spreadsheet.
'               This macro is designed to reset all formatting rules to default.
' ---------------------------------------------------------------------------------------- 

On Error GoTo ErrHandler

' Make sure we are positioned in the correct sheet
WS_PROMO.Select

' Disable Events
Application.EnableEvents = False

' Delete all conditional formatting rules in sheet
Cells.FormatConditions.Delete

' CREATE ALL THE CONDITIONAL FORMATTING RULES:

' (1) Make negative values red
With Cells(1, 1).FormatConditions.add(xlCellValue, xlLess, "=0")
    .Font.Color = -16776961
    .StopIfTrue = False
End With

' (2) Highlight defined good margin as green values
With Cells(1, 1).FormatConditions.add(xlCellValue, xlGreater, "=CP_HIGH_MARGIN_DEFINITION")
    .Font.Color = -16744448
    .StopIfTrue = False
End With

' (3) Make article strategy "D" red
With Cells(1, 1).FormatConditions.add(xlCellValue, xlEqual, "=""D""")
    .Font.Bold = True
    .Font.Color = -16776961
    .StopIfTrue = False
End With

' (4) Make article strategy "A" blue
With Cells(1, 1).FormatConditions.add(xlCellValue, xlEqual, "=""A""")
    .Font.Bold = True
    .Font.Color = -10092544
    .StopIfTrue = False
End With

' (5) Make article strategy "W" green
With Cells(1, 1).FormatConditions.add(xlCellValue, xlEqual, "=""W""")
    .Font.Bold = True
    .Font.Color = -16744448
    .StopIfTrue = False
End With

' (6) Show special cost in bold green font
With Cells(1, 1).FormatConditions.add(xlCellValue, xlNotEqual, "=0")
    .Font.Bold = True
    .Font.Color = -16744448
    .StopIfTrue = False
End With

' (7) Highlight duplicate heading names. There can be none.
With Cells(1, 1).FormatConditions.AddUniqueValues
    .DupeUnique = xlDuplicate
    .Font.Color = -16383844
    .Interior.Color = 13551615
    .StopIfTrue = False
End With

' (8) Make heading rows bold with yellow background
With Cells(1, 1).FormatConditions.add(Type:=xlExpression, Formula1:="=IF($B8=""H"";TRUE;FALSE)")
    .Font.Bold = True
    .Interior.Color = 13434879
    .StopIfTrue = False
End With

' Modify the "Applies To" ranges
Cells.FormatConditions(1).ModifyAppliesToRange Range("O8:P507")
Cells.FormatConditions(2).ModifyAppliesToRange Range("O8:O507")
Cells.FormatConditions(3).ModifyAppliesToRange Range("B8:B507")
Cells.FormatConditions(4).ModifyAppliesToRange Range("B8:B507")
Cells.FormatConditions(5).ModifyAppliesToRange Range("B8:B507")
Cells.FormatConditions(6).ModifyAppliesToRange Range("E8:E507")
Cells.FormatConditions(7).ModifyAppliesToRange Range("A7:AE7")
Cells.FormatConditions(8).ModifyAppliesToRange Range("B8:L507")


ErrHandler:
Application.EnableEvents = False

End Sub

How to get .pem file from .key and .crt files?

A pem file contains the certificate and the private key. It depends on the format your certificate/key are in, but probably it's as simple as this:

cat server.crt server.key > server.pem

Why is Spring's ApplicationContext.getBean considered bad?

I mentioned this in a comment on the other question, but the whole idea of Inversion of Control is to have none of your classes know or care how they get the objects they depend on. This makes it easy to change what type of implementation of a given dependency you use at any time. It also makes the classes easy to test, as you can provide mock implementations of dependencies. Finally, it makes the classes simpler and more focused on their core responsibility.

Calling ApplicationContext.getBean() is not Inversion of Control! While it's still easy to change what implemenation is configured for the given bean name, the class now relies directly on Spring to provide that dependency and can't get it any other way. You can't just make your own mock implementation in a test class and pass that to it yourself. This basically defeats Spring's purpose as a dependency injection container.

Everywhere you want to say:

MyClass myClass = applicationContext.getBean("myClass");

you should instead, for example, declare a method:

public void setMyClass(MyClass myClass) {
   this.myClass = myClass;
}

And then in your configuration:

<bean id="myClass" class="MyClass">...</bean>

<bean id="myOtherClass" class="MyOtherClass">
   <property name="myClass" ref="myClass"/>
</bean>

Spring will then automatically inject myClass into myOtherClass.

Declare everything in this way, and at the root of it all have something like:

<bean id="myApplication" class="MyApplication">
   <property name="myCentralClass" ref="myCentralClass"/>
   <property name="myOtherCentralClass" ref="myOtherCentralClass"/>
</bean>

MyApplication is the most central class, and depends at least indirectly on every other service in your program. When bootstrapping, in your main method, you can call applicationContext.getBean("myApplication") but you should not need to call getBean() anywhere else!

What is resource-ref in web.xml used for?

You can always refer to resources in your application directly by their JNDI name as configured in the container, but if you do so, essentially you are wiring the container-specific name into your code. This has some disadvantages, for example, if you'll ever want to change the name later for some reason, you'll need to update all the references in all your applications, and then rebuild and redeploy them.

<resource-ref> introduces another layer of indirection: you specify the name you want to use in the web.xml, and, depending on the container, provide a binding in a container-specific configuration file.

So here's what happens: let's say you want to lookup the java:comp/env/jdbc/primaryDB name. The container finds that web.xml has a <resource-ref> element for jdbc/primaryDB, so it will look into the container-specific configuration, that contains something similar to the following:

<resource-ref>
  <res-ref-name>jdbc/primaryDB</res-ref-name>
  <jndi-name>jdbc/PrimaryDBInTheContainer</jndi-name>
</resource-ref>

Finally, it returns the object registered under the name of jdbc/PrimaryDBInTheContainer.

The idea is that specifying resources in the web.xml has the advantage of separating the developer role from the deployer role. In other words, as a developer, you don't have to know what your required resources are actually called in production, and as the guy deploying the application, you will have a nice list of names to map to real resources.

find_spec_for_exe': can't find gem bundler (>= 0.a) (Gem::GemNotFoundException)

In my case the above suggestions did not work for me. Mine was little different scenario.

When i tried installing bundler using gem install bundler .. But i was getting

ERROR:  While executing gem ... (Gem::FilePermissionError)
    You don't have write permissions for the /Library/Ruby/Gems/2.3.0 directory.

then i tried using sudo gem install bundler then i was getting

ERROR:  While executing gem ... (Gem::FilePermissionError)
  You don't have write permissions for the /usr/bin directory.

then i tried with sudo gem install bundler -n /usr/local/bin ( Just /usr/bin dint work in my case ).

And then successfully installed bundler

EDIT: I use MacOS, maybe /usr/bin din't work for me for that reason (https://stackoverflow.com/a/34989655/3786657 comment )

Regex allow a string to only contain numbers 0 - 9 and limit length to 45

A combination of both attempts is probably what you need:

^[0-9]{1,45}$

Jquery Chosen plugin - dynamically populate list by Ajax

try this:

$('.chzn-choices input').autocomplete({
  source: function( request, response ) {
    $.ajax({
      url: "/change/name/autocomplete/"+request.term+"/",
      dataType: "json",
      beforeSend: function(){$('ul.chzn-results').empty();},
      success: function( data ) {
        response( $.map( data, function( item ) {
          $('ul.chzn-results').append('<li class="active-result">' + item.name + '</li>');
        }));
      }
    });
  }
});

What is the purpose of Looper and how to use it?

This answer has nothing to do with the question, but the use of looper and the way people created the handler and looper in ALL the answers here are plain bad practice (some explanations are correct though), I have to post this:

HandlerThread thread = new HandlerThread(threadName);
thread.start();
Looper looper = thread.getLooper();
Handler myHandler = new Handler(looper);

and for a full implementation

Where is the .NET Framework 4.5 directory?

.NET 4.5 is not a side-by-side version, it replaces the assemblies for 4.0. Much like .NET 3.0, 3.5 and 3.5SP1 replaced the assemblies for 2.0. And added some new ones. The CLR version is still 4.0.30319. You only care about the reference assemblies, they are in c:\program files\reference assemblies.

ALTER TABLE ADD COLUMN IF NOT EXISTS in SQLite

One workaround is to just create the columns and catch the exception/error that arise if the column already exist. When adding multiple columns, add them in separate ALTER TABLE statements so that one duplicate does not prevent the others from being created.

With sqlite-net, we did something like this. It's not perfect, since we can't distinguish duplicate sqlite errors from other sqlite errors.

Dictionary<string, string> columnNameToAddColumnSql = new Dictionary<string, string>
{
    {
        "Column1",
        "ALTER TABLE MyTable ADD COLUMN Column1 INTEGER"
    },
    {
        "Column2",
        "ALTER TABLE MyTable ADD COLUMN Column2 TEXT"
    }
};

foreach (var pair in columnNameToAddColumnSql)
{
    string columnName = pair.Key;
    string sql = pair.Value;

    try
    {
        this.DB.ExecuteNonQuery(sql);
    }
    catch (System.Data.SQLite.SQLiteException e)
    {
        _log.Warn(e, string.Format("Failed to create column [{0}]. Most likely it already exists, which is fine.", columnName));
    }
}

Saving changes after table edit in SQL Server Management Studio

Rather than unchecking the box (a poor solution), you should STOP editing data that way. If data must be changed, then do it with a script, so that you can easily port it to production and so that it is under source control. This also makes it easier to refresh testing changes after production has been pushed down to dev to enable developers to be working against fresher data.

how to write value into cell with vba code without auto type conversion?

This is probably too late, but I had a similar problem with dates that I wanted entered into cells from a text variable. Inevitably, it converted my variable text value to a date. What I finally had to do was concatentate a ' to the string variable and then put it in the cell like this:

prvt_rng_WrkSht.Cells(prvt_rng_WrkSht.Rows.Count, cnst_int_Col_Start_Date).Formula = "'" & _ 
    param_cls_shift.Start_Date (string property of my class) 

What does "Object reference not set to an instance of an object" mean?

what does this error mean? Object reference not set to an instance of an object.

exactly what it says, you are trying to use a null object as if it was a properly referenced object.

Format LocalDateTime with Timezone in Java8

LocalDateTime is a date-time without a time-zone. You specified the time zone offset format symbol in the format, however, LocalDateTime doesn't have such information. That's why the error occured.

If you want time-zone information, you should use ZonedDateTime.

DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("yyyyMMdd HH:mm:ss.SSSSSS Z");
ZonedDateTime.now().format(FORMATTER);
=> "20140829 14:12:22.122000 +09"

keytool error bash: keytool: command not found

These are the steps which solved my problem:

  • Search the path where my java was installed

    find / -name jre
    
  • Move to java directory (where jre was installed on my server)

    cd /path/to/jre/bin
    
  • Create SSL certificate with keytool command

    ./keytool -genkey -alias [mypassword] -keyalg [RSA]
    

php resize image on upload

You can use this library to manipulate the image while uploading. http://www.verot.net/php_class_upload.htm

How to get the url parameters using AngularJS

If you're using ngRoute, you can inject $routeParams into your controller

http://docs.angularjs.org/api/ngRoute/service/$routeParams

If you're using angular-ui-router, you can inject $stateParams

https://github.com/angular-ui/ui-router/wiki/URL-Routing

Why does PEP-8 specify a maximum line length of 79 characters?

I agree with Justin. To elaborate, overly long lines of code are harder to read by humans and some people might have console widths that only accommodate 80 characters per line.

The style recommendation is there to ensure that the code you write can be read by as many people as possible on as many platforms as possible and as comfortably as possible.

MySQL Insert into multiple tables? (Database normalization?)

For PDO You may do this

$stmt1 = "INSERT INTO users (username, password) VALUES('test', 'test')"; 
$stmt2 = "INSERT INTO profiles (userid, bio, homepage) VALUES('LAST_INSERT_ID(),'Hello world!', 'http://www.stackoverflow.com')";

$sth1 = $dbh->prepare($stmt1);
$sth2 = $dbh->prepare($stmt2);

BEGIN;
$sth1->execute (array ('test','test'));
$sth2->execute (array ('Hello world!','http://www.stackoverflow.com'));
COMMIT;

How to get build time stamp from Jenkins build variables?

One way this can be done is using shell script in global environment section, here, I am using UNIX timestamp but you can use any shell script syntax compatible time format:

pipeline {

    agent any

    environment {
        def BUILDVERSION = sh(script: "echo `date +%s`", returnStdout: true).trim()
    }

    stages {
        stage("Awesome Stage") {
            steps {
                echo "Current build version :: $BUILDVERSION"
            }
        }
    }
}

MySQL duplicate entry error even though there is no duplicate entry

i have just tried, and if you have data and table recreation wouldnt work, just alter table to InnoDB and try again, it would fix the problem

Load HTML File Contents to Div [without the use of iframes]

2019
Using fetch

<script>
fetch('page.html')
  .then(data => data.text())
  .then(html => document.getElementById('elementID').innerHTML = html);
</script>

<div id='elementID'> </div>

fetch needs to receive a http or https link, this means that it won't work locally.

Note: As Altimus Prime said, it is a feature for modern browsers

React passing parameter via onclick event using ES6 syntax

Use the value attribute of the button element to pass the id, as

<button onClick={this.handleRemove} value={id}>Remove</button>

and then in handleRemove, read the value from event as:

handleRemove(event) {
...
 remove(event.target.value);
...
}

This way you avoid creating a new function (when compared to using an arrow function) every time this component is re-rendered.

Difference between RUN and CMD in a Dockerfile

There has been enough answers on RUN and CMD. I just want to add a few words on ENTRYPOINT. CMD arguments can be overwritten by command line arguments, while ENTRYPOINT arguments are always used.

This article is a good source of information.

How to suppress "error TS2533: Object is possibly 'null' or 'undefined'"?

This is rather verbose and don't like it but it's the only thing that worked for me:

if (inputFile && inputFile.current) {
        ((inputFile.current as never) as HTMLInputElement).click()
}

only

if (inputFile && inputFile.current) {
        inputFile.current.click() // also with ! or ? didn't work
}

didn't work for me. Typesript version: 3.9.7 with eslint and recommended rules.

Is there a Mutex in Java?

To ensure that a Semaphore is binary you just need to make sure you pass in the number of permits as 1 when creating the semaphore. The Javadocs have a bit more explanation.

The specified DSN contains an architecture mismatch between the Driver and Application. JAVA

You get this exact same error when trying to connect to a MySQL database from MS-Access when the bit version (32 vs 64) of Access doesn't match

  1. the bit version of the ODBC Driver you are using
  2. the bit version of the ODBC Manager you used to set it up.

For those of you trying to connect MS-Access to MySQL on a 64 bit Windows system, I went through sheer torture trying to get it to work with both MS-Access 2010 and MS-Access 2013. Finally got it working, and here are the lessons I've learned along the way:

I bought a new Windows 7, 64 bit laptop, and I have an app which relies on MS-Access using MySQL tables.

  1. I installed the latest version of MySQL, 5.6, using the All In One package install. This allows you to install both the database and ODBC drivers all at once. That's nice, but the ODBC driver it installs seems to be the 64 bit one, so it will not work with 32 bit MS-Access. It also seems a little buggy - not for sure on that one. When you Add a new DSN in the ODBC Manager, this driver appears as "Microsoft ODBC For Oracle". I could not get this one to work. I had to install the 32 bit one, discussed below.

    • MySQL was working fine after the install. I restored my application MySQL database in the usual way. Now I want to connect to it using MS-Access.


  2. I had previously installed Office 2013, which I assumed was 64 bit. But upon checking the version (File, Account, About Access), I see that it is 32 bit. Both Access 2010 and 2013 are most commonly sold as 32-bit versions.

  3. My machine is a 64 bit machine. So by default, when you go to set up your DSN's for MS-Access, and go in the usual way into the ODBC Manager via Control Panel, Administrative Options, you get the 64 bit ODBC manager. You have no way of knowing that! You just can't tell. This is a huge gotcha!! It is impossible to set up a DSN from there and have it successfully connect to MS Access 32 bit. You will get the dreaded error:

    "the specified dsn contains an architecture mismatch..."

  4. You must download and install the 32 bit ODBC driver from MySQL. I used version 3.5.1

    http://dev.mysql.com/downloads/connector/odbc/3.51.html

  5. You must tell the ODBC Manager in Control Panel to take a hike and must instead explicitly invoke the 32 bit ODBC Manager with this command executed at the Start, Command prompt:

    c:\windows\sysWOW64\odbcad32.exe

    I created a shortcut to this on my desktop. From here, build your DSN with this manager. Important point: BUILD THEM AS SYSTEM DSNS, NOT USER DSNS! This tripped me up for awhile.

    By the way, the 64 bit version of the ODBC Manager can also be run explicitly as:

    c:\windows\system32\odbcad32.exe

  6. Once you've installed the 32-bit ODBC Driver from MySql, when you click Add in the ODBC Manager you will see 2 drivers listed. Choose "MySQL ODBC 5.2 ANSI Driver". I did not try the UNICODE driver.


That does it. Once you have defined your DSN's in the 32 bit ODBC manager, you can connect to MySQL in the usual way from within Access - External Data, ODBC Database, Link to the Database, select Machine Data Source, and the DSN you created to your MySQL database will be there.

Can Python test the membership of multiple values in a list?

Both of the answers presented here will not handle repeated elements. For example, if you are testing whether [1,2,2] is a sublist of [1,2,3,4], both will return True. That may be what you mean to do, but I just wanted to clarify. If you want to return false for [1,2,2] in [1,2,3,4], you would need to sort both lists and check each item with a moving index on each list. Just a slightly more complicated for loop.

AngularJS - How to use $routeParams in generating the templateUrl?

Router:-

...
.when('/enquiry/:page', {
    template: '<div ng-include src="templateUrl" onload="onLoad()"></div>',
    controller: 'enquiryCtrl'
})
...

Controller:-

...
// template onload event
$scope.onLoad = function() {
    console.log('onLoad()');
    f_tcalInit();  // or other onload stuff
}

// initialize
$scope.templateUrl = 'ci_index.php/adminctrl/enquiry/'+$routeParams.page;
...

I believe it is a weakness in angularjs that $routeParams is NOT visible inside the router. A tiny enhancement would make a world of difference during implementation.

How can I know if Object is String type object?

javamonkey79 is right. But don't forget what you might want to do (e.g. try something else or notify someone) if object is not an instance of String.

String myString;
if (object instanceof String) {
  myString = (String) object;
} else {
  // do something else     
}

BTW: If you use ClassCastException instead of Exception in your code above, you can be sure that you will catch the exception caused by casting object to String. And not any other exceptions caused by other code (e.g. NullPointerExceptions).

How to grep a text file which contains some binary data?

You can use "strings" to extract strings from a binary file, for example

strings binary.file | grep foo

Removing a model in rails (reverse of "rails g model Title...")

For future questioners: If you can't drop the tables from the console, try to create a migration that drops the tables for you. You should create a migration and then in the file note tables you want dropped like this:

class DropTables < ActiveRecord::Migration
  def up
    drop_table :table_you_dont_want
  end

  def down
    raise ActiveRecord::IrreversibleMigration
  end
end

Difference between 2 dates in seconds

$timeFirst  = strtotime('2011-05-12 18:20:20');
$timeSecond = strtotime('2011-05-13 18:20:20');
$differenceInSeconds = $timeSecond - $timeFirst;

You will then be able to use the seconds to find minutes, hours, days, etc.

Replace X-axis with own values

Yo could also set labels = FALSE inside axis(...) and print the labels in a separate command with Text. With this option you can rotate the text the text in case you need it

lablist<-as.vector(c(1:10))
axis(1, at=seq(1, 10, by=1), labels = FALSE)
text(seq(1, 10, by=1), par("usr")[3] - 0.2, labels = lablist, srt = 45, pos = 1, xpd = TRUE)

Detailed explanation here

Image with rotated labels

C++ calling base class constructors

Why the base class' default constructor is called? Turns out it's not always be the case. Any constructor of the base class (with different signatures) can be invoked from the derived class' constructor. In your case, the default constructor is called because it has no parameters so it's default.

When a derived class is created, the order the constructors are called is always Base -> Derived in the hierarchy. If we have:

class A {..}
class B : A {...}
class C : B {...}
C c;

When c is create, the constructor for A is invoked first, and then the constructor for B, and then the constructor for C.

To guarantee that order, when a derived class' constructor is called, it always invokes the base class' constructor before the derived class' constructor can do anything else. For that reason, the programmer can manually invoke a base class' constructor in the only initialisation list of the derived class' constructor, with corresponding parameters. For instance, in the following code, Derived's default constructor will invoke Base's constructor Base::Base(int i) instead of the default constructor.

Derived() : Base(5)
{      
}

If there's no such constructor invoked in the initialisation list of the derived class' constructor, then the program assumes a base class' constructor with no parameters. That's the reason why a constructor with no parameters (i.e. the default constructor) is invoked.

Getting error while sending email through Gmail SMTP - "Please log in via your web browser and then try again. 534-5.7.14"

I also came across this problem. Google detected my Mac as a new device and blocked it. To unblock, in a web browser log in to your Google account and go to "Account Settings".

Scroll down and you'll find "Recent activities". Click just below that on "Devices".

Your device will be listed. Okay your device. SMTP started working for me after I did this and lowered the protection as mentioned above.

Foreign keys in mongo?

You may be interested in using a ORM like Mongoid or MongoMapper.

http://mongoid.org/docs/relations/referenced/1-n.html

In a NoSQL database like MongoDB there are not 'tables' but collections. Documents are grouped inside Collections. You can have any kind of document – with any kind of data – in a single collection. Basically, in a NoSQL database it is up to you to decide how to organise the data and its relations, if there are any.

What Mongoid and MongoMapper do is to provide you with convenient methods to set up relations quite easily. Check out the link I gave you and ask any thing.

Edit:

In mongoid you will write your scheme like this:

class Student
  include Mongoid::Document

    field :name
    embeds_many :addresses
    embeds_many :scores    
end

class Address
  include Mongoid::Document

    field :address
    field :city
    field :state
    field :postalCode
    embedded_in :student
end

class Score
  include Mongoid::Document

    belongs_to :course
    field :grade, type: Float
    embedded_in :student
end


class Course
  include Mongoid::Document

  field :name
  has_many :scores  
end

Edit:

> db.foo.insert({group:"phones"})
> db.foo.find()                  
{ "_id" : ObjectId("4df6539ae90592692ccc9940"), "group" : "phones" }
{ "_id" : ObjectId("4df6540fe90592692ccc9941"), "group" : "phones" }
>db.foo.find({'_id':ObjectId("4df6539ae90592692ccc9940")}) 
{ "_id" : ObjectId("4df6539ae90592692ccc9940"), "group" : "phones" }

You can use that ObjectId in order to do relations between documents.

Merging two CSV files using Python

When I'm working with csv files, I often use the pandas library. It makes things like this very easy. For example:

import pandas as pd

a = pd.read_csv("filea.csv")
b = pd.read_csv("fileb.csv")
b = b.dropna(axis=1)
merged = a.merge(b, on='title')
merged.to_csv("output.csv", index=False)

Some explanation follows. First, we read in the csv files:

>>> a = pd.read_csv("filea.csv")
>>> b = pd.read_csv("fileb.csv")
>>> a
   title  stage    jan    feb
0   darn  3.001  0.421  0.532
1     ok  2.829  1.036  0.751
2  three  1.115  1.146  2.921
>>> b
   title    mar    apr    may       jun  Unnamed: 5
0   darn  0.631  1.321  0.951    1.7510         NaN
1     ok  1.001  0.247  2.456    0.3216         NaN
2  three  0.285  1.283  0.924  956.0000         NaN

and we see there's an extra column of data (note that the first line of fileb.csv -- title,mar,apr,may,jun, -- has an extra comma at the end). We can get rid of that easily enough:

>>> b = b.dropna(axis=1)
>>> b
   title    mar    apr    may       jun
0   darn  0.631  1.321  0.951    1.7510
1     ok  1.001  0.247  2.456    0.3216
2  three  0.285  1.283  0.924  956.0000

Now we can merge a and b on the title column:

>>> merged = a.merge(b, on='title')
>>> merged
   title  stage    jan    feb    mar    apr    may       jun
0   darn  3.001  0.421  0.532  0.631  1.321  0.951    1.7510
1     ok  2.829  1.036  0.751  1.001  0.247  2.456    0.3216
2  three  1.115  1.146  2.921  0.285  1.283  0.924  956.0000

and finally write this out:

>>> merged.to_csv("output.csv", index=False)

producing:

title,stage,jan,feb,mar,apr,may,jun
darn,3.001,0.421,0.532,0.631,1.321,0.951,1.751
ok,2.829,1.036,0.751,1.001,0.247,2.456,0.3216
three,1.115,1.146,2.921,0.285,1.283,0.924,956.0

Install php-zip on php 5.6 on Ubuntu

Try either

  • sudo apt-get install php-zip or
  • sudo apt-get install php5.6-zip

Then, you might have to restart your web server.

  • sudo service apache2 restart or
  • sudo service nginx restart

If you are installing on centos or fedora OS then use yum in place of apt-get. example:-

sudo yum install php-zip or sudo yum install php5.6-zip and sudo service httpd restart

Validating a Textbox field for only numeric input.

I have this extension which is kind of multi-purpose:

    public static bool IsNumeric(this object value)
    {
        if (value == null || value is DateTime)
        {
            return false;
        }

        if (value is Int16 || value is Int32 || value is Int64 || value is Decimal || value is Single || value is Double || value is Boolean)
        {
            return true;
        }

        try
        {
            if (value is string)
                Double.Parse(value as string);
            else
                Double.Parse(value.ToString());
            return true;
        }
        catch { }
        return false;
    }

It works for other data types. Should work fine for what you want to do.

Spring Boot java.lang.NoClassDefFoundError: javax/servlet/Filter

It's not good to change the scope of your application dependencies. Putting the dependency as compile, will provide the dependency also in your artifact that will be installed somewere. The best think to do is configure the RUN configuration of your sping boot application by specifying as stated in documentation :

"Include dependencies with 'Provided' scope" "Enable this option to add dependencies with the Provided scope to the runtime classpath."

enter image description here

json_encode(): Invalid UTF-8 sequence in argument

json_encode works only with UTF-8 data. You'll have to ensure that your data is in UTF-8. alternatively, you can use iconv() to convert your results to UTF-8 before feeding them to json_encode()

Detect if the app was launched/opened from a push notification

I'll start with a state chart that I created for my own use to visualize it more accurately and to consider all other states: https://docs.google.com/spreadsheets/d/e/2PACX-1vSdKOgo_F1TZwGJBAED4C_7cml0bEATqeL3P9UKpBwASlT6ZkU3iLdZnOZoevkMzOeng7gs31IFhD-L/pubhtml?gid=0&single=true

Using this chart, we can see what is actually required in order to develop a robust notification handling system that works in almost all possible use cases.

Complete solution ?

  • Store notification payload in didReceiveRemoteNotification
  • Clear stored notification in applicationWillEnterForeground and didFinishLaunchingWithOptions
  • To tackle cases where control Center/ Notification center pulled, you can use a flag willResignActiveCalled and set it to false initially, Set this to true in applicationWillResignActive method,
  • In didReceiveRemoteNotification method, save notifications(userInfo) only when willResignActiveCalled is false.
  • Reset willResignActiveCalled to false in applicationDidEnterBackground and applicationDidBecomeActive method.

Note: A Similar answer is suggested in comments on Eric's answer, however, the state sheet helps in finding all possible scenarios as I did in my app.

Please find the complete code below and comment below if any specific case is not handled:

AppDelegate

class AppDelegate: UIResponder, UIApplicationDelegate {
  private var willResignActiveCalled = false

  func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    NotificationUtils.shared.notification = nil
    return true
  }
  func applicationWillResignActive(_ application: UIApplication) {
    willResignActiveCalled = true
  }
  func applicationDidEnterBackground(_ application: UIApplication) {
    willResignActiveCalled = false
  }
  func applicationWillEnterForeground(_ application: UIApplication) {
    NotificationUtils.shared.notification = nil
  }
  func applicationDidBecomeActive(_ application: UIApplication) {
    willResignActiveCalled = false
    NotificationUtils.shared.performActionOnNotification()
  }
  func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
    if !willResignActiveCalled { // Check if app is in inactive by app switcher, control center, or notification center
      NotificationUtils.shared.handleNotification(userInfo: userInfo)
    }
  }
}

NotificationUtils : This is where you can write all your code to navigating to different parts of the application, handling Databases(CoreData/Realm) and do all other stuff that needs to be done when a notification is received.

   class NotificationUtils {
  static let shared = NotificationUtils()
  private init() {}

  var notification : [AnyHashable: Any]?

  func handleNotification(userInfo : [AnyHashable: Any]){
    if UIApplication.shared.applicationState == UIApplicationState.active {
      self.notification = userInfo //Save Payload
      //Show inApp Alert/Banner/Action etc
      // perform immediate action on notification
    }
    else if UIApplication.shared.applicationState == UIApplicationState.inactive{
      self.notification = userInfo
    }
    else if UIApplication.shared.applicationState == UIApplicationState.background{
      //Process notification in background,
      // Update badges, save some data received from notification payload in Databases (CoreData/Realm)
    }
  }

  func performActionOnNotification(){
    // Do all the stuffs like navigating to ViewControllers, updating Badges etc
    defer {
      notification = nil
    }
  }
}

Is there any boolean type in Oracle databases?

A common space-saving trick is storing boolean values as an Oracle CHAR, rather than NUMBER:

How to scale an Image in ImageView to keep the aspect ratio

Take a look at ImageView.ScaleType to control and understand the way resizing happens in an ImageView. When the image is resized (while maintaining its aspect ratio), chances are that either the image's height or width becomes smaller than ImageView's dimensions.

Is there a command to undo git init?

You can just delete .git. Typically:

rm -rf .git

Then, recreate as the right user.

How to remove Firefox's dotted outline on BUTTONS as well as links?

If you have a border on a button and want to hide the dotted outline in Firefox without removing the border (and hence it's extra width on the button) you can use:

.button::-moz-focus-inner {
    border-color: transparent;
}

Print an ArrayList with a for-each loop

import java.util.ArrayList;
import java.util.List;

class ArrLst{

    public static void main(String args[]){

        List l=new ArrayList();
        l.add(10);
        l.add(11);
        l.add(12);
        l.add(13);
        l.add(14);
        l.forEach((a)->System.out.println(a));
    }
}

SQL Server - calculate elapsed time between two datetime stamps in HH:MM:SS format

select convert(varchar, Max(Time) - Min(Time) , 108) from logTable where id=...

LaTeX: Prevent line break in a span of text

Define myurl command:


\def\myurl{\hfil\penalty 100 \hfilneg \hbox}

I don't want to cause line overflows, 
I'd just rather LaTeX insert linebreaks before 
\myurl{\tt http://stackoverflow.com/questions/1012799/} 
regions rather than inside them.

SSRS custom number format

am assuming that you want to know how to format numbers in SSRS

Just right click the TextBox on which you want to apply formatting, go to its expression.

suppose its expression is something like below

=Fields!myField.Value

then do this

=Format(Fields!myField.Value,"##.##") 

or

=Format(Fields!myFields.Value,"00.00")

difference between the two is that former one would make 4 as 4 and later one would make 4 as 04.00

this should give you an idea.

also: you might have to convert your field into a numerical one. i.e.

  =Format(CDbl(Fields!myFields.Value),"00.00")

so: 0 in format expression means, when no number is present, place a 0 there and # means when no number is present, leave it. Both of them works same when numbers are present ie. 45.6567 would be 45.65 for both of them:

UPDATE :

if you want to apply variable formatting on the same column based on row values i.e. you want myField to have no formatting when it has no decimal value but formatting with double precision when it has decimal then you can do it through logic. (though you should not be doing so)

Go to the appropriate textbox and go to its expression and do this:

=IIF((Fields!myField.Value - CInt(Fields!myField.Value)) > 0, 
    Format(Fields!myField.Value, "##.##"),Fields!myField.Value)

so basically you are using IIF(condition, true,false) operator of SSRS, ur condition is to check whether the number has decimal value, if it has, you apply the formatting and if no, you let it as it is.

this should give you an idea, how to handle variable formatting.

what does "error : a nonstatic member reference must be relative to a specific object" mean?

Only static functions are called with class name.

classname::Staicfunction();

Non static functions have to be called using objects.

classname obj;
obj.Somefunction();

This is exactly what your error means. Since your function is non static you have to use a object reference to invoke it.

The type or namespace cannot be found (are you missing a using directive or an assembly reference?)

If you have Login in a seperate folder within your project make sure that where you are using it you do:

using FootballLeagueSystem.[Whatever folder you are using]

calling javascript function on OnClientClick event of a Submit button

OnClientClick="SomeMethod()" event of that BUTTON, it return by default "true" so after that function it do postback

for solution use

//use this code in BUTTON  ==>   OnClientClick="return SomeMethod();"

//and your function like this
<script type="text/javascript">
  function SomeMethod(){
    // put your code here 
    return false;
  }
</script>

How can I autoformat/indent C code in vim?

Try the following keystrokes:

gg=G

Explanation: gg goes to the top of the file, = is a command to fix the indentation and G tells it to perform the operation to the end of the file.

Column "invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause"

You can use case in update and SWAP as many as you want

update Table SET column=(case when is_row_1 then value_2 else value_1 end) where rule_to_match_swap_columns

Nodejs - Redirect url

I used a switch statement, with the default as a 404:

var fs = require("fs");
var http = require("http");

function send404Response (response){
    response.writeHead(404, {"Content-Type": "text/html"});
    fs.createReadStream("./path/to/404.html").pipe(response);
}

function onRequest (request, response){
    switch (request.url){
        case "/page1":
            //statements
            break;
        case "/page2":
            //statements
            break;
        default:
        //if no 'match' is found
            send404Response(response);
            break;
    }
}

http.createServer(onRequest).listen(8080);

Convert text into number in MySQL query

You can use SUBSTRING and CONVERT:

SELECT stuff
FROM table
WHERE conditions
ORDER BY CONVERT(SUBSTRING(name_column, 6), SIGNED INTEGER);

Where name_column is the column with the "name-" values. The SUBSTRING removes everything up before the sixth character (i.e. the "name-" prefix) and then the CONVERT converts the left over to a real integer.

UPDATE: Given the changing circumstances in the comments (i.e. the prefix can be anything), you'll have to throw a LOCATE in the mix:

ORDER BY CONVERT(SUBSTRING(name_column, LOCATE('-', name_column) + 1), SIGNED INTEGER);

This of course assumes that the non-numeric prefix doesn't have any hyphens in it but the relevant comment says that:

name can be any sequence of letters

so that should be a safe assumption.

When is std::weak_ptr useful?

A good example would be a cache.

For recently accessed objects, you want to keep them in memory, so you hold a strong pointer to them. Periodically, you scan the cache and decide which objects have not been accessed recently. You don't need to keep those in memory, so you get rid of the strong pointer.

But what if that object is in use and some other code holds a strong pointer to it? If the cache gets rid of its only pointer to the object, it can never find it again. So the cache keeps a weak pointer to objects that it needs to find if they happen to stay in memory.

This is exactly what a weak pointer does -- it allows you to locate an object if it's still around, but doesn't keep it around if nothing else needs it.

Visual Studio 2013 error MS8020 Build tools v140 cannot be found

@bku_drytt's solution didn't do it for me.

I solved it by additionally changing every occurence of 14.0 to 12.0 and v140 to v120 manually in the .vcxproj files.

Then it compiled!

how to print json data in console.log

{"success":true,"input_data":{"quantity-row_122":"1","price-row_122":" 35.1 "}}

console.dir() will do what you need. It will give you a hierarchical structure of the data.

success:function(data){
     console.dir(data);
}

like so

> Object
  > input_data: Object
      price-row_122: " 35.1 "
      quantity-row_122: "1"
    success: true

I don't think you need console.log(JSON.stringify(data)).

To get the data you can do this without stringify:

console.log(data.success); // true
console.log(data.input_data['quantity-row_122']) // "1"
console.log(data.input_data['price-row_122']) // " 35.1 "

Note

The value from input_data Object will be typeof "1": String, but you can convert to number(Int or Float) using ParseInt or ParseFloat, like so:

 typeof parseFloat(data.input_data['price-row_122'], 10) // "number"
 parseFloat(data.input_data['price-row_122'], 10) // 35.1

Get all files and directories in specific path fast

There is a long history of the .NET file enumeration methods being slow. The issue is there is not an instantaneous way of enumerating large directory structures. Even the accepted answer here has its issues with GC allocations.

The best I've been able to do is wrapped up in my library and exposed as the FindFile (source) class in the CSharpTest.Net.IO namespace. This class can enumerate files and folders without unneeded GC allocations and string marshalling.

The usage is simple enough, and the RaiseOnAccessDenied property will skip the directories and files the user does not have access to:

    private static long SizeOf(string directory)
    {
        var fcounter = new CSharpTest.Net.IO.FindFile(directory, "*", true, true, true);
        fcounter.RaiseOnAccessDenied = false;

        long size = 0, total = 0;
        fcounter.FileFound +=
            (o, e) =>
            {
                if (!e.IsDirectory)
                {
                    Interlocked.Increment(ref total);
                    size += e.Length;
                }
            };

        Stopwatch sw = Stopwatch.StartNew();
        fcounter.Find();
        Console.WriteLine("Enumerated {0:n0} files totaling {1:n0} bytes in {2:n3} seconds.",
                          total, size, sw.Elapsed.TotalSeconds);
        return size;
    }

For my local C:\ drive this outputs the following:

Enumerated 810,046 files totaling 307,707,792,662 bytes in 232.876 seconds.

Your mileage may vary by drive speed, but this is the fastest method I've found of enumerating files in managed code. The event parameter is a mutating class of type FindFile.FileFoundEventArgs so be sure you do not keep a reference to it as it's values will change for each event raised.

Getting multiple values with scanf()

Yes.

int minx, miny, maxx,maxy;
do {
   printf("enter four integers: ");
} while (scanf("%d %d %d %d", &minx, &miny, &maxx, &maxy)!=4);

The loop is just to demonstrate that scanf returns the number of fields succesfully read (or EOF).

Setting cursor at the end of any text of a textbox

For Windows Forms you can control cursor position (and selection) with txtbox.SelectionStart and txtbox.SelectionLength properties. If you want to set caret to end try this:

txtbox.SelectionStart = txtbox.Text.Length;
txtbox.SelectionLength = 0;

For WPF see this question.

how to run or install a *.jar file in windows?

The UnsupportedClassVersionError means that you are probably using (installed) an older version of Java as used to create the JAR.
Go to java.sun.com page, download and install a newer JRE (Java Runtime Environment).
if you want/need to develop with Java, you will need the JDK which includes the JRE.

XAMPP Port 80 in use by "Unable to open process" with PID 4

Simply set Apache to listen on a different port. This can be done by clicking on the "Config" button on the same line as the "Apache" module, select the "httpd.conf" file in the dropdown, then change the "Listen 80" line to "Listen 8080". Save the file and close it.

Now it avoids Port 80 and uses Port 8080 instead without issue. The only additional thing you need to do is make sure to put localhost:8080 in the browser so the browser knows to look on Port 8080. Otherwise it defaults to Port 80 and won't find your local site.

Deny direct access to all .php files except index.php

Actually, I came here with the same question as the creator of the topic, but none of the solutions given were a complete answer to my problem. Why adding a code to ALL the files on your server when you could simply configure it once ? The closest one was Residuum's one, but still, he was excluding ALL files, when I wanted to exclude only php files that weren't named index.php.

So I came up with a .htaccess containing this :

<Files *.php>
    Order Deny,Allow
    Deny from all
    Allow from 127.0.0.1
</Files>

<Files index.php>
    Order Allow,Deny
    Allow from all
</Files>

(Remember, htaccess files are working recursively, so it suits perfectly the prerequisite of the question.)

And here we go. The only php files that will be accessible for an user will be the ones named index.php. But you can still acces to every image, css stylesheet, js script, etc.

check if array is empty (vba excel)

Above methods didn´t work for me. This did:

  Dim arrayIsNothing As Boolean

    On Error Resume Next
    arrayIsNothing = IsNumeric(UBound(YOUR_ARRAY)) And False
    If Err.Number <> 0 Then arrayIsNothing = True
    Err.Clear
    On Error GoTo 0

    'Now you can test:
    if arrayIsNothing then ...

WorksheetFunction.CountA - not working post upgrade to Office 2010

It may be obvious but, by stating the Range and not including which workbook or worksheet then it may be trying to CountA() on a different sheet entirely. I find to fully address these things saves a lot of headaches.

How to find all tables that have foreign keys that reference particular table.column and have values for those foreign keys?

This solution will not only display all relations but also the constraint name, which is required in some cases (e.g. drop constraint):

SELECT
    CONCAT(table_name, '.', column_name) AS 'foreign key',
    CONCAT(referenced_table_name, '.', referenced_column_name) AS 'references',
    constraint_name AS 'constraint name'
FROM
    information_schema.key_column_usage
WHERE
    referenced_table_name IS NOT NULL;

If you want to check tables in a specific database, add the following:

AND table_schema = 'database_name';

The relationship could not be changed because one or more of the foreign-key properties is non-nullable

I ran into this problem today and wanted to share my solution. In my case, the solution was to delete the Child items before getting the Parent from the database.

Previously I was doing it like in the code below. I will then get the same error listed in this question.

var Parent = GetParent(parentId);
var children = Parent.Children;
foreach (var c in children )
{
     Context.Children.Remove(c);
}
Context.SaveChanges();

What worked for me, is to get the children items first, using the parentId (foreign key) and then delete those items. Then I can get the Parent from the database and at that point, it should not have any children items anymore and I can add new children items.

var children = GetChildren(parentId);
foreach (var c in children )
{
     Context.Children.Remove(c);
}
Context.SaveChanges();

var Parent = GetParent(parentId);
Parent.Children = //assign new entities/items here

Show/hide forms using buttons and JavaScript

Would you want the same form with different parts, showing each part accordingly with a button?

Here an example with three steps, that is, three form parts, but it is expandable to any number of form parts. The HTML characters &laquo; and &raquo; just print respectively « and » which might be interesting for the previous and next button characters.

_x000D_
_x000D_
shows_form_part(1)_x000D_
_x000D_
/* this function shows form part [n] and hides the remaining form parts */_x000D_
function shows_form_part(n){_x000D_
  var i = 1, p = document.getElementById("form_part"+1);_x000D_
  while (p !== null){_x000D_
    if (i === n){_x000D_
      p.style.display = "";_x000D_
    }_x000D_
    else{_x000D_
      p.style.display = "none";_x000D_
    }_x000D_
    i++;_x000D_
    p = document.getElementById("form_part"+i);_x000D_
  }_x000D_
}_x000D_
_x000D_
/* this is called at the last step using info filled during the previous steps*/_x000D_
function calc_sum() {_x000D_
  var sum =_x000D_
    parseInt(document.getElementById("num1").value) +_x000D_
    parseInt(document.getElementById("num2").value) +_x000D_
    parseInt(document.getElementById("num3").value);_x000D_
_x000D_
  alert("The sum is: " + sum);_x000D_
}
_x000D_
<div id="form_part1">_x000D_
  Part 1<br>_x000D_
  <input type="number" value="1" id="num1"><br>_x000D_
  <button type="button" onclick="shows_form_part(2)">&raquo;</button>_x000D_
</div>_x000D_
_x000D_
<div id="form_part2">_x000D_
  Part 2<br>_x000D_
  <input type="number" value="2" id="num2"><br>_x000D_
  <button type="button" onclick="shows_form_part(1)">&laquo;</button>_x000D_
  <button type="button" onclick="shows_form_part(3)">&raquo;</button>_x000D_
</div>_x000D_
_x000D_
<div id="form_part3">_x000D_
  Part 3<br>_x000D_
  <input type="number" value="3" id="num3"><br>_x000D_
  <button type="button" onclick="shows_form_part(2)">&laquo;</button>_x000D_
  <button type="button" onclick="calc_sum()">Sum</button>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How do I remove an item from a stl vector with a certain value?

From c++20:

A non-member function introduced std::erase, which takes the vector and value to be removed as inputs.

ex:

std::vector<int> v = {90,80,70,60,50};
std::erase(v,50);

Attach the Source in Eclipse of a jar

Simply import the package of the required source class in your code from jar.

You can find jar's sub packages in

Eclipse -- YourProject --> Referenced libraries --> yourJars --> Packages --> Clases

Like-- I was troubling with the mysql connector jar issue "the source attachment does not contain the source" by giving the path of source folder it display this statement

The source attachment does not contain the source for the file StatementImpl.class

Then I just import the package of mysql connector jar which contain the required class:

import com.mysql.jdbc.*;

Then program is working fine.

SonarQube not picking up Unit Test Coverage

Jenkins does not show coverage results as it is a problem of version compatibilities between jenkins jacoco plugin and maven jacoco plugin. On my side I have fixed it by using a more recent version of maven jacoco plugin

<build>
   <pluginManagement>
     <plugins>
       <plugin>
         <groupId>org.jacoco</groupId>
         <artifactId>jacoco-maven-plugin</artifactId>
         <version>0.7.9</version>
       </plugin>
     <plugins>
   <pluginManagement>
<build>

How do I skip a header from CSV files in Spark?

You could load each file separately, filter them with file.zipWithIndex().filter(_._2 > 0) and then union all the file RDDs.

If the number of files is too large, the union could throw a StackOverflowExeption.

Android: how to parse URL String with spaces to URI object?

java.net.URLEncoder.encode(finalPartOfString, "utf-8");

This will URL-encode the string.

finalPartOfString is the part after the last slash - in your case, the name of the song, as it seems.

How does Tomcat find the HOME PAGE of my Web App?

In any web application, there will be a web.xml in the WEB-INF/ folder.

If you dont have one in your web app, as it seems to be the case in your folder structure, the default Tomcat web.xml is under TOMCAT_HOME/conf/web.xml

Either way, the relevant lines of the web.xml are

<welcome-file-list>
        <welcome-file>index.html</welcome-file>
        <welcome-file>index.htm</welcome-file>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>

so any file matching this pattern when found will be shown as the home page.

In Tomcat, a web.xml setting within your web app will override the default, if present.

Further Reading

How do I override the default home page loaded by Tomcat?

Should I use Vagrant or Docker for creating an isolated environment?

Disclaimer: I wrote Vagrant! But because I wrote Vagrant, I spend most of my time living in the DevOps world which includes software like Docker. I work with a lot of companies using Vagrant and many use Docker, and I see how the two interplay.

Before I talk too much, a direct answer: in your specific scenario (yourself working alone, working on Linux, using Docker in production), you can stick with Docker alone and simplify things. In many other scenarios (I discuss further), it isn't so easy.

It isn't correct to directly compare Vagrant to Docker. In some scenarios, they do overlap, and in the vast majority, they don't. Actually, the more apt comparison would be Vagrant versus something like Boot2Docker (minimal OS that can run Docker). Vagrant is a level above Docker in terms of abstractions, so it isn't a fair comparison in most cases.

Vagrant launches things to run apps/services for the purpose of development. This can be on VirtualBox, VMware. It can be remote like AWS, OpenStack. Within those, if you use containers, Vagrant doesn't care, and embraces that: it can automatically install, pull down, build, and run Docker containers, for example. With Vagrant 1.6, Vagrant has docker-based development environments, and supports using Docker with the same workflow as Vagrant across Linux, Mac, and Windows. Vagrant doesn't try to replace Docker here, it embraces Docker practices.

Docker specifically runs Docker containers. If you're comparing directly to Vagrant: it is specifically a more specific (can only run Docker containers), less flexible (requires Linux or Linux host somewhere) solution. Of course if you're talking about production or CI, there is no comparison to Vagrant! Vagrant doesn't live in these environments, and so Docker should be used.

If your organization runs only Docker containers for all their projects and only has developers running on Linux, then okay, Docker could definitely work for you!

Otherwise, I don't see a benefit to attempting to use Docker alone, since you lose a lot of what Vagrant has to offer, which have real business/productivity benefits:

  • Vagrant can launch VirtualBox, VMware, AWS, OpenStack, etc. machines. It doesn't matter what you need, Vagrant can launch it. If you are using Docker, Vagrant can install Docker on any of these so you can use them for that purpose.

  • Vagrant is a single workflow for all your projects. Or to put another way, it is just one thing people have to learn to run a project whether it is in a Docker container or not. If, for example, in the future, a competitor arises to compete directly with Docker, Vagrant will be able to run that too.

  • Vagrant works on Windows (back to XP), Mac (back to 10.5), and Linux (back to kernel 2.6). In all three cases, the workflow is the same. If you use Docker, Vagrant can launch a machine (VM or remote) that can run Docker on all three of these systems.

  • Vagrant knows how to configure some advanced or non-trivial things like networking and syncing folders. For example: Vagrant knows how to attach a static IP to a machine or forward ports, and the configuration is the same no matter what system you use (VirtualBox, VMware, etc.) For synced folders, Vagrant provides multiple mechanisms to get your local files over to the remote machine (VirtualBox shared folders, NFS, rsync, Samba [plugin], etc.). If you're using Docker, even Docker with a VM without Vagrant, you would have to manually do this or they would have to reinvent Vagrant in this case.

  • Vagrant 1.6 has first-class support for docker-based development environments. This will not launch a virtual machine on Linux, and will automatically launch a virtual machine on Mac and Windows. The end result is that working with Docker is uniform across all platforms, while Vagrant still handles the tedious details of things such as networking, synced folders, etc.

To address specific counter arguments that I've heard in favor of using Docker instead of Vagrant:

  • "It is less moving parts" - Yes, it can be, if you use Docker exclusively for every project. Even then, it is sacrificing flexibility for Docker lock-in. If you ever decide to not use Docker for any project, past, present, or future, then you'll have more moving parts. If you had used Vagrant, you have that one moving part that supports the rest.

  • "It is faster!" - Once you have the host that can run Linux containers, Docker is definitely faster at running a container than any virtual machine would be to launch. But launching a virtual machine (or remote machine) is a one-time cost. Over the course of the day, most Vagrant users never actually destroy their VM. It is a strange optimization for development environments. In production, where Docker really shines, I understand the need to quickly spin up/down containers.

I hope now its clear to see that it is very difficult, and I believe not correct, to compare Docker to Vagrant. For dev environments, Vagrant is more abstract, more general. Docker (and the various ways you can make it behave like Vagrant) is a specific use case of Vagrant, ignoring everything else Vagrant has to offer.

In conclusion: in highly specific use cases, Docker is certainly a possible replacement for Vagrant. In most use cases, it is not. Vagrant doesn't hinder your usage of Docker; it actually does what it can to make that experience smoother. If you find this isn't true, I'm happy to take suggestions to improve things, since a goal of Vagrant is to work equally well with any system.

Hope this clears things up!

Calling JMX MBean method from a shell script

Potentially its easiest to write this in Java

import javax.management.*;
import javax.management.remote.*;

public class JmxInvoke {

    public static void main(String... args) throws Exception {
        JMXConnectorFactory.connect(new JMXServiceURL(args[0]))
            .getMBeanServerConnection().invoke(new ObjectName(args[1]), args[2], new Object[]{}, new String[]{});    
    }

}

This would compile to a single .class and needs no dependencies in server or any complicated maven packaging.

call it with

javac JmxInvoke.java
java -cp . JmxInvoke [url] [beanName] [method]

Check if string begins with something?

You can use string.match() and a regular expression for this too:

if(pathname.match(/^\/sub\/1/)) { // you need to escape the slashes

string.match() will return an array of matching substrings if found, otherwise null.

How to make an Android Spinner with initial text "Select One"?

So this is my final example "all-in" for a button-spinner

In activity_my_form.xml

    <Button
        android:id="@+id/btnSpinnerPlanets"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:gravity="left|center_vertical"
        android:singleLine="true"
        android:text="@string/selectAPlanet"
        android:textSize="10sp"
        android:background="@android:drawable/btn_dropdown">
    </Button>

In strings.xml

<string name="selectAPlanet">Select planet&#8230;</string>

<string-array name="planets__entries">
    <item>The Sun with a name very long so long long long long longThe Sun with a name very long so long long long long longThe Sun with a name very long so long long long long long</item>
    <item>Mercury</item>
    <item>Venus</item>
    <item>Earth</item>
    <item>Mars</item>
    <item>Jupiter</item>
    <item>Saturn</item>
    <item>Uranus</item>
    <item>Neptune</item>
</string-array>

In MyFormActivity.java

public class MyFormActivity extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        ((Button) findViewById(R.id.btnSpinnerPlanets)).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                final String[] items = view.getResources().getStringArray(R.array.planets__entries);
                ArrayAdapter<String> adapter = new ArrayAdapter<String>(MyFormActivity.this, android.R.layout.simple_spinner_dropdown_item, items);
                new AlertDialog.Builder(MyFormActivity.this).setTitle("the prompt").setAdapter(adapter, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        ((Button) findViewById(R.id.btnSpinnerPlanets)).setText(items[which]);
                        dialog.dismiss();
                    }
                }).create().show();
            }
        });     

    }

}   

Finally I obtained a font size configurable no first item selectable button spinner!!! Thanks to HRJ

Search and get a line in Python

With regular expressions

import re
s="""
    qwertyuiop
    asdfghjkl

    zxcvbnm
    token qwerty

    asdfghjklñ
"""
>>> items=re.findall("token.*$",s,re.MULTILINE)
>>> for x in items:
...     print x
...
token qwerty

Git:nothing added to commit but untracked files present

In case someone cares just about the error nothing added to commit but untracked files present (use "git add" to track) and not about Please move or remove them before you can merge.. You might have a look at the answers on Git - Won't add files?

There you find at least 2 good candidates for the issue in question here: that you either are in a subfolder or in a parent folder, but not in the actual repo folder. If you are in the directory one level too high, this will definitely raise that message "nothing added to commit…", see my answer in the link for details. I do not know if the same message occurs when you are in a subfolder, but it is likely. That could fit to your explanations.

How to generate XML file dynamically using PHP?

Take a look at the Tiny But Strong templating system. It's generally used for templating HTML but there's an extension that works with XML files. I use this extensively for creating reports where I can have one code file and two template files - htm and xml - and the user can then choose whether to send a report to screen or spreadsheet.

Another advantage is you don't have to code the xml from scratch, in some cases I've been wanting to export very large complex spreadsheets, and instead of having to code all the export all that is required is to save an existing spreadsheet in xml and substitute in code tags where data output is required. It's a quick and a very efficient way to work.

How to make Bitmap compress without change the bitmap size?

I have done this way:

Get Compressed Bitmap from Singleton class:

ImageView imageView = (ImageView)findViewById(R.id.imageView);
Bitmap bitmap = ImageUtils.getInstant().getCompressedBitmap("Your_Image_Path_Here");
imageView.setImageBitmap(bitmap);

ImageUtils.java:

public class ImageUtils {

    public static ImageUtils mInstant;

    public static ImageUtils getInstant(){
        if(mInstant==null){
            mInstant = new ImageUtils();
        }
        return mInstant;
    }

    public  Bitmap getCompressedBitmap(String imagePath) {
        float maxHeight = 1920.0f;
        float maxWidth = 1080.0f;
        Bitmap scaledBitmap = null;
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        Bitmap bmp = BitmapFactory.decodeFile(imagePath, options);

        int actualHeight = options.outHeight;
        int actualWidth = options.outWidth;
        float imgRatio = (float) actualWidth / (float) actualHeight;
        float maxRatio = maxWidth / maxHeight;

        if (actualHeight > maxHeight || actualWidth > maxWidth) {
            if (imgRatio < maxRatio) {
                imgRatio = maxHeight / actualHeight;
                actualWidth = (int) (imgRatio * actualWidth);
                actualHeight = (int) maxHeight;
            } else if (imgRatio > maxRatio) {
                imgRatio = maxWidth / actualWidth;
                actualHeight = (int) (imgRatio * actualHeight);
                actualWidth = (int) maxWidth;
            } else {
                actualHeight = (int) maxHeight;
                actualWidth = (int) maxWidth;

            }
        }

        options.inSampleSize = calculateInSampleSize(options, actualWidth, actualHeight);
        options.inJustDecodeBounds = false;
        options.inDither = false;
        options.inPurgeable = true;
        options.inInputShareable = true;
        options.inTempStorage = new byte[16 * 1024];

        try {
            bmp = BitmapFactory.decodeFile(imagePath, options);
        } catch (OutOfMemoryError exception) {
            exception.printStackTrace();

        }
        try {
            scaledBitmap = Bitmap.createBitmap(actualWidth, actualHeight, Bitmap.Config.ARGB_8888);
        } catch (OutOfMemoryError exception) {
            exception.printStackTrace();
        }

        float ratioX = actualWidth / (float) options.outWidth;
        float ratioY = actualHeight / (float) options.outHeight;
        float middleX = actualWidth / 2.0f;
        float middleY = actualHeight / 2.0f;

        Matrix scaleMatrix = new Matrix();
        scaleMatrix.setScale(ratioX, ratioY, middleX, middleY);

        Canvas canvas = new Canvas(scaledBitmap);
        canvas.setMatrix(scaleMatrix);
        canvas.drawBitmap(bmp, middleX - bmp.getWidth() / 2, middleY - bmp.getHeight() / 2, new Paint(Paint.FILTER_BITMAP_FLAG));

        ExifInterface exif = null;
        try {
            exif = new ExifInterface(imagePath);
            int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, 0);
            Matrix matrix = new Matrix();
            if (orientation == 6) {
                matrix.postRotate(90);
            } else if (orientation == 3) {
                matrix.postRotate(180);
            } else if (orientation == 8) {
                matrix.postRotate(270);
            }
            scaledBitmap = Bitmap.createBitmap(scaledBitmap, 0, 0, scaledBitmap.getWidth(), scaledBitmap.getHeight(), matrix, true);
        } catch (IOException e) {
            e.printStackTrace();
        }
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        scaledBitmap.compress(Bitmap.CompressFormat.JPEG, 85, out);

        byte[] byteArray = out.toByteArray();

        Bitmap updatedBitmap = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);

        return updatedBitmap;
    }

    private int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
        final int height = options.outHeight;
        final int width = options.outWidth;
        int inSampleSize = 1;

        if (height > reqHeight || width > reqWidth) {
            final int heightRatio = Math.round((float) height / (float) reqHeight);
            final int widthRatio = Math.round((float) width / (float) reqWidth);
            inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
        }
        final float totalPixels = width * height;
        final float totalReqPixelsCap = reqWidth * reqHeight * 2;

        while (totalPixels / (inSampleSize * inSampleSize) > totalReqPixelsCap) {
            inSampleSize++;
        }
        return inSampleSize;
    }
}

Dimensions are same after compressing Bitmap.

How did I checked ?

Bitmap beforeBitmap = BitmapFactory.decodeFile("Your_Image_Path_Here");
Log.i("Before Compress Dimension", beforeBitmap.getWidth()+"-"+beforeBitmap.getHeight());

Bitmap afterBitmap = ImageUtils.getInstant().getCompressedBitmap("Your_Image_Path_Here");
Log.i("After Compress Dimension", afterBitmap.getWidth() + "-" + afterBitmap.getHeight());

Output:

Before Compress : Dimension: 1080-1452
After Compress : Dimension: 1080-1452

Hope this will help you.

Can I delete data from the iOS DeviceSupport directory?

More Suggestive answer supporting rmaddy's answer as our primary purpose is to delete unnecessary file and folder:

  1. Delete this folder after every few days interval. Most of the time, it occupy huge space!

      ~/Library/Developer/Xcode/DerivedData
    
  2. All your targets are kept in the archived form in Archives folder. Before you decide to delete contents of this folder, here is a warning - if you want to be able to debug deployed versions of your App, you shouldn’t delete the archives. Xcode will manage of archives and creates new file when new build is archived.

      ~/Library/Developer/Xcode/Archives
    
  3. iOS Device Support folder creates a subfolder with the device version as an identifier when you attach the device. Most of the time it’s just old stuff. Keep the latest version and rest of them can be deleted (if you don’t have an app that runs on 5.1.1, there’s no reason to keep the 5.1.1 directory/directories). If you really don't need these, delete. But we should keep a few although we test app from device mostly.

    ~/Library/Developer/Xcode/iOS DeviceSupport
    
  4. Core Simulator folder is familiar for many Xcode users. It’s simulator’s territory; that's where it stores app data. It’s obvious that you can toss the older version simulator folder/folders if you no longer support your apps for those versions. As it is user data, no big issue if you delete it completely but it’s safer to use ‘Reset Content and Settings’ option from the menu to delete all of your app data in a Simulator.

      ~/Library/Developer/CoreSimulator 
    

(Here's a handy shell command for step 5: xcrun simctl delete unavailable )

  1. Caches are always safe to delete since they will be recreated as necessary. This isn’t a directory; it’s a file of kind Xcode Project. Delete away!

    ~/Library/Caches/com.apple.dt.Xcode
    
  2. Additionally, Apple iOS device automatically syncs specific files and settings to your Mac every time they are connected to your Mac machine. To be on safe side, it’s wise to use Devices pane of iTunes preferences to delete older backups; you should be retaining your most recent back-ups off course.

     ~/Library/Application Support/MobileSync/Backup
    

Source: https://ajithrnayak.com/post/95441624221/xcode-users-can-free-up-space-on-your-mac

I got back about 40GB!

Find and replace string values in list

Beside list comprehension, you can try map

>>> map(lambda x: str.replace(x, "[br]", "<br/>"), words)
['how', 'much', 'is<br/>', 'the', 'fish<br/>', 'no', 'really']

Delete files older than 15 days using PowerShell

If you are having problems with the above examples on a Windows 10 box, try replacing .CreationTime with .LastwriteTime. This worked for me.

dir C:\locationOfFiles -ErrorAction SilentlyContinue | Where { ((Get-Date)-$_.LastWriteTime).days -gt 15 } | Remove-Item -Force

On localhost, how do I pick a free port number?

For the sake of snippet of what the guys have explained above:

import socket
from contextlib import closing

def find_free_port():
    with closing(socket.socket(socket.AF_INET, socket.SOCK_STREAM)) as s:
        s.bind(('', 0))
        s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        return s.getsockname()[1]

Can I call a base class's virtual function if I'm overriding it?

Yes,

class Bar : public Foo
{
    ...

    void printStuff()
    {
        Foo::printStuff();
    }
};

It is the same as super in Java, except it allows calling implementations from different bases when you have multiple inheritance.

class Foo {
public:
    virtual void foo() {
        ...
    }
};

class Baz {
public:
    virtual void foo() {
        ...
    }
};

class Bar : public Foo, public Baz {
public:
    virtual void foo() {
        // Choose one, or even call both if you need to.
        Foo::foo();
        Baz::foo();
    }
};

Is having an 'OR' in an INNER JOIN condition a bad idea?

This kind of JOIN is not optimizable to a HASH JOIN or a MERGE JOIN.

It can be expressed as a concatenation of two resultsets:

SELECT  *
FROM    maintable m
JOIN    othertable o
ON      o.parentId = m.id
UNION
SELECT  *
FROM    maintable m
JOIN    othertable o
ON      o.id = m.parentId

, each of them being an equijoin, however, SQL Server's optimizer is not smart enough to see it in the query you wrote (though they are logically equivalent).

Install IPA with iTunes 11

In iTunes 11 you can go to the view menu, and "Show Sidebar", this will give you the sidebar, that you can drag 'n drop to.

You'll drag 'n drop to the open area that will be near the bottom of the sidebar (I'm typically doing this with both an IPA and a provisioning profile). After you do that, there will be an apps menu that appears in the sidebar with your app in it. Click on that, and you'll see your application in the main view. You can then drag your application from there to your device. Below, please find a video (it's private, so you'll need the URL) that outlines the steps visually: http://youtube.com/watch?v=0ACq4CRpEJ8&feature=youtu.be

css3 transition animation on load?

I think I have found a sort of work around for the OP question - instead of a transition beginning 'on.load' of the page - I found that using an animation for an opacity fade in had the same effect, (I was looking for the same thing as OP).

So I wanted to have the body text fade in from white(same as site background) to black text colour on page load - and I've only been coding since Monday so I was looking for an 'on.load' style thing code, but don't know JS yet - so here is my code that worked well for me.

#main p {
  animation: fadein 2s;
}
@keyframes fadein {
  from { opacity: 0}
  to   { opacity: 1}
}

And for whatever reason, this doesn't work for .class only #id's(at least not on mine)

Hope this helps - as I know this site helps me a lot!

How do I remove leading whitespace in Python?

The function strip will remove whitespace from the beginning and end of a string.

my_str = "   text "
my_str = my_str.strip()

will set my_str to "text".

How do I write out a text file in C# with a code page other than UTF-8?

You can have something like this

 switch (EncodingFormat.Trim().ToLower())
    {
        case "utf-8":
            File.WriteAllBytes(fileName, ASCIIEncoding.Convert(ASCIIEncoding.ASCII, new UTF8Encoding(false), convertToCSV(result, fileName)));
            break;
        case "utf-8+bom":
            File.WriteAllBytes(fileName, ASCIIEncoding.Convert(ASCIIEncoding.ASCII, new UTF8Encoding(true), convertToCSV(result, fileName)));
            break;
        case "ISO-8859-1":
            File.WriteAllBytes(fileName, ASCIIEncoding.Convert(ASCIIEncoding.ASCII, Encoding.GetEncoding("iso-8859-1"), convertToCSV(result, fileName)));
            break;
        case ..............
    }

How do you convert a byte array to a hexadecimal string, and vice versa?

This is an answer to revision 4 of Tomalak's highly popular answer (and subsequent edits).

I'll make the case that this edit is wrong, and explain why it could be reverted. Along the way, you might learn a thing or two about some internals, and see yet another example of what premature optimization really is and how it can bite you.

tl;dr: Just use Convert.ToByte and String.Substring if you're in a hurry ("Original code" below), it's the best combination if you don't want to re-implement Convert.ToByte. Use something more advanced (see other answers) that doesn't use Convert.ToByte if you need performance. Do not use anything else other than String.Substring in combination with Convert.ToByte, unless someone has something interesting to say about this in the comments of this answer.

warning: This answer may become obsolete if a Convert.ToByte(char[], Int32) overload is implemented in the framework. This is unlikely to happen soon.

As a general rule, I don't much like to say "don't optimize prematurely", because nobody knows when "premature" is. The only thing you must consider when deciding whether to optimize or not is: "Do I have the time and resources to investigate optimization approaches properly?". If you don't, then it's too soon, wait until your project is more mature or until you need the performance (if there is a real need, then you will make the time). In the meantime, do the simplest thing that could possibly work instead.

Original code:

    public static byte[] HexadecimalStringToByteArray_Original(string input)
    {
        var outputLength = input.Length / 2;
        var output = new byte[outputLength];
        for (var i = 0; i < outputLength; i++)
            output[i] = Convert.ToByte(input.Substring(i * 2, 2), 16);
        return output;
    }

Revision 4:

    public static byte[] HexadecimalStringToByteArray_Rev4(string input)
    {
        var outputLength = input.Length / 2;
        var output = new byte[outputLength];
        using (var sr = new StringReader(input))
        {
            for (var i = 0; i < outputLength; i++)
                output[i] = Convert.ToByte(new string(new char[2] { (char)sr.Read(), (char)sr.Read() }), 16);
        }
        return output;
    }

The revision avoids String.Substring and uses a StringReader instead. The given reason is:

Edit: you can improve performance for long strings by using a single pass parser, like so:

Well, looking at the reference code for String.Substring, it's clearly "single-pass" already; and why shouldn't it be? It operates at byte-level, not on surrogate pairs.

It does allocate a new string however, but then you need to allocate one to pass to Convert.ToByte anyway. Furthermore, the solution provided in the revision allocates yet another object on every iteration (the two-char array); you can safely put that allocation outside the loop and reuse the array to avoid that.

    public static byte[] HexadecimalStringToByteArray(string input)
    {
        var outputLength = input.Length / 2;
        var output = new byte[outputLength];
        var numeral = new char[2];
        using (var sr = new StringReader(input))
        {
            for (var i = 0; i < outputLength; i++)
            {
                numeral[0] = (char)sr.Read();
                numeral[1] = (char)sr.Read();
                output[i] = Convert.ToByte(new string(numeral), 16);
            }
        }
        return output;
    }

Each hexadecimal numeral represents a single octet using two digits (symbols).

But then, why call StringReader.Read twice? Just call its second overload and ask it to read two characters in the two-char array at once; and reduce the amount of calls by two.

    public static byte[] HexadecimalStringToByteArray(string input)
    {
        var outputLength = input.Length / 2;
        var output = new byte[outputLength];
        var numeral = new char[2];
        using (var sr = new StringReader(input))
        {
            for (var i = 0; i < outputLength; i++)
            {
                var read = sr.Read(numeral, 0, 2);
                Debug.Assert(read == 2);
                output[i] = Convert.ToByte(new string(numeral), 16);
            }
        }
        return output;
    }

What you're left with is a string reader whose only added "value" is a parallel index (internal _pos) which you could have declared yourself (as j for example), a redundant length variable (internal _length), and a redundant reference to the input string (internal _s). In other words, it's useless.

If you wonder how Read "reads", just look at the code, all it does is call String.CopyTo on the input string. The rest is just book-keeping overhead to maintain values we don't need.

So, remove the string reader already, and call CopyTo yourself; it's simpler, clearer, and more efficient.

    public static byte[] HexadecimalStringToByteArray(string input)
    {
        var outputLength = input.Length / 2;
        var output = new byte[outputLength];
        var numeral = new char[2];
        for (int i = 0, j = 0; i < outputLength; i++, j += 2)
        {
            input.CopyTo(j, numeral, 0, 2);
            output[i] = Convert.ToByte(new string(numeral), 16);
        }
        return output;
    }

Do you really need a j index that increments in steps of two parallel to i? Of course not, just multiply i by two (which the compiler should be able to optimize to an addition).

    public static byte[] HexadecimalStringToByteArray_BestEffort(string input)
    {
        var outputLength = input.Length / 2;
        var output = new byte[outputLength];
        var numeral = new char[2];
        for (int i = 0; i < outputLength; i++)
        {
            input.CopyTo(i * 2, numeral, 0, 2);
            output[i] = Convert.ToByte(new string(numeral), 16);
        }
        return output;
    }

What does the solution look like now? Exactly like it was at the beginning, only instead of using String.Substring to allocate the string and copy the data to it, you're using an intermediary array to which you copy the hexadecimal numerals to, then allocate the string yourself and copy the data again from the array and into the string (when you pass it in the string constructor). The second copy might be optimized-out if the string is already in the intern pool, but then String.Substring will also be able to avoid it in these cases.

In fact, if you look at String.Substring again, you see that it uses some low-level internal knowledge of how strings are constructed to allocate the string faster than you could normally do it, and it inlines the same code used by CopyTo directly in there to avoid the call overhead.

String.Substring

  • Worst-case: One fast allocation, one fast copy.
  • Best-case: No allocation, no copy.

Manual method

  • Worst-case: Two normal allocations, one normal copy, one fast copy.
  • Best-case: One normal allocation, one normal copy.

Conclusion? If you want to use Convert.ToByte(String, Int32) (because you don't want to re-implement that functionality yourself), there doesn't seem to be a way to beat String.Substring; all you do is run in circles, re-inventing the wheel (only with sub-optimal materials).

Note that using Convert.ToByte and String.Substring is a perfectly valid choice if you don't need extreme performance. Remember: only opt for an alternative if you have the time and resources to investigate how it works properly.

If there was a Convert.ToByte(char[], Int32), things would be different of course (it would be possible to do what I described above and completely avoid String).

I suspect that people who report better performance by "avoiding String.Substring" also avoid Convert.ToByte(String, Int32), which you should really be doing if you need the performance anyway. Look at the countless other answers to discover all the different approaches to do that.

Disclaimer: I haven't decompiled the latest version of the framework to verify that the reference source is up-to-date, I assume it is.

Now, it all sounds good and logical, hopefully even obvious if you've managed to get so far. But is it true?

Intel(R) Core(TM) i7-3720QM CPU @ 2.60GHz
    Cores: 8
    Current Clock Speed: 2600
    Max Clock Speed: 2600
--------------------
Parsing hexadecimal string into an array of bytes
--------------------
HexadecimalStringToByteArray_Original: 7,777.09 average ticks (over 10000 runs), 1.2X
HexadecimalStringToByteArray_BestEffort: 8,550.82 average ticks (over 10000 runs), 1.1X
HexadecimalStringToByteArray_Rev4: 9,218.03 average ticks (over 10000 runs), 1.0X

Yes!

Props to Partridge for the bench framework, it's easy to hack. The input used is the following SHA-1 hash repeated 5000 times to make a 100,000 bytes long string.

209113288F93A9AB8E474EA78D899AFDBB874355

Have fun! (But optimize with moderation.)

Joining three tables using MySQL

Use ANSI syntax and it will be a lot more clear how you are joining the tables:

SELECT s.name as Student, c.name as Course 
FROM student s
    INNER JOIN bridge b ON s.id = b.sid
    INNER JOIN course c ON b.cid  = c.id 
ORDER BY s.name 

Escape curly brace '{' in String.Format

Use double braces {{ or }} so your code becomes:

sb.AppendLine(String.Format("public {0} {1} {{ get; private set; }}", 
prop.Type, prop.Name));

// For prop.Type of "Foo" and prop.Name of "Bar", the result would be:
// public Foo Bar { get; private set; }

Table cell widths - fixing width, wrapping/truncating long words

As long as you fix the width of the table itself and set the table-layout property, this is pretty simple :

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <style type="text/css">
        td { width: 30px; overflow: hidden; }
        table { width : 90px; table-layout: fixed; }
    </style>
</head>
<body>

    <table border="2">
        <tr>
            <td>word</td>
            <td>two words</td>
            <td>onereallylongword</td>

        </tr>
    </table>
</body>
</html>

I've tested this in IE6 and 7 and it seems to work fine.

to_string not declared in scope

This error, as correctly identified above, is due to the compiler not using c++11 or above standard. This answer is for Windows 10.

For c++11 and above standard support in codeblocks version 17:

  1. Click settings in the toolbar.

  2. A drop-down menu appears. Select compiler option.

  3. Choose Global Compiler Settings.

  4. In the toolbar in this new window in second section, choose compiler settings.

  5. Then choose compiler flags option in below toolbar.

  6. Unfold general tab. Check the C++ standard that you want your compiler to follow.

  7. Click OK.

For those who are trying to get C++11 support in Sublime text.

  1. Download mingw compiler version 7 or above. In versions below this, the default c++ standard used is c++98 whereas in versions higher than 7, the default standard used is c++11.

  2. Copy the folder in main C drive. It should not be inside any other folder in C drive.

  3. Rename the folder as MinGW. This name is case insensitive, so it should any variation of mingw and must not include any other characters in the name.

  4. Then go to environment variables and edit the path variable. Add this "C:\mingw\bin" and click OK.

  5. You can check the version of g++ in cmd by typing g++ -v.

  6. This should be sufficient to enable c++11 in sublime text.

If you want to take inputs and outputs as well from input files for competitive programming purposes, then follow this link.

Git Cherry-pick vs Merge Workflow

In my opinion cherry-picking should be reserved for rare situations where it is required, for example if you did some fix on directly on 'master' branch (trunk, main development branch) and then realized that it should be applied also to 'maint'. You should base workflow either on merge, or on rebase (or "git pull --rebase").

Please remember that cherry-picked or rebased commit is different from the point of view of Git (has different SHA-1 identifier) than the original, so it is different than the commit in remote repository. (Rebase can usually deal with this, as it checks patch id i.e. the changes, not a commit id).

Also in git you can merge many branches at once: so called octopus merge. Note that octopus merge has to succeed without conflicts. Nevertheless it might be useful.

HTH.

Saving data to a file in C#

Starting with the System.IO namespace (particularly the File or FileInfo objects) should get you started.

http://msdn.microsoft.com/en-us/library/system.io.file.aspx

http://msdn.microsoft.com/en-us/library/system.io.fileinfo.aspx

Passing properties by reference in C#

Properties cannot be passed by reference ? Make it a field then, and use the property to reference it publicly:

public class MyClass
{
    public class MyStuff
    {
        string foo { get; set; }
    }

    private ObservableCollection<MyStuff> _collection;

    public ObservableCollection<MyStuff> Items { get { return _collection; } }

    public MyClass()
    {
        _collection = new ObservableCollection<MyStuff>();
        this.LoadMyCollectionByRef<MyStuff>(ref _collection);
    }

    public void LoadMyCollectionByRef<T>(ref ObservableCollection<T> objects_collection)
    {
        // Load refered collection
    }
}

Storing WPF Image Resources

Full description how to use resources: WPF Application Resource, Content, and Data Files

And how to reference them, read "Pack URIs in WPF".

In short, there is even means to reference resources from referenced/referencing assemblies.

Java, looping through result set

Result Set are actually contains multiple rows of data, and use a cursor to point out current position. So in your case, rs4.getString(1) only get you the data in first column of first row. In order to change to next row, you need to call next()

a quick example

while (rs.next()) {
    String sid = rs.getString(1);
    String lid = rs.getString(2);
    // Do whatever you want to do with these 2 values
}

there are many useful method in ResultSet, you should take a look :)

Android SDK manager won't open

Been trying to get the SDK manager to run for a while now following various threads with similar problems I could find.

Another solution to consider is to move android SDK to a dir without spaces in its name.

For instance in my case it resided in:

e:\Program Files (x86)\Android\android-sdk\

and would fail. When moved to:

c:\android_sdk_sucks\

It worked.

How to enable back/left swipe gesture in UINavigationController after setting leftBarButtonItem?

For those who are still having trouble with this, try separating the two lines as below.

override func viewDidLoad() {
    self.navigationController!.interactivePopGestureRecognizer!.delegate = self
    ...

override func viewWillAppear(_ animated: Bool) {
    self.navigationController!.interactivePopGestureRecognizer!.isEnabled = true
    ...

Obviously, in my app,

interactivePopGestureRecognizer!.isEnabled

got reset to false before the view was shown for some reason.

Haversine Formula in Python (Bearing and Distance between two GPS points)

The bearing calculation is incorrect, you need to swap the inputs to atan2.

    bearing = atan2(sin(long2-long1)*cos(lat2), cos(lat1)*sin(lat2)-sin(lat1)*cos(lat2)*cos(long2-long1))
    bearing = degrees(bearing)
    bearing = (bearing + 360) % 360

This will give you the correct bearing.

header location not working in my php code

I had same application on my localhost and on a shared server. On my localhost the redirects worked fine while on this shared server didn't. I checked the phpinfo and I saw what caused this:

enter image description here

While on my localhost I had this:

enter image description here

So I asked the system admin to increase that value and after he did that, everything worked fine.

How to use workbook.saveas with automatic Overwrite

To split the difference of opinion

I prefer:

   xls.DisplayAlerts = False    
   wb.SaveAs fullFilePath, AccessMode:=xlExclusive, ConflictResolution:=xlLocalSessionChanges
   xls.DisplayAlerts = True

HttpContext.Current.Session is null when routing requests

I was missing a reference to System.web.mvc dll in the session adapter, and adding the same fixed the issue.

Hopefully it will help someone else going through same scenario.

Checking if a worksheet-based checkbox is checked

Is this what you are trying?

Sub Sample()
    Dim cb As Shape

    Set cb = ActiveSheet.Shapes("Check Box 1")

    If cb.OLEFormat.Object.Value = 1 Then
        MsgBox "Checkbox is Checked"
    Else
        MsgBox "Checkbox is not Checked"
    End If
End Sub

Replace Activesheet with the relevant sheetname. Also replace Check Box 1 with the relevant checkbox name.

Creating custom function in React component

With React Functional way

import React, { useEffect } from "react";
import ReactDOM from "react-dom";
import Button from "@material-ui/core/Button";

const App = () => {
  const saySomething = (something) => {
    console.log(something);
  };
  useEffect(() => {
    saySomething("from useEffect");
  });
  const handleClick = (e) => {
    saySomething("element clicked");
  };
  return (
    <Button variant="contained" color="primary" onClick={handleClick}>
      Hello World
    </Button>
  );
};

ReactDOM.render(<App />, document.querySelector("#app"));

https://codesandbox.io/s/currying-meadow-gm9g0

How to upload file to server with HTTP POST multipart/form-data?

Here's my final working code. My web service needed one file (POST parameter name was "file") & a string value (POST parameter name was "userid").

/// <summary>
/// Occurs when upload backup application bar button is clicked. Author : Farhan Ghumra
 /// </summary>
private async void btnUploadBackup_Click(object sender, EventArgs e)
{
    var dbFile = await ApplicationData.Current.LocalFolder.GetFileAsync(Util.DBNAME);
    var fileBytes = await GetBytesAsync(dbFile);
    var Params = new Dictionary<string, string> { { "userid", "9" } };
    UploadFilesToServer(new Uri(Util.UPLOAD_BACKUP), Params, Path.GetFileName(dbFile.Path), "application/octet-stream", fileBytes);
}

/// <summary>
/// Creates HTTP POST request & uploads database to server. Author : Farhan Ghumra
/// </summary>
private void UploadFilesToServer(Uri uri, Dictionary<string, string> data, string fileName, string fileContentType, byte[] fileData)
{
    string boundary = "----------" + DateTime.Now.Ticks.ToString("x");
    HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(uri);
    httpWebRequest.ContentType = "multipart/form-data; boundary=" + boundary;
    httpWebRequest.Method = "POST";
    httpWebRequest.BeginGetRequestStream((result) =>
    {
        try
        {
            HttpWebRequest request = (HttpWebRequest)result.AsyncState;
            using (Stream requestStream = request.EndGetRequestStream(result))
            {
                WriteMultipartForm(requestStream, boundary, data, fileName, fileContentType, fileData);
            }
            request.BeginGetResponse(a =>
            {
                try
                {
                    var response = request.EndGetResponse(a);
                    var responseStream = response.GetResponseStream();
                    using (var sr = new StreamReader(responseStream))
                    {
                        using (StreamReader streamReader = new StreamReader(response.GetResponseStream()))
                        {
                            string responseString = streamReader.ReadToEnd();
                            //responseString is depend upon your web service.
                            if (responseString == "Success")
                            {
                                MessageBox.Show("Backup stored successfully on server.");
                            }
                            else
                            {
                                MessageBox.Show("Error occurred while uploading backup on server.");
                            } 
                        }
                    }
                }
                catch (Exception)
                {

                }
            }, null);
        }
        catch (Exception)
        {

        }
    }, httpWebRequest);
}

/// <summary>
/// Writes multi part HTTP POST request. Author : Farhan Ghumra
/// </summary>
private void WriteMultipartForm(Stream s, string boundary, Dictionary<string, string> data, string fileName, string fileContentType, byte[] fileData)
{
    /// The first boundary
    byte[] boundarybytes = Encoding.UTF8.GetBytes("--" + boundary + "\r\n");
    /// the last boundary.
    byte[] trailer = Encoding.UTF8.GetBytes("\r\n--" + boundary + "--\r\n");
    /// the form data, properly formatted
    string formdataTemplate = "Content-Dis-data; name=\"{0}\"\r\n\r\n{1}";
    /// the form-data file upload, properly formatted
    string fileheaderTemplate = "Content-Dis-data; name=\"{0}\"; filename=\"{1}\";\r\nContent-Type: {2}\r\n\r\n";

    /// Added to track if we need a CRLF or not.
    bool bNeedsCRLF = false;

    if (data != null)
    {
        foreach (string key in data.Keys)
        {
            /// if we need to drop a CRLF, do that.
            if (bNeedsCRLF)
                WriteToStream(s, "\r\n");

            /// Write the boundary.
            WriteToStream(s, boundarybytes);

            /// Write the key.
            WriteToStream(s, string.Format(formdataTemplate, key, data[key]));
            bNeedsCRLF = true;
        }
    }

    /// If we don't have keys, we don't need a crlf.
    if (bNeedsCRLF)
        WriteToStream(s, "\r\n");

    WriteToStream(s, boundarybytes);
    WriteToStream(s, string.Format(fileheaderTemplate, "file", fileName, fileContentType));
    /// Write the file data to the stream.
    WriteToStream(s, fileData);
    WriteToStream(s, trailer);
}

/// <summary>
/// Writes string to stream. Author : Farhan Ghumra
/// </summary>
private void WriteToStream(Stream s, string txt)
{
    byte[] bytes = Encoding.UTF8.GetBytes(txt);
    s.Write(bytes, 0, bytes.Length);
}

/// <summary>
/// Writes byte array to stream. Author : Farhan Ghumra
/// </summary>
private void WriteToStream(Stream s, byte[] bytes)
{
    s.Write(bytes, 0, bytes.Length);
}

/// <summary>
/// Returns byte array from StorageFile. Author : Farhan Ghumra
/// </summary>
private async Task<byte[]> GetBytesAsync(StorageFile file)
{
    byte[] fileBytes = null;
    using (var stream = await file.OpenReadAsync())
    {
        fileBytes = new byte[stream.Size];
        using (var reader = new DataReader(stream))
        {
            await reader.LoadAsync((uint)stream.Size);
            reader.ReadBytes(fileBytes);
        }
    }

    return fileBytes;
}

I am very much thankful to Darin Rousseau for helping me.

Anaconda vs. miniconda

Per the original docs:

Choose Anaconda if you:

  • Are new to conda or Python
  • Like the convenience of having Python and over 1500 scientific packages automatically installed at once
  • Have the time and disk space (a few minutes and 3 GB), and/or
  • Don’t want to install each of the packages you want to use individually.

Choose Miniconda if you:

  • Do not mind installing each of the packages you want to use individually.
  • Do not have time or disk space to install over 1500 packages at once, and/or
  • Just want fast access to Python and the conda commands, and wish to sort out the other programs later.

I use Miniconda myself. Anaconda is bloated. Many of the packages are never used and could still be easily installed if and when needed.

Note that Conda is the package manager (e.g. conda list displays all installed packages in the environment), whereas Anaconda and Miniconda are distributions. A software distribution is a collection of packages, pre-built and pre-configured, that can be installed and used on a system. A package manager is a tool that automates the process of installing, updating, and removing packages.

Anaconda is a full distribution of the central software in the PyData ecosystem, and includes Python itself along with the binaries for several hundred third-party open-source projects. Miniconda is essentially an installer for an empty conda environment, containing only Conda, its dependencies, and Python. Source.

Once Conda is installed, you can then install whatever package you need from scratch along with any desired version of Python.

2-4.4.0.1 is the version number for your Anaconda installation package. Strangely, it is not listed in their Old Package Lists.

In April 2016, the Anaconda versioning jumped from 2.5 to 4.0 in order to avoid confusion with Python versions 2 & 3. Version 4.0 included the Anaconda Navigator.

Release notes for subsequent versions can be found here.

How to split string using delimiter char using T-SQL?

You simply need to do a SUBSTR on the string in col3....

    Select col1, col2, REPLACE(substr(col3, instr(col3, 'Client Name'), 
    (instr(col3, '|', instr(col3, 'Client Name')  -
    instr(col3, 'Client Name'))
    ),
'Client Name = ',
'')
    from Table01 

And yes, that is a bad DB design for the reasons stated in the original issue

How to install python developer package?

If you use yum search you can find the python dev package for your version of python.

For me I was using python 3.5. I ran the following

yum search python | grep devel

Which returned the following

enter image description here

I was then able to install the correct package for my version of python with the following cmd.

sudo yum install python35u-devel.x86_64

This works on centos for ubuntu or debian you would need to use apt-get

How to move the layout up when the soft keyboard is shown android

android:fitsSystemWindows="true"

add property on main layout of layout file and

android:windowSoftInputMode="adjustResize"

add line in your Manifest.xml file on your Activty

its perfect work for me.

How to call code behind server method from a client side JavaScript function?

I had to register my buttonid as a postbacktrigger...

RegisterPostbackTrigger(idOfButton)

Correct redirect URI for Google API and OAuth 2.0

There's no problem with using a localhost url for Dev work - obviously it needs to be changed when it comes to production.

You need to go here: https://developers.google.com/accounts/docs/OAuth2 and then follow the link for the API Console - link's in the Basic Steps section. When you've filled out the new application form you'll be asked to provide a redirect Url. Put in the page you want to go to once access has been granted.

When forming the Google oAuth Url - you need to include the redirect url - it has to be an exact match or you'll have problems. It also needs to be UrlEncoded.

Copy and paste content from one file to another file in vi

Use the variations of d like dd to cut.

To write a range of lines to another file you can use:

:<n>,<m> w filename

Where <n> and <m> are numbers (or symbols) that designate a range of lines.

For using the desktop clipboard, take a look at the +g commands.

How to get response body using HttpURLConnection, when code other than 2xx is returned?

If the response code isn't 200 or 2xx, use getErrorStream() instead of getInputStream().

Round number to nearest integer

For this purpose I would suggest just do the following thing -

int(round(x))

This will give you nearest integer.

Hope this helps!!

How to make PDF file downloadable in HTML link?

This is a common issue but few people know there's a simple HTML 5 solution:

<a href="./directory/yourfile.pdf" download="newfilename">Download the pdf</a>

Where newfilename is the suggested filename for the user to save the file. Or it will default to the filename on the serverside if you leave it empty, like this:

<a href="./directory/yourfile.pdf" download>Download the pdf</a>

Compatibility: I tested this on Firefox 21 and Iron, both worked fine. It might not work on HTML5-incompatible or outdated browsers. The only browser I tested that didn't force download is IE...

Check compatibility here: http://caniuse.com/#feat=download

How to print the current time in a Batch-File?

we can easily print the current time and date using echo and system variables as below.

echo %DATE% %TIME%

output example: 13-Sep-19 15:53:05.62

More than one file was found with OS independent path 'META-INF/LICENSE'

You can add this in yourProject/app/build.gradle inside android{}

android {      
      packagingOptions {
        exclude 'META-INF/DEPENDENCIES'
        exclude 'META-INF/LICENSE'
        exclude 'META-INF/LICENSE.txt'
        exclude 'META-INF/license.txt'
        exclude 'META-INF/NOTICE'
        exclude 'META-INF/NOTICE.txt'
        exclude 'META-INF/notice.txt'
        exclude 'META-INF/ASL2.0'
        exclude("META-INF/*.kotlin_module") 
      }          
}

maxReceivedMessageSize and maxBufferSize in app.config

You can do that in your app.config. like that:

maxReceivedMessageSize="2147483647" 

(The max value is Int32.MaxValue )

Or in Code:

WSHttpBinding binding = new WSHttpBinding();
binding.Name = "MyBinding";
binding.MaxReceivedMessageSize = Int32.MaxValue;

Note:

If your service is open to the Wide world, think about security when you increase this value.