Programs & Examples On #Wvvm

Relative paths in Python

Consider my code:

import os


def readFile(filename):
    filehandle = open(filename)
    print filehandle.read()
    filehandle.close()



fileDir = os.path.dirname(os.path.realpath('__file__'))
print fileDir

#For accessing the file in the same folder
filename = "same.txt"
readFile(filename)

#For accessing the file in a folder contained in the current folder
filename = os.path.join(fileDir, 'Folder1.1/same.txt')
readFile(filename)

#For accessing the file in the parent folder of the current folder
filename = os.path.join(fileDir, '../same.txt')
readFile(filename)

#For accessing the file inside a sibling folder.
filename = os.path.join(fileDir, '../Folder2/same.txt')
filename = os.path.abspath(os.path.realpath(filename))
print filename
readFile(filename)

how to configure apache server to talk to HTTPS backend server?

In my case, my server was configured to work only in https mode, and error occured when I try to access http mode. So changing http://my-service to https://my-service helped.

What's the effect of adding 'return false' to a click event listener?

I am surprised that no one mentioned onmousedown instead of onclick. The

onclick='return false'

does not catch the browser's default behaviour resulting in (sometimes unwanted) text selection occurring for mousedown but

onmousedown='return false'

does.

In other words, when I click on a button, its text sometimes becomes accidentally selected changing the look of the button, that may be unwanted. That is the default behaviour that we are trying to prevent here. However, the mousedown event is registered before click, so if you only prevent that behaviour inside your click handler, it will not affect the unwanted selection arising from the mousedown event. So the text still gets selected. However, preventing default for the mousedown event will do the job.

See also event.preventDefault() vs. return false

Check synchronously if file/directory exists in Node.js

updated asnwer for those people 'correctly' pointing out it doesnt directly answer the question, more bring an alternative option.

Sync solution:

fs.existsSync('filePath') also see docs here.

Returns true if the path exists, false otherwise.

Async Promise solution

In an async context you could just write the async version in sync method with using the await keyword. You can simply turn the async callback method into an promise like this:

function fileExists(path){
  return new Promise((resolve, fail) => fs.access(path, fs.constants.F_OK, 
    (err, result) => err ? fail(err) : resolve(result))
  //F_OK checks if file is visible, is default does no need to be specified.

}

async function doSomething() {
  var exists = await fileExists('filePath');
  if(exists){ 
    console.log('file exists');
  }
}

the docs on access().

Converting integer to digit list

>>>list(map(int, str(number)))  #number is a given integer

It returns a list of all digits of number.

Get keys of a Typescript interface as array of strings

Safe variants

Creating an array or tuple of keys from an interface with safety compile-time checks requires a bit of creativity. Types are erased at run-time and object types (unordered, named) cannot be converted to tuple types (ordered, unnamed) without resorting to non-supported techniques.

Comparison to other answers

The here proposed variants all consider/trigger a compile error in case of duplicate or missing tuple items given a reference object type like IMyTable. For example declaring an array type of (keyof IMyTable)[] cannot catch these errors.

In addition, they don't require a specific library (last variant uses ts-morph, which I would consider a generic compiler wrapper), emit a tuple type as opposed to an object (only first solution creates an array) or wide array type (compare to these answers) and lastly don't need classes.

Variant 1: Simple typed array

// Record type ensures, we have no double or missing keys, values can be neglected
function createKeys(keyRecord: Record<keyof IMyTable, any>): (keyof IMyTable)[] {
  return Object.keys(keyRecord) as any
}

const keys = createKeys({ isDeleted: 1, createdAt: 1, title: 1, id: 1 })
// const keys: ("id" | "title" | "createdAt" | "isDeleted")[]

+ easiest +- manual with auto-completion - array, no tuple

Playground

If you don't like creating a record, take a look at this alternative with Set and assertion types.


Variant 2: Tuple with helper function

function createKeys<T extends readonly (keyof IMyTable)[] | [keyof IMyTable]>(
    t: T & CheckMissing<T, IMyTable> & CheckDuplicate<T>): T {
    return t
}

+ tuple +- manual with auto-completion +- more advanced, complex types

Playground

Explanation

createKeys does compile-time checks by merging the function parameter type with additional assertion types, that emit an error for not suitable input. (keyof IMyTable)[] | [keyof IMyTable] is a "black magic" way to force inference of a tuple instead of an array from the callee side. Alternatively, you can use const assertions / as const from caller side.

CheckMissing checks, if T misses keys from U:

type CheckMissing<T extends readonly any[], U extends Record<string, any>> = {
    [K in keyof U]: K extends T[number] ? never : K
}[keyof U] extends never ? T : T & "Error: missing keys"

type T1 = CheckMissing<["p1"], {p1:any, p2:any}> //["p1"] & "Error: missing keys"
type T2 = CheckMissing<["p1", "p2"], { p1: any, p2: any }> // ["p1", "p2"]

Note: T & "Error: missing keys" is just for nice IDE errors. You could also write never. CheckDuplicates checks double tuple items:

type CheckDuplicate<T extends readonly any[]> = {
    [P1 in keyof T]: "_flag_" extends
    { [P2 in keyof T]: P2 extends P1 ? never :
        T[P2] extends T[P1] ? "_flag_" : never }[keyof T] ?
    [T[P1], "Error: duplicate"] : T[P1]
}

type T3 = CheckDuplicate<[1, 2, 3]> // [1, 2, 3]
type T4 = CheckDuplicate<[1, 2, 1]> 
// [[1, "Error: duplicate"], 2, [1, "Error: duplicate"]]

Note: More infos on unique item checks in tuples are in this post. With TS 4.1, we also can name missing keys in the error string - take a look at this Playground.


Variant 3: Recursive type

With version 4.1, TypeScript officially supports conditional recursive types, which can be potentially used here as well. Though, the type computation is expensive due to combinatory complexity - performance degrades massively for more than 5-6 items. I list this alternative for completeness (Playground):

type Prepend<T, U extends any[]> = [T, ...U] // TS 4.0 variadic tuples

type Keys<T extends Record<string, any>> = Keys_<T, []>
type Keys_<T extends Record<string, any>, U extends PropertyKey[]> =
  {
    [P in keyof T]: {} extends Omit<T, P> ? [P] : Prepend<P, Keys_<Omit<T, P>, U>>
  }[keyof T]

const t1: Keys<IMyTable> = ["createdAt", "isDeleted", "id", "title"] // ?

+ tuple +- manual with auto-completion + no helper function -- performance


Variant 4: Code generator / TS compiler API

ts-morph is chosen here, as it is a tad simpler wrapper alternative to the original TS compiler API. Of course, you can also use the compiler API directly. Let's look at the generator code:

// ./src/mybuildstep.ts
import {Project, VariableDeclarationKind, InterfaceDeclaration } from "ts-morph";

const project = new Project();
// source file with IMyTable interface
const sourceFile = project.addSourceFileAtPath("./src/IMyTable.ts"); 
// target file to write the keys string array to
const destFile = project.createSourceFile("./src/generated/IMyTable-keys.ts", "", {
  overwrite: true // overwrite if exists
}); 

function createKeys(node: InterfaceDeclaration) {
  const allKeys = node.getProperties().map(p => p.getName());
  destFile.addVariableStatement({
    declarationKind: VariableDeclarationKind.Const,
    declarations: [{
        name: "keys",
        initializer: writer =>
          writer.write(`${JSON.stringify(allKeys)} as const`)
    }]
  });
}

createKeys(sourceFile.getInterface("IMyTable")!);
destFile.saveSync(); // flush all changes and write to disk

After we compile and run this file with tsc && node dist/mybuildstep.js, a file ./src/generated/IMyTable-keys.ts with following content is generated:

// ./src/generated/IMyTable-keys.ts
const keys = ["id","title","createdAt","isDeleted"] as const;

+ auto-generating solution + scalable for multiple properties + no helper function + tuple - extra build-step - needs familiarity with compiler API

PHP Undefined Index

if you use isset like the answer posted already by singles, just make sure there is a bracket at the end like so:
$query_age = (isset($_GET['query_age']) ? $_GET['query_age'] : null);

How can I verify a Google authentication API access token?

you can verify a Google authentication access token by using this endpoint:

https://www.googleapis.com/oauth2/v3/tokeninfo?access_token=<access_token>

This is Google V3 OAuth AccessToken validating endpoint, you can refer from google document below: (In OAUTH 2.0 ENDPOINTS Tab)

https://developers.google.com/identity/protocols/OAuth2UserAgent#validate-access-token

CSS white space at bottom of page despite having both min-height and height tag

The problem is how 100% height is being calculated. Two ways to deal with this.

Add 20px to the body padding-bottom

body {
    padding-bottom: 20px;
}

or add a transparent border to body

body {
    border: 1px solid transparent;
}

Both worked for me in firebug

In defense of this answer

Below are some comments regarding the correctness of my answer to this question. These kinds of discussions are exactly why stackoverflow is so great. Many different people have different opinions on how best to solve the problem. I've learned some incredible coding style that I would not have thought of myself. And I've been told that readers have learned something from my style from time to time. Social coding has really encouraged me to be a better programmer.

Social coding can, at times, be disturbing. I hate it when I spend 30 minutes flushing out an answer with a jsfiddle and detailed explanation only to submit and find 10 other answers all saying the same thing in less detail. And the author accepts someone else's answer. How frustrating! I think that this has happend to my fellow contributors–in particular thirtydot.

Thirtydot's answer is completely legit. The p around the script is the culprit in this problem. Remove it and the space goes away. It also is a good answer to this question.

But why? Shouldn't the p tag's height, padding and margin be calculated into the height of the body?

And it is! If you remove the padding-bottom style that I've suggested and then set the body's background to black, you will see that the body's height includes this extra p space accurately (you see the strip at the bottom turn to black). But the gradient fails to include it when finding where to start. This is the real problem.

The two solutions that I've offered are ways to tell the browser to calculate the gradient properly. In fact, the padding-bottom could just be 1px. The value isn't important, but the setting is. It makes the browser take a look at where the body ends. Setting the border will have the same effect.

In my opinion, a padding setting of 20px looks the best for this page and that is why I answered it this way. It is addressing the problem of where the gradient starts.

Now, if I were building this page. I would have avoided wrapping the script in a p tag. But I must assume that author of the page either can't change it or has a good reason for putting it in there. I don't know what that script does. Will it write something that needs a p tag? Again, I would avoid this practice and it is fine to question its presence, but also I accept that there are cases where it must be there.

My hope in writing this "defense" is that the people who marked down this answer might consider that decision. My answer is thought out, purposeful, and relevant. The author thought so. However, in this social environment, I respect that you disagree and have a right to degrade my answer. I just hope that your choice is motivated by disagreement with my answer and not that author chose mine over yours.

Check if a class `active` exist on element with jquery

    if($('selector').hasClass('active')){ }

i think this will check if the selector hasClass active ...

Add tooltip to font awesome icon

The simplest solution I have found is to wrap your Font Awesome Icon in an <a></a> tag:

   <Tooltip title="Node.js" >
     <a>
        <FontAwesomeIcon icon={faNode} size="2x" />
     </a>
   </Tooltip>

Bash scripting, multiple conditions in while loop

The correct options are (in increasing order of recommendation):

# Single POSIX test command with -o operator (not recommended anymore).
# Quotes strongly recommended to guard against empty or undefined variables.
while [ "$stats" -gt 300 -o "$stats" -eq 0 ]

# Two POSIX test commands joined in a list with ||.
# Quotes strongly recommended to guard against empty or undefined variables.
while [ "$stats" -gt 300 ] || [ "$stats" -eq 0 ]

# Two bash conditional expressions joined in a list with ||.
while [[ $stats -gt 300 ]] || [[ $stats -eq 0 ]]

# A single bash conditional expression with the || operator.
while [[ $stats -gt 300 || $stats -eq 0 ]]

# Two bash arithmetic expressions joined in a list with ||.
# $ optional, as a string can only be interpreted as a variable
while (( stats > 300 )) || (( stats == 0 ))

# And finally, a single bash arithmetic expression with the || operator.
# $ optional, as a string can only be interpreted as a variable
while (( stats > 300 || stats == 0 ))

Some notes:

  1. Quoting the parameter expansions inside [[ ... ]] and ((...)) is optional; if the variable is not set, -gt and -eq will assume a value of 0.

  2. Using $ is optional inside (( ... )), but using it can help avoid unintentional errors. If stats isn't set, then (( stats > 300 )) will assume stats == 0, but (( $stats > 300 )) will produce a syntax error.

JavaScript window resize event

var EM = new events_managment();

EM.addEvent(window, 'resize', function(win,doc, event_){
    console.log('resized');
    //EM.removeEvent(win,doc, event_);
});

function events_managment(){
    this.events = {};
    this.addEvent = function(node, event_, func){
        if(node.addEventListener){
            if(event_ in this.events){
                node.addEventListener(event_, function(){
                    func(node, event_);
                    this.events[event_](win_doc, event_);
                }, true);
            }else{
                node.addEventListener(event_, function(){
                    func(node, event_);
                }, true);
            }
            this.events[event_] = func;
        }else if(node.attachEvent){

            var ie_event = 'on' + event_;
            if(ie_event in this.events){
                node.attachEvent(ie_event, function(){
                    func(node, ie_event);
                    this.events[ie_event]();
                });
            }else{
                node.attachEvent(ie_event, function(){
                    func(node, ie_event);
                });
            }
            this.events[ie_event] = func;
        }
    }
    this.removeEvent = function(node, event_){
        if(node.removeEventListener){
            node.removeEventListener(event_, this.events[event_], true);
            this.events[event_] = null;
            delete this.events[event_];
        }else if(node.detachEvent){
            node.detachEvent(event_, this.events[event_]);
            this.events[event_] = null;
            delete this.events[event_];
        }
    }
}

unix diff side-to-side results?

Try cdiff - View colored, incremental diff in workspace or from stdin with side by side and auto pager support.

Chart.js v2 - hiding grid lines

options: {
    scales: {
        xAxes: [{
            gridLines: {
                drawOnChartArea: false
            }
        }],
        yAxes: [{
            gridLines: {
                drawOnChartArea: false
            }
        }]
    }
}

Access restriction: Is not accessible due to restriction on required library ..\jre\lib\rt.jar

Not a true solution, but everywhere I looked the solution suggested was to simply tell Eclipse that those aren't errors. You can change it by going to Properties --> Java Compiler --> Errors Warnings --> Deprecated and restrited APIs --> Forbidden reference (acess rule), Change it from Error to Warning or Ignore.

Shared folder between MacOSX and Windows on Virtual Box

Edit

4+ years later after the original reply in 2015, virtualbox.org now offers an official user manual in both html and pdf formats, which effectively deprecates the previous version of this answer:

  • Step 3 (Guest Additions) mentioned in this response as well as several others, is discussed in great detail in manual sections 4.1 and 4.2
  • Step 1 (Shared Folders Setting in VirtualBox Manager) is discussed in section 4.3

Original Answer

Because there isn't an official answer yet and I literally just did this for my OS X/WinXP install, here's what I did:

  1. VirtualBox Manager: Open the Shared Folders setting and click the '+' icon to add a new folder. Then, populate the Folder Path (or use the drop-down to navigate) with the folder you want shared and make sure "Auto-Mount" and "Make Permanent" are checked.
  2. Boot Windows
  3. Once Windows is running, goto the Devices menu (at the top of the VirtualBox Manager window) and select "Insert Guest Additions CD Image...". Cycle through the prompts and once you finish installing, let it reboot.
  4. After Windows reboots, your new drive should show up as a Network Drive in Windows Explorer.

Hope that helps.

Best database field type for a URL

  1. Lowest common denominator max URL length among popular web browsers: 2,083 (Internet Explorer)
  1. http://dev.mysql.com/doc/refman/5.0/en/char.html
    Values in VARCHAR columns are variable-length strings. The length can be specified as a value from 0 to 255 before MySQL 5.0.3, and 0 to 65,535 in 5.0.3 and later versions. The effective maximum length of a VARCHAR in MySQL 5.0.3 and later is subject to the maximum row size (65,535 bytes, which is shared among all columns) and the character set used.
  1. So ...
    < MySQL 5.0.3 use TEXT
    or
    >= MySQL 5.0.3 use VARCHAR(2083)

Change the On/Off text of a toggle button Android

In some cases, you need to force refresh the view in order to make it work.

toggleButton.setTextOff(textOff);
toggleButton.requestLayout();

toggleButton.setTextOn(textOn);
toggleButton.requestLayout();

How to change UIButton image in Swift

in swift 3.0:

@IBOutlet weak var selectionButton: UIButton!

selectionButton.setImage(UIImage.addBlueIcon, for: .selected)

Assigning the return value of new by reference is deprecated

Nitin is correct - the issue is actually in the MDB2 code.

According to Replacement for PEAR: MDB2 on PHP 5.3 you can update to the SVN version of MDB2 for a version which is PHP5.3 compatible.

As that answer was given in March 2010, and http://pear.php.net/package/MDB2/ shows a release some months later, I expect the current version of MDB2 will solve the issue also.

iOS Simulator to test website on Mac

You can check and use their free trial browserstack , saucelabs or browser shots I know this is a very old question and I am answering too late and today there are many options available but may be someone get this usefull.

Why does configure say no C compiler found when GCC is installed?

I had the same issue with mind. I tried using sudo apt-get install build-essential It still won't work. I simply created a hardlink to the gcc-x binary in the /usr/bin/ folder. sudo ls /usr/bin/gcc-x /usr/bin/gcc

That worked for me!

What is the purpose of Android's <merge> tag in XML layouts?

Another reason to use merge is when using custom viewgroups in ListViews or GridViews. Instead of using the viewHolder pattern in a list adapter, you can use a custom view. The custom view would inflate an xml whose root is a merge tag. Code for adapter:

public class GridViewAdapter extends BaseAdapter {
     // ... typical Adapter class methods
     @Override
     public View getView(int position, View convertView, ViewGroup parent) {
        WallpaperView wallpaperView;
        if (convertView == null)
           wallpaperView = new WallpaperView(activity);
        else
            wallpaperView = (WallpaperView) convertView;

        wallpaperView.loadWallpaper(wallpapers.get(position), imageWidth);
        return wallpaperView;
    }
}

here is the custom viewgroup:

public class WallpaperView extends RelativeLayout {

    public WallpaperView(Context context) {
        super(context);
        init(context);
    }
    // ... typical constructors

    private void init(Context context) {
        View.inflate(context, R.layout.wallpaper_item, this);
        imageLoader = AppController.getInstance().getImageLoader();
        imagePlaceHolder = (ImageView) findViewById(R.id.imgLoader2);
        thumbnail = (NetworkImageView) findViewById(R.id.thumbnail2);
        thumbnail.setScaleType(ImageView.ScaleType.CENTER_CROP);
    }

    public void loadWallpaper(Wallpaper wallpaper, int imageWidth) {
        // ...some logic that sets the views
    }
}

and here is the XML:

<merge xmlns:android="http://schemas.android.com/apk/res/android">

    <ImageView
        android:id="@+id/imgLoader"
        android:layout_width="30dp"
        android:layout_height="30dp"
        android:layout_centerInParent="true"
        android:src="@drawable/ico_loader" />

    <com.android.volley.toolbox.NetworkImageView
        android:id="@+id/thumbnail"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</merge>

Cannot load 64-bit SWT libraries on 32-bit JVM ( replacing SWT file )

Eclipse is launching your application with whatever JRE you defined in your launch configuration. Since you're running the 32-bit Eclipse, you're running/debugging against its 32-bit SWT libraries, and you'll need to run a 32-bit JRE.

Your 64-bit JRE is, for whatever reason, your default Installed JRE.

To change this, first make sure you have a 32-bit JRE configured in the Installed JREs preference. Go to Window -> Preferences and navigate to Java -> Installed JREs:

Installed JREs

You can click Add and navigate to your 32-bit JVM's JAVA_HOME to add it.

Then in your Run Configuration, find your Eclipse Application and make sure the Runtime JRE is set to the 32-bit JRE you just configured:

Run Configuration

(Note the combobox that is poorly highlighted.)

Don't try replacing SWT jars, that will likely end poorly.

How do I do a case-insensitive string comparison?

This is another regex which I have learned to love/hate over the last week so usually import as (in this case yes) something that reflects how im feeling! make a normal function.... ask for input, then use ....something = re.compile(r'foo*|spam*', yes.I)...... re.I (yes.I below) is the same as IGNORECASE but you cant make as many mistakes writing it!

You then search your message using regex's but honestly that should be a few pages in its own , but the point is that foo or spam are piped together and case is ignored. Then if either are found then lost_n_found would display one of them. if neither then lost_n_found is equal to None. If its not equal to none return the user_input in lower case using "return lost_n_found.lower()"

This allows you to much more easily match up anything thats going to be case sensitive. Lastly (NCS) stands for "no one cares seriously...!" or not case sensitive....whichever

if anyone has any questions get me on this..

    import re as yes

    def bar_or_spam():

        message = raw_input("\nEnter FoO for BaR or SpaM for EgGs (NCS): ") 

        message_in_coconut = yes.compile(r'foo*|spam*',  yes.I)

        lost_n_found = message_in_coconut.search(message).group()

        if lost_n_found != None:
            return lost_n_found.lower()
        else:
            print ("Make tea not love")
            return

    whatz_for_breakfast = bar_or_spam()

    if whatz_for_breakfast == foo:
        print ("BaR")

    elif whatz_for_breakfast == spam:
        print ("EgGs")

React "after render" code?

For me, no combination of window.requestAnimationFrame or setTimeout produced consistent results. Sometimes it worked, but not always—or sometimes it would be too late.

I fixed it by looping window.requestAnimationFrame as many times as necessary.
(Typically 0 or 2-3 times)

The key is diff > 0: here we can ensure exactly when the page updates.

// Ensure new image was loaded before scrolling
if (oldH > 0 && images.length > prevState.images.length) {
    (function scroll() {
        const newH = ref.scrollHeight;
        const diff = newH - oldH;

        if (diff > 0) {
            const newPos = top + diff;
            window.scrollTo(0, newPos);
        } else {
            window.requestAnimationFrame(scroll);
        }
    }());
}

JQuery, select first row of table

Ok so if an image in a table is clicked you want the data of the first row of the table this image is in.

//image click stuff here {
$(this). // our image
closest('table'). // Go upwards through our parents untill we hit the table
children('tr:first'); // Select the first row we find

var $row = $(this).closest('table').children('tr:first');

parent() will only get the direct parent, closest should do what we want here. From jQuery docs: Get the first ancestor element that matches the selector, beginning at the current element and progressing up through the DOM tree.

Saving response from Requests to file

I believe all the existing answers contain the relevant information, but I would like to summarize.

The response object that is returned by requests get and post operations contains two useful attributes:

Response attributes

  • response.text - Contains str with the response text.
  • response.content - Contains bytes with the raw response content.

You should choose one or other of these attributes depending on the type of response you expect.

  • For text-based responses (html, json, yaml, etc) you would use response.text
  • For binary-based responses (jpg, png, zip, xls, etc) you would use response.content.

Writing response to file

When writing responses to file you need to use the open function with the appropriate file write mode.

  • For text responses you need to use "w" - plain write mode.
  • For binary responses you need to use "wb" - binary write mode.

Examples

Text request and save

# Request the HTML for this web page:
response = requests.get("https://stackoverflow.com/questions/31126596/saving-response-from-requests-to-file")
with open("response.txt", "w") as f:
    f.write(response.text)

Binary request and save

# Request the profile picture of the OP:
response = requests.get("https://i.stack.imgur.com/iysmF.jpg?s=32&g=1")
with open("response.jpg", "wb") as f:
    f.write(response.content)

Answering the original question

The original code should work by using wb and response.content:

import requests

files = {'f': ('1.pdf', open('1.pdf', 'rb'))}
response = requests.post("https://pdftables.com/api?&format=xlsx-single",files=files)
response.raise_for_status() # ensure we notice bad responses
file = open("out.xls", "wb")
file.write(response.content)
file.close()

But I would go further and use the with context manager for open.

import requests

with open('1.pdf', 'rb') as file:
    files = {'f': ('1.pdf', file)}
    response = requests.post("https://pdftables.com/api?&format=xlsx-single",files=files)

response.raise_for_status() # ensure we notice bad responses

with open("out.xls", "wb") as file:
    file.write(response.content)

Adding blank spaces to layout

This can by be achieved by using space or view.

Space is lightweight but not much flexible.

View occupies a rectangular area on the screen and is responsible for drawing and event handling. View is more customizable, you can add background, draw shapes like space.

Implementing Space :

(Eg: Space For 20 vertical and 10 horizontal density pixels)

<Space
  android:layout_width="10dp"
  android:layout_height="20dp"/>

Implementing View :

(Eg: View For 20 vertical and 10 horizontal density pixels including a background color)

  <View
       android:layout_width="10dp"
       android:layout_height="20dp"
       android:background="@color/bg_color"/>

Space for string formatting using HTML entity:

&#160; for non-breakable whitespace. &#032; for regular space.

Failed to load resource: the server responded with a status of 500 (Internal Server Error) in Bind function

The 500 code would normally indicate an error on the server, not anything with your code. Some thoughts

  • Talk to the server developer for more info. You can't get more info directly.
  • Verify your arguments into the call (values). Look for anything you might think could cause a problem for the server process. The process should not die and should return you a better code, but bugs happen there also.
  • Could be intermittent, like if the server database goes down. May be worth trying at another time.

Is it possible to access to google translate api for free?

Yes, you can use GT for free. See the post with explanation. And look at repo on GitHub.

UPD 19.03.2019 Here is a version for browser on GitHub.

UIAlertView first deprecated IOS 9

I tried the above methods, and no one can show the alert view, only when I put the presentViewController: method in a dispatch_async sentence:

dispatch_async(dispatch_get_main_queue(), ^ { [self presentViewController:alert animated:YES completion:nil]; });

Refer to Alternative to UIAlertView for iOS 9?.

How to get the previous URL in JavaScript?

If you are writing a web app or single page application (SPA) where routing takes place in the app/browser rather than a round-trip to the server, you can do the following:

window.history.pushState({ prevUrl: window.location.href }, null, "/new/path/in/your/app")

Then, in your new route, you can do the following to retrieve the previous URL:

window.history.state.prevUrl // your previous url

Copy entire directory contents to another directory?

FileUtils.copyDirectory()

Copies a whole directory to a new location preserving the file dates. This method copies the specified directory and all its child directories and files to the specified destination. The destination is the new location and name of the directory.

The destination directory is created if it does not exist. If the destination directory did exist, then this method merges the source with the destination, with the source taking precedence.

To do so, here's the example code

String source = "C:/your/source";
File srcDir = new File(source);

String destination = "C:/your/destination";
File destDir = new File(destination);

try {
    FileUtils.copyDirectory(srcDir, destDir);
} catch (IOException e) {
    e.printStackTrace();
}

How do I run a Python script on my web server?

Very simply, you can rename your Python script to "pythonscript.cgi". Post that in your cgi-bin directory, add the appropriate permissions and browse to it.

This is a great link you can start with.

Here's another good one.

Hope that helps.


EDIT (09/12/2015): The second link has long been removed. Replaced it with one that provides information referenced from the original.

Checking if a variable is an integer

I have had a similar issue before trying to determine if something is a string or any sort of number whatsoever. I have tried using a regular expression, but that is not reliable for my use case. Instead, you can check the variable's class to see if it is a descendant of the Numeric class.

if column.class < Numeric
  number_to_currency(column)
else
  column.html_safe
end

In this situation, you could also substitute for any of the Numeric descendants: BigDecimal, Date::Infinity, Integer, Fixnum, Float, Bignum, Rational, Complex

How to tag docker image with docker-compose

It seems the docs/tool have been updated and you can now add the image tag to your script. This was successful for me.

Example:

version: '2'
services:

  baggins.api.rest:
    image: my.image.name:rc2
    build:
      context: ../..
      dockerfile: app/Docker/Dockerfile.release
    ports:
      ...

https://docs.docker.com/compose/compose-file/#build

How does RewriteBase work in .htaccess

RewriteBase is only applied to the target of a relative rewrite rule.

  • Using RewriteBase like this...

    RewriteBase /folder/
    RewriteRule a\.html b.html
    
  • is essentially the same as...

    RewriteRule a\.html /folder/b.html
    
  • But when the .htaccess file is inside /folder/ then this also points to the same target:

    RewriteRule a\.html b.html
    

Although the docs imply always using a RewriteBase, Apache usually detects it correctly for paths under the DocumentRoot unless:

  • You are using Alias directives

  • You are using .htaccess rewrite rules to perform HTTP redirects (rather than just silent rewriting) to relative URLs

In these cases, you may find that you need to specify the RewriteBase.

However, since it's a confusing directive, it's generally better to simply specify absolute (aka 'root relative') URIs in your rewrite targets. Other developers reading your rules will grasp these more easily.



Quoting from Jon Lin's excellent in-depth answer here:

In an htaccess file, mod_rewrite works similar to a <Directory> or <Location> container. and the RewriteBase is used to provide a relative path base.

For example, say you have this folder structure:

DocumentRoot
|-- subdir1
`-- subdir2
    `-- subsubdir

So you can access:

  • http://example.com/ (root)
  • http://example.com/subdir1 (subdir1)
  • http://example.com/subdir2 (subdir2)
  • http://example.com/subdir2/subsubdir (subsubdir)

The URI that gets sent through a RewriteRule is relative to the directory containing the htaccess file. So if you have:

RewriteRule ^(.*)$ - 
  • In the root htaccess, and the request is /a/b/c/d, then the captured URI ($1) is a/b/c/d.
  • If the rule is in subdir2 and the request is /subdir2/e/f/g then the captured URI is e/f/g.
  • If the rule is in the subsubdir, and the request is /subdir2/subsubdir/x/y/z, then the captured URI is x/y/z.

The directory that the rule is in has that part stripped off of the URI. The rewrite base has no affect on this, this is simply how per-directory works.

What the rewrite base does do, is provide a URL-path base (not a file-path base) for any relative paths in the rule's target. So say you have this rule:

RewriteRule ^foo$ bar.php [L]

The bar.php is a relative path, as opposed to:

RewriteRule ^foo$ /bar.php [L]

where the /bar.php is an absolute path. The absolute path will always be the "root" (in the directory structure above). That means that regardless of whether the rule is in the "root", "subdir1", "subsubdir", etc. the /bar.php path always maps to http://example.com/bar.php.

But the other rule, with the relative path, it's based on the directory that the rule is in. So if

RewriteRule ^foo$ bar.php [L]

is in the "root" and you go to http://example.com/foo, you get served http://example.com/bar.php. But if that rule is in the "subdir1" directory, and you go to http://example.com/subdir1/foo, you get served http://example.com/subdir1/bar.php. etc. This sometimes works and sometimes doesn't, as the documentation says, it's supposed to be required for relative paths, but most of the time it seems to work. Except when you are redirecting (using the R flag, or implicitly because you have http://host in your rule's target). That means this rule:

RewriteRule ^foo$ bar.php [L,R]

if it's in the "subdir2" directory, and you go to http://example.com/subdir2/foo, mod_rewrite will mistake the relative path as a file-path instead of a URL-path and because of the R flag, you'll end up getting redirected to something like: http://example.com/var/www/localhost/htdocs/subdir1. Which is obviously not what you want.

This is where RewriteBase comes in. The directive tells mod_rewrite what to append to the beginning of every relative path. So if I have:

RewriteBase /blah/
RewriteRule ^foo$ bar.php [L]

in "subsubdir", going to http://example.com/subdir2/subsubdir/foo will actually serve me http://example.com/blah/bar.php. The "bar.php" is added to the end of the base. In practice, this example is usually not what you want, because you can't have multiple bases in the same directory container or htaccess file.

In most cases, it's used like this:

RewriteBase /subdir1/
RewriteRule ^foo$ bar.php [L]

where those rules would be in the "subdir1" directory and

RewriteBase /subdir2/subsubdir/
RewriteRule ^foo$ bar.php [L]

would be in the "subsubdir" directory.

This partly allows you to make your rules portable, so you can drop them in any directory and only need to change the base instead of a bunch of rules. For example if you had:

RewriteEngine On
RewriteRule ^foo$ /subdir1/bar.php [L]
RewriteRule ^blah1$ /subdir1/blah.php?id=1 [L]
RewriteRule ^blah2$ /subdir1/blah2.php [L]
...

such that going to http://example.com/subdir1/foo will serve http://example.com/subdir1/bar.php etc. And say you decided to move all of those files and rules to the "subsubdir" directory. Instead of changing every instance of /subdir1/ to /subdir2/subsubdir/, you could have just had a base:

RewriteEngine On
RewriteBase /subdir1/
RewriteRule ^foo$ bar.php [L]
RewriteRule ^blah1$ blah.php?id=1 [L]
RewriteRule ^blah2$ blah2.php [L]
...

And then when you needed to move those files and the rules to another directory, just change the base:

RewriteBase /subdir2/subsubdir/

and that's it.

Custom exception type

I often use an approach with prototypal inheritance. Overriding toString() gives you the advantage that tools like Firebug will log the actual information instead of [object Object] to the console for uncaught exceptions.

Use instanceof to determine the type of exception.

main.js

// just an exemplary namespace
var ns = ns || {};

// include JavaScript of the following
// source files here (e.g. by concatenation)

var someId = 42;
throw new ns.DuplicateIdException('Another item with ID ' +
    someId + ' has been created');
// Firebug console:
// uncaught exception: [Duplicate ID] Another item with ID 42 has been created

Exception.js

ns.Exception = function() {
}

/**
 * Form a string of relevant information.
 *
 * When providing this method, tools like Firebug show the returned 
 * string instead of [object Object] for uncaught exceptions.
 *
 * @return {String} information about the exception
 */
ns.Exception.prototype.toString = function() {
    var name = this.name || 'unknown';
    var message = this.message || 'no description';
    return '[' + name + '] ' + message;
};

DuplicateIdException.js

ns.DuplicateIdException = function(message) {
    this.name = 'Duplicate ID';
    this.message = message;
};

ns.DuplicateIdException.prototype = new ns.Exception();

Javascript to display the current date and time

Get the data you need and combine it in the String;

getDate(): Returns the date
getMonth(): Returns the month
getFullYear(): Returns the year
getHours();
getMinutes();

Check out : Working With Dates

Mount current directory as a volume in Docker on Windows 10

Command prompt (Cmd.exe)

When the Docker CLI is used from the Windows Cmd.exe, use %cd% to mount the current directory:

echo test > test.txt
docker run --rm -v %cd%:/data busybox ls -ls /data/test.txt

Git Bash (MinGW)

When the Docker CLI is used from the Git Bash (MinGW), mounting the current directory may fail due to a POSIX path conversion: Docker mounted volume adds ;C to end of windows path when translating from linux style path.

Escape the POSIX paths by prefixing with /

To skip the path conversion, POSIX paths have to be prefixed with the slash (/) to have leading double slash (//), including /$(pwd)

touch test.txt
docker run --rm -v /$(pwd):/data busybox ls -la //data/test.txt

Disable the path conversion

Disable the POSIX path conversion in Git Bash (MinGW) by setting MSYS_NO_PATHCONV=1 environment variable at the command level

touch test.txt
MSYS_NO_PATHCONV=1 docker run --rm -v $(pwd):/data busybox ls -la /data/test.txt

or shell (system) level

export MSYS_NO_PATHCONV=1
touch test.txt
docker run --rm -v $(pwd):/data busybox ls -la /data/test.txt

How to install "ifconfig" command in my ubuntu docker image?

sudo apt-get install iproute2 then run ip addr show

it works..

Return a 2d array from a function

Whatever changes you would make in function will persist.So there is no need to return anything.You can pass 2d array and change it whenever you will like.

  void MakeGridOfCounts(int Grid[][6])
    {
      cGrid[6][6] = {{0, }, {0, }, {0, }, {0, }, {0, }, {0, }};

    }

or

void MakeGridOfCounts(int Grid[][6],int answerArray[][6])
    {
     ....//do the changes in the array as you like they will reflect in main... 
    }

Mail not sending with PHPMailer over SSL using SMTP

First, Google created the "use less secure accounts method" function:

https://myaccount.google.com/security

Then created the another permission:

https://accounts.google.com/b/0/DisplayUnlockCaptcha

Hope it helps.

How to use HTTP_X_FORWARDED_FOR properly?

HTTP_CLIENT_IP is the most reliable way of getting the user's IP address. Next is HTTP_X_FORWARDED_FOR, followed by REMOTE_ADDR. Check all three, in that order, assuming that the first one that is set (isset($_SERVER['HTTP_CLIENT_IP']) returns true if that variable is set) is correct. You can independently check if the user is using a proxy using various methods. Check this out.

How can I remove the string "\n" from within a Ruby string?

use chomp or strip functions from Ruby:

"abcd\n".chomp => "abcd"
"abcd\n".strip => "abcd"

VHDL - How should I create a clock in a testbench?

How to use a clock and do assertions

This example shows how to generate a clock, and give inputs and assert outputs for every cycle. A simple counter is tested here.

The key idea is that the process blocks run in parallel, so the clock is generated in parallel with the inputs and assertions.

library ieee;
use ieee.std_logic_1164.all;

entity counter_tb is
end counter_tb;

architecture behav of counter_tb is
    constant width : natural := 2;
    constant clk_period : time := 1 ns;

    signal clk : std_logic := '0';
    signal data : std_logic_vector(width-1 downto 0);
    signal count : std_logic_vector(width-1 downto 0);

    type io_t is record
        load : std_logic;
        data : std_logic_vector(width-1 downto 0);
        count : std_logic_vector(width-1 downto 0);
    end record;
    type ios_t is array (natural range <>) of io_t;
    constant ios : ios_t := (
        ('1', "00", "00"),
        ('0', "UU", "01"),
        ('0', "UU", "10"),
        ('0', "UU", "11"),

        ('1', "10", "10"),
        ('0', "UU", "11"),
        ('0', "UU", "00"),
        ('0', "UU", "01")
    );
begin
    counter_0: entity work.counter port map (clk, load, data, count);

    process
    begin
        for i in ios'range loop
            load <= ios(i).load;
            data <= ios(i).data;
            wait until falling_edge(clk);
            assert count = ios(i).count;
        end loop;
        wait;
    end process;

    process
    begin
        for i in 1 to 2 * ios'length loop
            wait for clk_period / 2;
            clk <= not clk;
        end loop;
        wait;
    end process;
end behav;

The counter would look like this:

library ieee;
use ieee.std_logic_1164.all;
use ieee.numeric_std.all; -- unsigned

entity counter is
    generic (
        width : in natural := 2
    );
    port (
        clk, load : in std_logic;
        data : in std_logic_vector(width-1 downto 0);
        count : out std_logic_vector(width-1 downto 0)
    );
end entity counter;

architecture rtl of counter is
    signal cnt : unsigned(width-1 downto 0);
begin
    process(clk) is
    begin
        if rising_edge(clk) then
            if load = '1' then
                cnt <= unsigned(data);
            else
                cnt <= cnt + 1;
            end if;
        end if;
    end process;
    count <= std_logic_vector(cnt);
end architecture rtl;

Related: https://electronics.stackexchange.com/questions/148320/proper-clock-generation-for-vhdl-testbenches

JDK on OSX 10.7 Lion

You can download jdk6 here http://support.apple.com/kb/DL1573

Wish it helps

Transaction count after EXECUTE indicates a mismatching number of BEGIN and COMMIT statements. Previous count = 1, current count = 0

I encountered this error once after omitting this statement from my transaction.

COMMIT TRANSACTION [MyTransactionName]

How do I check in SQLite whether a table exists?

You could try:

SELECT name FROM sqlite_master WHERE name='table_name'

Is it possible to force Excel recognize UTF-8 CSV files automatically?

I have had the same issue in the past (how to produce files that Excel can read, and other tools can also read). I was using TSV rather than CSV, but the same problem with encodings came up.

I failed to find any way to get Excel to recognize UTF-8 automatically, and I was not willing/able to inflict on the consumers of the files complicated instructions how to open them. So I encoded them as UTF-16le (with a BOM) instead of UTF-8. Twice the size, but Excel can recognize the encoding. And they compress well, so the size rarely (but sadly not never) matters.

Formatting html email for Outlook

You should definitely check out the MSDN on what Outlook will support in regards to css and html. The link is here: http://msdn.microsoft.com/en-us/library/aa338201(v=office.12).aspx. If you do not have at least office 2007 you really need to upgrade as there are major differences between 2007 and previous editions. Also try saving the resulting email to file and examine it with firefox you will see what is being changed by outlook and possibly have a more specific question to ask. You can use Word to view the email as a sort of preview as well (but you won't get info on what styles are/are not being applied.

How do I put an image into my picturebox using ImageLocation?

if you provide a bad path or a broken link, if the compiler cannot find the image, the picture box would display an X icon on its body.

PictureBox picture = new PictureBox
        {
            Name = "pictureBox",
            Size = new Size(100, 50),
            Location = new Point(14, 17),
            Image = Image.FromFile(@"c:\Images\test.jpg"),
            SizeMode = PictureBoxSizeMode.CenterImage
        };
p.Controls.Add(picture);

OR

PictureBox picture = new PictureBox
        {
            Name = "pictureBox",
            Size = new Size(100, 50),
            Location = new Point(14, 17),
            ImageLocation = @"c:\Images\test.jpg",
            SizeMode = PictureBoxSizeMode.CenterImage
        };
p.Controls.Add(picture);

i'm not sure where you put images in your folder structure but you can find the path as bellow

 picture.ImageLocation = Path.Combine(System.Windows.Forms.Application.StartupPath, "Resources\Images\1.jpg");

How to log request and response body with Retrofit-Android?

I used setLogLevel(LogLevel.FULL).setLog(new AndroidLog("YOUR_LOG_TAG")), it helped me.
UPDATE.
You can also try for debug purpose use retrofit.client.Response as response model

Convert SVG image to PNG with PHP

I do not know of a standalone PHP / Apache solution, as this would require a PHP library that can read and render SVG images. I'm not sure such a library exists - I don't know any.

ImageMagick is able to rasterize SVG files, either through the command line or the PHP binding, IMagick, but seems to have a number of quirks and external dependencies as shown e.g. in this forum thread. I think it's still the most promising way to go, it's the first thing I would look into if I were you.

Spaces cause split in path with PowerShell

Can use the . dot operator.

. "C:\Users\user\AppData\Local\Programs\Microsoft VS Code\bin\code.cmd"

or the Start-Process command

Start-Process -PSPath "C:\Users\user\AppData\Local\Programs\Microsoft VS Code\bin\code.cmd"

or using ProcessStartInfo and Process

$ProcessInfo = New-Object -TypeName System.Diagnostics.ProcessStartInfo
$ProcessInfo.FileName = 'C:\WINDOWS\System32\WindowsPowerShell\v1.0\powershell.exe'
if($Admin){ $ProcessInfo.Verb = 'runas' }
$ProcessInfo.UseShellExecute = $false

$CommandParameters = '-noexit -noprofile -command Set-Location -LiteralPath c:\; $host.ui.RawUI.WindowTitle = ''[{0}] PS''; Set-PSReadlineOption -HistorySaveStyle SaveNothing;' -f $Cred.UserName
$ProcessInfo.Arguments = $CommandParameters
$ProcessInfo.Domain = ($Cred.UserName -split '\\')[0]
$ProcessInfo.UserName = ($Cred.UserName -split '\\')[1]
$ProcessInfo.Password = $Cred.Password

$ProcessObject = New-Object -TypeName System.Diagnostics.Process
$ProcessObject.StartInfo = $ProcessInfo
$ProcessObject.Start() | Out-Null

Maven build Compilation error : Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.1:compile (default-compile) on project Maven

If your local jdk version is 11 or 9, 10, and your project's java source/target version is 1.8, and you are using org.projectlombok:lombok package, then you can try to update its version to 1.16.22 or 1.18.12, like this:

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.16.22</version>
        </dependency>

It just solved my issue.

Java - Convert int to Byte Array of 4 Bytes?

int integer = 60;
byte[] bytes = new byte[4];
for (int i = 0; i < 4; i++) {
    bytes[i] = (byte)(integer >>> (i * 8));
}

Simple and clean way to convert JSON string to Object in Swift

It might be help someone. Similar example.

This is our Codable class to bind data. You can easily create this class using SwiftyJsonAccelerator

 class ModelPushNotificationFilesFile: Codable {

  enum CodingKeys: String, CodingKey {
    case url
    case id
    case fileExtension = "file_extension"
    case name
  }

  var url: String?
  var id: Int?
  var fileExtension: String?
  var name: String?

  init (url: String?, id: Int?, fileExtension: String?, name: String?) {
    self.url = url
    self.id = id
    self.fileExtension = fileExtension
    self.name = name
  }

  required init(from decoder: Decoder) throws {
    let container = try decoder.container(keyedBy: CodingKeys.self)
    url = try container.decodeIfPresent(String.self, forKey: .url)
    id = try container.decodeIfPresent(Int.self, forKey: .id)
    fileExtension = try container.decodeIfPresent(String.self, forKey: .fileExtension)
    name = try container.decodeIfPresent(String.self, forKey: .name)
  }

}

This is Json String

    let jsonString = "[{\"name\":\"\",\"file_extension\":\"\",\"id\":10684,\"url\":\"https:\\/\\/homepages.cae.wisc.edu\\/~ece533\\/images\\/tulips.png\"},

{\"name\":\"\",\"file_extension\":\"\",\"id\":10684,\"url\":\"https:\\/\\/homepages.cae.wisc.edu\\/~ece533\\/images\\/arctichare.png\"},

{\"name\":\"\",\"file_extension\":\"\",\"id\":10684,\"url\":\"https:\\/\\/homepages.cae.wisc.edu\\/~ece533\\/images\\/serrano.png\"},

{\"name\":\"\",\"file_extension\":\"\",\"id\":10684,\"url\":\"https:\\/\\/homepages.cae.wisc.edu\\/~ece533\\/images\\/peppers.png\"},

{\"name\":\"\",\"file_extension\":\"\",\"id\":10684,\"url\":\"https:\\/\\/homepages.cae.wisc.edu\\/~ece533\\/images\\/pool.png\"}]"

Here we convert to swift object.

   let jsonData = Data(jsonString.utf8)

        let decoder = JSONDecoder()

        do {
            let fileArray = try decoder.decode([ModelPushNotificationFilesFile].self, from: jsonData)
            print(fileArray)
            print(fileArray[0].url)
        } catch {
            print(error.localizedDescription)
        }

What causes a Python segmentation fault?

I understand you've solved your issue, but for others reading this thread, here is the answer: you have to increase the stack that your operating system allocates for the python process.

The way to do it, is operating system dependant. In linux, you can check with the command ulimit -s your current value and you can increase it with ulimit -s <new_value>

Try doubling the previous value and continue doubling if it does not work, until you find one that does or run out of memory.

How can I write data in YAML format in a file?

import yaml

data = dict(
    A = 'a',
    B = dict(
        C = 'c',
        D = 'd',
        E = 'e',
    )
)

with open('data.yml', 'w') as outfile:
    yaml.dump(data, outfile, default_flow_style=False)

The default_flow_style=False parameter is necessary to produce the format you want (flow style), otherwise for nested collections it produces block style:

A: a
B: {C: c, D: d, E: e}

Is it possible to program iPhone in C++

I use Objective-C to slap the UI together.
But the hard guts of the code is still written in C++.

That is the main purpose of Objective-C the UI interface and handling the events.
And it works great for that purpose.

I still like C++ as the backend for the code though (but that's mainly becuase I like C++) you could quite easily use Objective-C for the backend of the application as well.

Focusable EditText inside ListView

this post was matching exactly my keywords. I have a ListView header with a search EditText and a search Button.

In order to give focus to the EditText after loosing the initial focus the only HACK that i found is:

    searchText.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View arg0) {
            // LOTS OF HACKS TO MAKE THIS WORK.. UFF...
            searchButton.requestFocusFromTouch();
            searchText.requestFocus();
        }
    });

Lost lots of hours and it's not a real fix. Hope it helps someone tough.

ASP.NET MVC Global Variables

For non-static variables, I sorted it out via Application class dictionary as below:

At Global.asax.ac:

namespace MvcWebApplication 
{ 
    // Note: For instructions on enabling IIS6 or IIS7 classic mode, 
    // visit http://go.microsoft.com/?LinkId=9394801 

    public class MvcApplication : System.Web.HttpApplication 
    { 
        private string _licensefile; // the global private variable

        internal string LicenseFile // the global controlled variable
        { 
            get 
            { 
                if (String.IsNullOrEmpty(_licensefile)) 
                { 
                    string tempMylFile = Path.Combine(Path.GetDirectoryName(Assembly.GetAssembly(typeof(LDLL.License)).Location), "License.l"); 
                    if (!File.Exists(tempMylFile)) 
                        File.Copy(Server.MapPath("~/Content/license/License.l"), 
                            tempMylFile, 
                            true); 
                    _licensefile = tempMylFile; 
                } 
                return _licensefile; 
            } 
        }
        protected void Application_Start()
        {
            Application["LicenseFile"] = LicenseFile;// the global variable's bed

            AreaRegistration.RegisterAllAreas();

            RegisterGlobalFilters(GlobalFilters.Filters);
            RegisterRoutes(RouteTable.Routes);
        }
    }
}

And in Controller:

namespace MvcWebApplication.Controllers
{
    public class HomeController : Controller
    {
        //
        // GET: /Home/

        public ActionResult Index()
        {
            return View(HttpContext.Application["LicenseFile"] as string);
        }

    }
}

In this way we can have global variables in ASP.NET MVC :)

NOTE: If your object is not string simply write:

return View(HttpContext.Application["X"] as yourType);

How can I list all foreign keys referencing a given table in SQL Server?

First

EXEC sp_fkeys 'Table', 'Schema'

Then use NimbleText to play with your results

Execute PHP script in cron job

You may need to run the cron job as a user with permissions to execute the PHP script. Try executing the cron job as root, using the command runuser (man runuser). Or create a system crontable and run the PHP script as an authorized user, as @Philip described.

I provide a detailed answer how to use cron in this stackoverflow post.

How to write a cron that will run a script every day at midnight?

Select a date from date picker using Selenium webdriver

This code should work properly to get the current date from the calendar.

String today=getCurrentDay(); //function 
driver.findElement(By.xpath("here xpath of textbox")).click();
Thread.sleep(5000);
WebElement dateWidgetForm= driver.findElement(By.xpath("here xpath of calender"));
List<WebElement> columns = dateWidgetForm.findElements(By.tagName("td"));

    for (WebElement cell: columns) {
      String z=cell.getAttribute("class").toString();
      if(z.equalsIgnoreCase("day")){
      if (cell.getText().equals(today)) {
        cell.click();
        break;
      }
    }

private String getCurrentDay() {
 Calendar calendar = Calendar.getInstance(TimeZone.getDefault());
 //Get Current Day as a number
 int todayInt = calendar.get(Calendar.DAY_OF_MONTH);
 System.out.println("Today Int: " + todayInt +"\n");

 //Integer to String Conversion
 String todayStr = Integer.toString(todayInt);
 return todayStr;
}

How to convert integers to characters in C?

void main ()
 {
    int temp,integer,count=0,i,cnd=0;
    char ascii[10]={0};
    printf("enter a number");
    scanf("%d",&integer);
     if(integer>>31)
     {
     /*CONVERTING 2's complement value to normal value*/    
     integer=~integer+1;    
     for(temp=integer;temp!=0;temp/=10,count++);    
     ascii[0]=0x2D;
     count++;
     cnd=1;
     }
     else
     for(temp=integer;temp!=0;temp/=10,count++);    
     for(i=count-1,temp=integer;i>=cnd;i--)
     {

        ascii[i]=(temp%10)+0x30;
        temp/=10;
     }
    printf("\n count =%d ascii=%s ",count,ascii);

 }

How to handle AssertionError in Python and find out which line or statement it occurred on?

The traceback module and sys.exc_info are overkill for tracking down the source of an exception. That's all in the default traceback. So instead of calling exit(1) just re-raise:

try:
    assert "birthday cake" == "ice cream cake", "Should've asked for pie"
except AssertionError:
    print 'Houston, we have a problem.'
    raise

Which gives the following output that includes the offending statement and line number:

Houston, we have a problem.
Traceback (most recent call last):
  File "/tmp/poop.py", line 2, in <module>
    assert "birthday cake" == "ice cream cake", "Should've asked for pie"
AssertionError: Should've asked for pie

Similarly the logging module makes it easy to log a traceback for any exception (including those which are caught and never re-raised):

import logging

try:
    assert False == True 
except AssertionError:
    logging.error("Nothing is real but I can't quit...", exc_info=True)

How to download an entire directory and subdirectories using wget?

you can also use this command :

wget --mirror -pc --convert-links -P ./your-local-dir/ http://www.your-website.com

so that you get the exact mirror of the website you want to download

How to display loading message when an iFrame is loading?

I have followed the following approach

First, add sibling div

$('<div class="loading"></div>').insertBefore("#Iframe");

and then when the iframe completed loading

$("#Iframe").load(function(){
   $(this).siblings(".loading-fetching-content").remove(); 
  });

What is the use of the init() usage in JavaScript?

NB. Constructor function names should start with a capital letter to distinguish them from ordinary functions, e.g. MyClass instead of myClass.

Either you can call init from your constructor function:

var myObj = new MyClass(2, true);

function MyClass(v1, v2) 
{
    // ...

    // pub methods
    this.init = function() {
        // do some stuff        
    };

    // ...

    this.init(); // <------------ added this
}

Or more simply you could just copy the body of the init function to the end of the constructor function. No need to actually have an init function at all if it's only called once.

OpenCV with Network Cameras

OpenCV can be compiled with FFMPEG support. From ./configure --help:

--with-ffmpeg     use ffmpeg libraries (see LICENSE) [automatic]

You can then use cvCreateFileCapture_FFMPEG to create a CvCapture with e.g. the URL of the camera's MJPG stream.

I use this to grab frames from an AXIS camera:

CvCapture *capture = 
    cvCreateFileCapture_FFMPEG("http://axis-cam/mjpg/video.mjpg?resolution=640x480&req_fps=10&.mjpg");

How to solve time out in phpmyadmin?

If any of you happen to use WAMP then at least in the current version (3.0.6 x64) there's a file located in <your-wamp-dir>\alias\phpmyadmin.conf which overrides some of your php.ini options.

Edit this part:

# To import big file you can increase values php_admin_value upload_max_filesize 512M php_admin_value post_max_size 512M php_admin_value max_execution_time 600 php_admin_value max_input_time 600

AJAX POST and Plus Sign ( + ) -- How to Encode?

If you have to do a curl in php, you should use urlencode() from PHP but individually!

strPOST = "Item1=" . $Value1 . "&Item2=" . urlencode("+")

If you do urlencode(strPOST), you will bring you another problem, you will have one Item1 and & will be change %xx value and be as one value, see down here the return!

Example 1

$strPOST = "Item1=" . $Value1 . "&Item2=" . urlencode("+") will give Item1=Value1&Item2=%2B

Example 2

$strPOST = urlencode("Item1=" . $Value1 . "&Item2=+") will give Item1%3DValue1%26Item2%3D%2B

Example 1 is the good way to prepare string for POST in curl

Example 2 show that the receptor will not see the equal and the ampersand to distinguish both value!

How to get a unique computer identifier in Java (like disk ID or motherboard ID)?

I think you should look at this link ... you can make a mixed key using several identifiers such as mac+os+hostname+cpu id+motherboard serial number.

How do I convert an object to an array?

Simple version:

$arrayObject = new ArrayObject($object);
$array = $arrayObject->getArrayCopy();

Updated recursive version:

class RecursiveArrayObject extends ArrayObject
{
    function getArrayCopy()
    {
        $resultArray = parent::getArrayCopy();
        foreach($resultArray as $key => $val) {
            if (!is_object($val)) {
                continue;
            }
            $o = new RecursiveArrayObject($val);
            $resultArray[$key] = $o->getArrayCopy();
        }
        return $resultArray;
    }
}

$arrayObject = new RecursiveArrayObject($object);
$array = $arrayObject->getArrayCopy();

How to get the directory of the currently running file?

Sometimes this is enough, the first argument will always be the file path

package main

import (
    "fmt"
    "os"
)


func main() {
    fmt.Println(os.Args[0])

    // or
    dir, _ := os.Getwd()
    fmt.Println(dir)
}

Find Process Name by its Process ID

@ECHO OFF
SETLOCAL ENABLEDELAYEDEXPANSION
SET /a pid=1600
FOR /f "skip=3delims=" %%a IN ('tasklist') DO (
 SET "found=%%a"
 SET /a foundpid=!found:~26,8!
 IF %pid%==!foundpid! echo found %pid%=!found:~0,24%!
)

GOTO :EOF

...set PID to suit your circumstance.

How do I copy the contents of one ArrayList into another?

Copy of one list into second is quite simple , you can do that as below:-

ArrayList<List1> list1= new ArrayList<>();
ArrayList<List1> list2= new ArrayList<>();
//this will your copy your list1 into list2
list2.addAll(list1);

Bash script to check running process

A simple script version of one of Andor's above suggestions:

!/bin/bash

pgrep $1 && echo Running

If the above script is called test.sh then, in order to test, type: test.sh NameOfProcessToCheck

e.g. test.sh php

Cassandra port usage - how are the ports used?

I resolved issue using below steps :

  1. Stop cassandara services

    sudo su -
    systemctl stop datastax-agent
    systemctl stop opscenterd
    systemctl stop app-dse
    
  2. Take backup and Change port from 9042 to 9035

    cp /opt/dse/resources/cassandra/conf/cassandra.yaml /opt/dse/resources/cassandra/conf/bkp_cassandra.yaml
    Vi /opt/dse/resources/cassandra/conf/cassandra.yaml
    native_transport_port: 9035
    
  3. Start Cassandra services

    systemctl start datastax-agent
    systemctl start opscenterd
    systemctl start app-dse
    
  4. create cqlshrc file.

    vi  /root/.cassandra/cqlshrc
    
    [connection]
    hostname = 198.168.1.100
    port = 9035
    

Thanks, Mahesh

Spring expected at least 1 bean which qualifies as autowire candidate for this dependency

If there is an interface anywhere in the ThreadProvider hierarchy try putting the name of the Interface as the type of your service provider, eg. if you have say this structure:

public class ThreadProvider implements CustomInterface{
...
}

Then in your controller try this:

@Controller
public class ChiusuraController {

    @Autowired
    private CustomInterface chiusuraProvider;
}

The reason why this is happening is, in your first case when you DID NOT have ChiusuraProvider extend ThreadProvider Spring probably was underlying creating a CGLIB based proxy for you(to handle the @Transaction).

When you DID extend from ThreadProvider assuming that ThreadProvider extends some interface, Spring in that case creates a Java Dynamic Proxy based Proxy, which would appear to be an implementation of that interface instead of being of ChisuraProvider type.

If you absolutely need to use ChisuraProvider you can try AspectJ as an alternative or force CGLIB based proxy in the case with ThreadProvider also this way:

<aop:aspectj-autoproxy proxy-target-class="true"/>

Here is some more reference on this from the Spring Reference site: http://static.springsource.org/spring/docs/3.1.x/spring-framework-reference/html/classic-aop-spring.html#classic-aop-pfb

Open File Dialog, One Filter for Multiple Excel Extensions?

If you want to merge the filters (eg. CSV and Excel files), use this formula:

OpenFileDialog of = new OpenFileDialog();
of.Filter = "CSV files (*.csv)|*.csv|Excel Files|*.xls;*.xlsx";

Or if you want to see XML or PDF files in one time use this:

of.Filter = @" XML or PDF |*.xml;*.pdf";

Creating a JSON dynamically with each input value using jquery

same from above example - if you are just looking for json (not an array of object) just use

function getJsonDetails() {
      item = {}
      item ["token1"] = token1val;
      item ["token2"] = token1val;
      return item;
}
console.log(JSON.stringify(getJsonDetails()))

this output ll print as (a valid json)

{ 
   "token1":"samplevalue1",
   "token2":"samplevalue2"
}

What are Maven goals and phases and what is their difference?

The definitions are detailed at the Maven site's page Introduction to the Build Lifecycle, but I have tried to summarize:

Maven defines 4 items of a build process:

  1. Lifecycle

    Three built-in lifecycles (aka build lifecycles): default, clean, site. (Lifecycle Reference)

  2. Phase

    Each lifecycle is made up of phases, e.g. for the default lifecycle: compile, test, package, install, etc.

  3. Plugin

    An artifact that provides one or more goals.

    Based on packaging type (jar, war, etc.) plugins' goals are bound to phases by default. (Built-in Lifecycle Bindings)

  4. Goal

    The task (action) that is executed. A plugin can have one or more goals.

    One or more goals need to be specified when configuring a plugin in a POM. Additionally, in case a plugin does not have a default phase defined, the specified goal(s) can be bound to a phase.

Maven can be invoked with:

  1. a phase (e.g clean, package)
  2. <plugin-prefix>:<goal> (e.g. dependency:copy-dependencies)
  3. <plugin-group-id>:<plugin-artifact-id>[:<plugin-version>]:<goal> (e.g. org.apache.maven.plugins:maven-compiler-plugin:3.7.0:compile)

with one or more combinations of any or all, e.g.:

mvn clean dependency:copy-dependencies package

error: expected primary-expression before ')' token (C)

A function call needs to be performed with objects. You are doing the equivalent of this:

// function declaration/definition
void foo(int) {}

// function call
foo(int); // wat!??

i.e. passing a type where an object is required. This makes no sense in C or C++. You need to be doing

int i = 42;
foo(i);

or

foo(42);

Date in mmm yyyy format in postgresql

SELECT TO_CHAR(NOW(), 'Mon YYYY');

How to detect lowercase letters in Python?

import re
s = raw_input('Type a word: ')
slower=''.join(re.findall(r'[a-z]',s))
supper=''.join(re.findall(r'[A-Z]',s))
print slower, supper

Prints:

Type a word: A Title of a Book
itleofaook ATB

Or you can use a list comprehension / generator expression:

slower=''.join(c for c in s if c.islower())
supper=''.join(c for c in s if c.isupper())
print slower, supper

Prints:

Type a word: A Title of a Book
itleofaook ATB

appcompat-v7:21.0.0': No resource found that matches the given name: attr 'android:actionModeShareDrawable'

I was up to date with everything and still got this error, not sure why but I think the image was corrupted in a strange way and after replacing the image I got rid of the error. Might be worth to try with a different image :)

GitHub - List commits by author

If the author has a GitHub account, just click the author's username from anywhere in the commit history, and the commits you can see will be filtered down to those by that author:

Screenshot showing where to click to filter down commits

You can also click the 'n commits' link below their name on the repo's "contributors" page:

Another screenshot

Alternatively, you can directly append ?author=<theusername> or ?author=<emailaddress> to the URL. For example, https://github.com/jquery/jquery/commits/master?author=dmethvin or https://github.com/jquery/jquery/commits/[email protected] both give me:

Screenshot with only Dave Methvin's commits

For authors without a GitHub account, only filtering by email address will work, and you will need to manually add ?author=<emailaddress> to the URL - the author's name will not be clickable from the commits list.


You can also get the list of commits by a particular author from the command line using

git log --author=[your git name]

Example:

git log --author=Prem

Regular expression to remove HTML tags from a string

A trivial approach would be to replace

<[^>]*>

with nothing. But depending on how ill-structured your input is that may well fail.

How can I make a clickable link in an NSAttributedString?

if you want active substring in your UITextView then you can use my extended TextView... its short and simple. You can edit it as you want.

result: enter image description here

code: https://github.com/marekmand/ActiveSubstringTextView

How to check whether a given string is valid JSON in Java

I have found a very simple solution for it.

Please first install this library net.sf.json-lib for it.

    import net.sf.json.JSONException;

    import net.sf.json.JSONSerializer;

    private static boolean isValidJson(String jsonStr) {
        boolean isValid = false;
        try {
            JSONSerializer.toJSON(jsonStr);
            isValid = true;
        } catch (JSONException je) {
            isValid = false;
        }
        return isValid;
    }

    public static void testJson() {
        String vjson = "{\"employees\": [{ \"firstName\":\"John\" , \"lastName\":\"Doe\" },{ \"firstName\":\"Anna\" , \"lastName\":\"Smith\" },{ \"firstName\":\"Peter\" , \"lastName\":\"Jones\" }]}";
        String ivjson = "{\"employees\": [{ \"firstName\":\"John\" ,, \"lastName\":\"Doe\" },{ \"firstName\":\"Anna\" , \"lastName\":\"Smith\" },{ \"firstName\":\"Peter\" , \"lastName\":\"Jones\" }]}";
        System.out.println(""+isValidJson(vjson)); // true
        System.out.println(""+isValidJson(ivjson)); // false
    }

Done. Enjoy

Reading from file using read() function

fgets would work for you. here is very good documentation on this :-
http://www.cplusplus.com/reference/cstdio/fgets/

If you don't want to use fgets, following method will work for you :-

int readline(FILE *f, char *buffer, size_t len)
{
   char c; 
   int i;

   memset(buffer, 0, len);

   for (i = 0; i < len; i++)
   {   
      int c = fgetc(f); 

      if (!feof(f)) 
      {   
         if (c == '\r')
            buffer[i] = 0;
         else if (c == '\n')
         {   
            buffer[i] = 0;

            return i+1;
         }   
         else
            buffer[i] = c; 
      }   
      else
      {   
         //fprintf(stderr, "read_line(): recv returned %d\n", c);
         return -1; 
      }   
   }   

   return -1; 
}

AngularJS - Passing data between pages

What you should do is create a service to share data between controllers.

Nice tutorial https://www.youtube.com/watch?v=HXpHV5gWgyk

Call js-function using JQuery timer

setInterval is the function you want. That repeats every x miliseconds.

window.setInterval(function() {
    alert('test');
}, 10000);

Populate one dropdown based on selection in another

Could you please have a look at: http://jsfiddle.net/4Zw3M/1/.

Basically, the data is stored in an Array and the options are added accordingly. I think the code says more than a thousand words.

var data = [ // The data
    ['ten', [
        'eleven','twelve'
    ]],
    ['twenty', [
        'twentyone', 'twentytwo'
    ]]
];

$a = $('#a'); // The dropdowns
$b = $('#b');

for(var i = 0; i < data.length; i++) {
    var first = data[i][0];
    $a.append($("<option>"). // Add options
       attr("value",first).
       data("sel", i).
       text(first));
}

$a.change(function() {
    var index = $(this).children('option:selected').data('sel');
    var second = data[index][1]; // The second-choice data

    $b.html(''); // Clear existing options in second dropdown

    for(var j = 0; j < second.length; j++) {
        $b.append($("<option>"). // Add options
           attr("value",second[j]).
           data("sel", j).
           text(second[j]));
    }
}).change(); // Trigger once to add options at load of first choice

Android customized button; changing text color

Changing text color of button

Because this method is now deprecated

button.setTextColor(getResources().getColor(R.color.your_color));

I use the following:

button.setTextColor(ContextCompat.getColor(mContext, R.color.your_color));

Leave menu bar fixed on top when scrolled

This effect is typically achieved by having some jquery logic as follows:

$(window).bind('scroll', function () {
    if ($(window).scrollTop() > 50) {
        $('.menu').addClass('fixed');
    } else {
        $('.menu').removeClass('fixed');
    }
});

This says once the window has scrolled past a certain number of vertical pixels, it adds a class to the menu that changes it's position value to "fixed".

For complete implementation details see: http://jsfiddle.net/adamb/F4BmP/

Pass variables to Ruby script via command line

Something like this:

ARGV.each do|a|
  puts "Argument: #{a}"
end

then

$ ./test.rb "test1 test2"

or

v1 = ARGV[0]
v2 = ARGV[1]
puts v1       #prints test1
puts v2       #prints test2

Getting the thread ID from a thread

System.Threading.Thread.CurrentThread.Name

System.Threading.Thread.CurrentThread.ManagedThreadId

bash string equality

There's no difference, == is a synonym for = (for the C/C++ people, I assume). See here, for example.

You could double-check just to be really sure or just for your interest by looking at the bash source code, should be somewhere in the parsing code there, but I couldn't find it straightaway.

Can the Twitter Bootstrap Carousel plugin fade in and out on slide transition

Yes. Bootstrap uses CSS transitions so it can be done easily without any Javascript. Just use CSS3. Please take a look at

carousel.carousel-fade

in the CSS of the following examples:

How do I kill the process currently using a port on localhost in Windows?

In case you want to do it using Python: check Is it possible in python to kill process that is listening on specific port, for example 8080?

The answer from Smunk works nicely. I repeat his code here:

from psutil import process_iter
from signal import SIGTERM # or SIGKILL

for proc in process_iter():
    for conns in proc.connections(kind='inet'):
        if conns.laddr.port == 8080:
            proc.send_signal(SIGTERM) # or SIGKILL
            continue

Hide div after a few seconds

This will hide the div after 1 second (1000 milliseconds).

_x000D_
_x000D_
setTimeout(function() {_x000D_
    $('#mydiv').fadeOut('fast');_x000D_
}, 1000); // <-- time in milliseconds
_x000D_
#mydiv{_x000D_
    width: 100px;_x000D_
    height: 100px;_x000D_
    background: #000;_x000D_
    color: #fff;_x000D_
    text-align: center;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div id="mydiv">myDiv</div>
_x000D_
_x000D_
_x000D_

If you just want to hide without fading, use hide().

"Cannot update paths and switch to branch at the same time"

It causes by that your local branch doesn't track remote branch. As ssasi said,you need use these commands:

git remote update
git fetch
git checkout -b branch_nameA origin/branch_nameB

I solved my problem just now....

The page cannot be displayed because an internal server error has occurred on server

I've fixed it. I had the following section in web.config :

httpErrors existingResponse="PassThrough"

When I remove it, I got a real error

How to make CREATE OR REPLACE VIEW work in SQL Server?

Here is another method, where you don't have to duplicate the contents of the view:

IF (NOT EXISTS (SELECT 1 FROM sys.views WHERE name = 'data_VVV'))
BEGIN
    EXECUTE('CREATE VIEW data_VVVV as SELECT 1 as t');
END;

GO

ALTER VIEW data_VVVV AS 
    SELECT VCV.xxxx, VCV.yyyy AS yyyy, VCV.zzzz AS zzzz FROM TABLE_A ;

The first checks for the existence of the view (there are other ways to do this). If it doesn't exist, then create it with something simple and dumb. If it does, then just move on to the alter view statement.

C# switch statement limitations - why?

This is my original post, which sparked some debate... because it is wrong:

The switch statement is not the same thing as a big if-else statement. Each case must be unique and evaluated statically. The switch statement does a constant time branch regardless of how many cases you have. The if-else statement evaluates each condition until it finds one that is true.


In fact, the C# switch statement is not always a constant time branch.

In some cases the compiler will use a CIL switch statement which is indeed a constant time branch using a jump table. However, in sparse cases as pointed out by Ivan Hamilton the compiler may generate something else entirely.

This is actually quite easy to verify by writing various C# switch statements, some sparse, some dense, and looking at the resulting CIL with the ildasm.exe tool.

How to make bootstrap 3 fluid layout without horizontal scrollbar

I ran in to the same problem (wanting a fluid layout) but wanted to keep the responsive options with rearranging columns and so on for smaller screens and ended up with a small change to in variables.less:

// Large screen / wide desktop  (last row of file)
@container-lg-desktop:        100%; //((1140px + @grid-gutter-width));

This value is used once in grid.less and sets

@media (min-width: @screen-lg-desktop) {
  .container {
    max-width: @container-lg-desktop;
  }
  ....
}

The result is that over 1200px the grid is fluid (without horizontal scrollbars). Below that the normal responsive rules apply. You can of course set this to other media queries as well just as easily.

If you do not want to edit and compile .less yourself you could override the maxwidth in your own style sheet similair to below:

@media (min-width: 1200px) {  /* or min-width: wherever-you-want-your-fluid-breakpoint */
  body .container {
    max-width: 100%;
  }
}

All this assumes you use the normal Bootstrap grid syntax, including container, like below:

<div class="container">
  <div class="row" >
    <div class="col-md-6">.col-md-6</div>
    <div class="col-md-6">.col-md-6</div>
  </div>
</div>

Hope this helps!

Create SQL identity as primary key?

Simple change to syntax is all that is needed:

 create table ImagenesUsuario (
   idImagen int not null identity(1,1) primary key
 )

By explicitly using the "constraint" keyword, you can give the primary key constraint a particular name rather than depending on SQL Server to auto-assign a name:

 create table ImagenesUsuario (
   idImagen int not null identity(1,1) constraint pk_ImagenesUsario primary key
 )

Add the "CLUSTERED" keyword if that makes the most sense based on your use of the table (i.e., the balance of searches for a particular idImagen and amount of writing outweighs the benefits of clustering the table by some other index).

How to delete a file via PHP?

You can delete the file using

unlink($Your_file_path);

but if you are deleting a file from it's http path then this unlink is not work proper. You have to give a file path correct.

Remove redundant paths from $PATH variable

For an easy copy-paste template I use this Perl snippet:

PATH=`echo $PATH | perl -pe s:/path/to/be/excluded::`

This way you don't need to escape the slashes for the substitute operator.

Transport security has blocked a cleartext HTTP

See the forum post Application Transport Security?.

Also the page Configuring App Transport Security Exceptions in iOS 9 and OSX 10.11.

For example, you can add a specific domain like:

<key>NSAppTransportSecurity</key>
<dict>
  <key>NSExceptionDomains</key>
  <dict>
    <key>example.com</key>
    <dict>
      <!--Include to allow subdomains-->
      <key>NSIncludesSubdomains</key>
      <true/>
      <!--Include to allow HTTP requests-->
      <key>NSTemporaryExceptionAllowsInsecureHTTPLoads</key>
      <true/>
      <!--Include to specify minimum TLS version-->
      <key>NSTemporaryExceptionMinimumTLSVersion</key>
      <string>TLSv1.1</string>
    </dict>
  </dict>
</dict>

The lazy option is:

<key>NSAppTransportSecurity</key>
<dict>
  <!--Include to allow all connections (DANGER)-->
  <key>NSAllowsArbitraryLoads</key>
      <true/>
</dict>

Note:

info.plist is an XML file so you can place this code more or less anywhere inside the file.

Displaying the build date

One approach which I'm amazed no-one has mentioned yet is to use T4 Text Templates for code generation.

<#@ template debug="false" hostspecific="true" language="C#" #>
<#@ assembly name="System.Core" #>
<#@ import namespace="System" #>
<#@ output extension=".g.cs" #>
using System;
namespace Foo.Bar
{
    public static partial class Constants
    {
        public static DateTime CompilationTimestampUtc { get { return new DateTime(<# Write(DateTime.UtcNow.Ticks.ToString()); #>L, DateTimeKind.Utc); } }
    }
}

Pros:

  • Locale-independent
  • Allows a lot more than just the time of compilation

Cons:

Remove folder and its contents from git/GitHub's history

If you are here to copy-paste code:

This is an example which removes node_modules from history

git filter-branch --tree-filter "rm -rf node_modules" --prune-empty HEAD
git for-each-ref --format="%(refname)" refs/original/ | xargs -n 1 git update-ref -d
echo node_modules/ >> .gitignore
git add .gitignore
git commit -m 'Removing node_modules from git history'
git gc
git push origin master --force

What git actually does:

The first line iterates through all references on the same tree (--tree-filter) as HEAD (your current branch), running the command rm -rf node_modules. This command deletes the node_modules folder (-r, without -r, rm won't delete folders), with no prompt given to the user (-f). The added --prune-empty deletes useless (not changing anything) commits recursively.

The second line deletes the reference to that old branch.

The rest of the commands are relatively straightforward.

Unit testing with mockito for constructors

I have used "Pattern 2 - the "factory helper pattern"

Pattern 2 - the factory helper pattern

One case where this pattern won't work is if MyClass is final. Most of the Mockito framework doesn't play particularly well with final classes; and this includes the use of spy(). Another case is where MyClass uses getClass() somewhere, and requires the resulting value to be MyClass. This won't work, because the class of a spy is actually a Mockito-generated subclass of the original class.

In either of these cases, you'll need the slightly more robust factory helper pattern, as follows.

public class MyClass{
  static class FactoryHelper{
      Foo makeFoo( A a, B b, C c ){
          return new Foo( a, b, c );
      }
  }

  //...

  private FactoryHelper helper;
  public MyClass( X x, Y y ){
      this( x, y, new FactoryHelper());
  } 

  MyClass( X x, Y, y, FactoryHelper helper ){

      //...

      this.helper = helper;
  } 

  //...

  Foo foo = helper.makeFoo( a, b, c );
}

So, you have a special constructor, just for testing, that has an additional argument. This is used from your test class, when creating the object that you're going to test. In your test class, you mock the FactoryHelper class, as well as the object that you want to create.

@Mock private MyClass.FactoryHelper mockFactoryHelper;
@Mock private Foo mockFoo;
private MyClass toTest;

and you can use it like this

toTest = new MyClass( x, y, mockFactoryHelper ); 
when( mockFactoryHelper.makeFoo( 
  any( A.class ), any( B.class ), any( C.class )))
  .thenReturn( mockFoo ); 

Source: http://web.archive.org/web/20160322155004/http://code.google.com/p/mockito/wiki/MockingObjectCreation

How To Use DateTimePicker In WPF?

This just came in ;)

There is a new DatePicker class for WPF in the .NET 4.0 runtime: http://msdn.microsoft.com/en-us/library/system.windows.controls.datepicker.aspx

Also see the "Whats new in WPF" for more nice features: http://msdn.microsoft.com/en-us/library/bb613588.aspx

Python multiprocessing PicklingError: Can't pickle <type 'function'>

This solution requires only the installation of dill and no other libraries as pathos

def apply_packed_function_for_map((dumped_function, item, args, kwargs),):
    """
    Unpack dumped function as target function and call it with arguments.

    :param (dumped_function, item, args, kwargs):
        a tuple of dumped function and its arguments
    :return:
        result of target function
    """
    target_function = dill.loads(dumped_function)
    res = target_function(item, *args, **kwargs)
    return res


def pack_function_for_map(target_function, items, *args, **kwargs):
    """
    Pack function and arguments to object that can be sent from one
    multiprocessing.Process to another. The main problem is:
        «multiprocessing.Pool.map*» or «apply*»
        cannot use class methods or closures.
    It solves this problem with «dill».
    It works with target function as argument, dumps it («with dill»)
    and returns dumped function with arguments of target function.
    For more performance we dump only target function itself
    and don't dump its arguments.
    How to use (pseudo-code):

        ~>>> import multiprocessing
        ~>>> images = [...]
        ~>>> pool = multiprocessing.Pool(100500)
        ~>>> features = pool.map(
        ~...     *pack_function_for_map(
        ~...         super(Extractor, self).extract_features,
        ~...         images,
        ~...         type='png'
        ~...         **options,
        ~...     )
        ~... )
        ~>>>

    :param target_function:
        function, that you want to execute like  target_function(item, *args, **kwargs).
    :param items:
        list of items for map
    :param args:
        positional arguments for target_function(item, *args, **kwargs)
    :param kwargs:
        named arguments for target_function(item, *args, **kwargs)
    :return: tuple(function_wrapper, dumped_items)
        It returs a tuple with
            * function wrapper, that unpack and call target function;
            * list of packed target function and its' arguments.
    """
    dumped_function = dill.dumps(target_function)
    dumped_items = [(dumped_function, item, args, kwargs) for item in items]
    return apply_packed_function_for_map, dumped_items

It also works for numpy arrays.

Page unload event in asp.net

Refer to the ASP.NET page lifecycle to help find the right event to override. It really depends what you want to do. But yes, there is an unload event.

    protected override void OnUnload(EventArgs e)
    {
        base.OnUnload(e);

        // your code
    }

But just remember (from the above link): During the unload stage, the page and its controls have been rendered, so you cannot make further changes to the response stream. If you attempt to call a method such as the Response.Write method, the page will throw an exception.

Can an int be null in Java?

As @Glen mentioned in a comment, you basically have two ways around this:

  • use an "out of bound" value. For instance, if "data" can never be negative in normal use, return a negative value to indicate it's invalid.
  • Use an Integer. Just make sure the "check" method returns an Integer, and you assign it to an Integer not an int. Because if an "int" gets involved along the way, the automatic boxing and unboxing can cause problems.

EditText, inputType values (xml)

Supplemental answer

Here is how the standard keyboard behaves for each of these input types.

enter image description here

See this answer for more details.

How to open Android Device Monitor in latest Android Studio 3.1

Now you can use device file explorer instead of device monitor. Go to

view > tool windows > device file explorer

screenshot: opening device file explorer in android studio 3.1.3

More details

  1. Click View > Tool Windows > Device File Explorer or click the Device File Explorer button in the tool window bar to open the Device File Explorer.
  2. Select a device from the drop down list.
  3. Interact with the device content in the file explorer window. Right-click on a file or directory to create a new file or directory, save the selected file or directory to your machine, upload, delete, or synchronize. Double-click a file to open it in Android Studio.

Android Studio saves files you open this way in a temporary directory outside of your project. If you make modifications to a file you opened using the Device File Explorer, and would like to save your changes back to the device, you must manually upload the modified version of the file to the device.

screenshot: The Device File Explorer tool window

When exploring a device's files, the following directories are particularly useful:

data/data/app_name/

Contains data files for your app stored on internal storage

sdcard/

Contains user files stored on external user storage (pictures, etc.)

Note: Not all files on a hardware device are visible in the Device File Explorer. For example, in the data/data/ directory, entries corresponding to apps on the device that are not debuggable cannot be expanded in the Device File Explorer.

How to replace existing value of ArrayList element in Java

Use the set method to replace the old value with a new one.

list.set( 2, "New" );

Difference between virtual and abstract methods

an abstract method must be call override in derived class other wise it will give compile-time error and in virtual you may or may not override it's depend if it's good enough use it

Example:

abstract class twodshape
{
    public abstract void area(); // no body in base class
}

class twodshape2 : twodshape
{
    public virtual double area()
    {
        Console.WriteLine("AREA() may be or may not be override");
    }
}

Format the date using Ruby on Rails

First you will need to convert the timestamp to an actual Ruby Date/Time. If you receive it just as a string or int from facebook, you will need to do something like this:

my_date = Time.at(timestamp_from_facebook.to_i)

Then to format it nicely in the view, you can just use to_s (for the default formatting):

<%= my_date.to_s %>

Note that if you don't put to_s, it will still be called by default if you use it in a view or in a string e.g. the following will also call to_s on the date:

<%= "Here is a date: #{my_date}" %>

or if you want the date formatted in a specific way (eg using "d/m/Y") - you can use strftime as outlined in the other answer.

Is it possible to dynamically compile and execute C# code fragments?

Found this useful - ensures the compiled Assembly references everything you currently have referenced, since there's a good chance you wanted the C# you're compiling to use some classes etc in the code that's emitting this:

(string code is the dynamic C# being compiled)

        var refs = AppDomain.CurrentDomain.GetAssemblies();
        var refFiles = refs.Where(a => !a.IsDynamic).Select(a => a.Location).ToArray();
        var cSharp = (new Microsoft.CSharp.CSharpCodeProvider()).CreateCompiler();
        var compileParams = new System.CodeDom.Compiler.CompilerParameters(refFiles);
        compileParams.GenerateInMemory = true;
        compileParams.GenerateExecutable = false;

        var compilerResult = cSharp.CompileAssemblyFromSource(compileParams, code);
        var asm = compilerResult.CompiledAssembly;

In my case I was emitting a class, whose name was stored in a string, className, which had a single public static method named Get(), that returned with type StoryDataIds. Here's what calling that method looks like:

        var tempType = asm.GetType(className);
        var ids = (StoryDataIds)tempType.GetMethod("Get").Invoke(null, null);

Warning: Compilation can be surprisingly, extremely slow. A small, relatively simple 10-line chunk of code compiles at normal priority in 2-10 seconds on our relatively fast server. You should never tie calls to CompileAssemblyFromSource() to anything with normal performance expectations, like a web request. Instead, proactively compile code you need on a low-priority thread and have a way of dealing with code that requires that code to be ready, until it's had a chance to finish compiling. For example you could use it in a batch job process.

How to quit android application programmatically

It depends on how fast you want to close your app.

A safe way to close your app is finishAffinity();

It closes you app after all processes finished processing. This may need some time. If you close your app this way, and restart it after a short time, it is possible that your new application runs in the same process. With all the not finished processes and singleton objects of the old application.

If you want to be sure, that your app is closed completly use System.exit(0);

This will close your app immediatly. But it is possible, that you damage files that your app has open or an edit on shared preferences does not finish. So use this carefully.

If you use watchdog in combination with a long running task, you can see the influences of the different methods.

new ANRWatchDog(2000).setANRListener(new ANRWatchDog.ANRListener() {
    public void onAppNotResponding(ANRError error) {
        MainActivity.this.finishAffinity();
        System.exit(0);
    }
}).start();
for(int i = 0; i < 10; ++i){
    --i;
}

This kills your app after 2 seconds without displaying an ANR dialog or something like that. If you remove System.exit(0), run this code and restart the app after it is closed, you will experience some strange behaviour, because the endless loop is still running.

Appending an element to the end of a list in Scala

This is similar to one of the answers but in different way :

scala> val x = List(1,2,3)
x: List[Int] = List(1, 2, 3)

scala> val y = x ::: 4 :: Nil
y: List[Int] = List(1, 2, 3, 4)

Make just one slide different size in Powerpoint

True you can't have different sized slides. NOT true the size of you slide doesn't matter. It will size it to your resolution, but you can click on the magnifying icon(at least on PP 2013) and you can then scroll in all directions of your slide in original resolution.

Twitter API returns error 215, Bad Authentication Data

After two days of research I finally found that to access s.o. public tweets you just need any application credentials, and not that particular user ones. So if you are developing for a client, you don't have to ask them to do anything.

To use the new Twitter API 1.1 you need two things:

First, you can (actually have to) create an application with your own credentials and then get the Access token (OAUTH_TOKEN) and Access token secret (OAUTH_TOKEN_SECRET) from the "Your access token" section. Then you supply them in the constructor for the new TwitterOAuth object. Now you can access anyone public tweets.

$connection = new TwitterOAuth( CONSUMER_KEY, CONSUMER_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET );

$connection->host = "https://api.twitter.com/1.1/"; // change the default
$connection->ssl_verifypeer = TRUE;
$connection->content_type = 'application/x-www-form-urlencoded';

$tweets = $connection->get('http://api.twitter.com/1.1/statuses/user_timeline.json?screen_name='.$username.'&count='.$count);

Actually I think this is what Pavel has suggested also, but it is not so obvious from his answer.

Hope this saves someone else those two days :)

Razor-based view doesn't see referenced assemblies

I had the same problem: MVC3 Project MyCore.Web was referencing to MyCore.DBLayer namespace from another project in the same solution (with assembly name MyCoreDBLayer). All objects from MyCore.DBLayer worked perfectly in Controllers and Models but failed in Razor views with an error 'The type or namespace name 'DBLayer' does not exist in the namespace 'MyCore' (are you missing an assembly reference?)' which was obviously not the case.

  • Copy Local option was set to true.
  • Adding "using..." statements in Razor views was useless
  • Adding namespaces to system.web.webPages.razor section was useless as well

Adding assembly referecene to system.web/compilation/assemblies section of the root web.config file fixed the issue. The section now looks like:

<system.web>
    <compilation debug="true" targetFramework="4.0">
      <assemblies>
        <add assembly="System.Web.Abstractions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
        <add assembly="System.Web.Helpers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
        <add assembly="System.Web.Routing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
        <add assembly="System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
        <add assembly="System.Web.WebPages, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
        **<add assembly="MyCoreDBLayer" />**
      </assemblies>
    </compilation>
...
</system.web>

Omitting version, culture, token was OK for now, but should be fixed in the future.

Create a new TextView programmatically then display it below another TextView

Try this code:

final String[] str = {"one","two","three","asdfgf"};
final RelativeLayout rl = (RelativeLayout) findViewById(R.id.rl);
final TextView[] tv = new TextView[10];

for (int i=0; i<str.length; i++)
{
    tv[i] = new TextView(this); 
    RelativeLayout.LayoutParams params=new RelativeLayout.LayoutParams
         ((int)LayoutParams.WRAP_CONTENT,(int)LayoutParams.WRAP_CONTENT);
    params.leftMargin = 50;
    params.topMargin  = i*50;
    tv[i].setText(str[i]);
    tv[i].setTextSize((float) 20);
    tv[i].setPadding(20, 50, 20, 50);
    tv[i].setLayoutParams(params);
    rl.addView(tv[i]);  
}

How to print object array in JavaScript?

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

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

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

Select Row number in postgres

SELECT tab.*,
    row_number() OVER () as rnum
  FROM tab;

Here's the relevant section in the docs.

P.S. This, in fact, fully matches the answer in the referenced question.

Are the decimal places in a CSS width respected?

Even when the number is rounded when the page is painted, the full value is preserved in memory and used for subsequent child calculation. For example, if your box of 100.4999px paints to 100px, it's child with a width of 50% will be calculated as .5*100.4999 instead of .5*100. And so on to deeper levels.

I've created deeply nested grid layout systems where parents widths are ems, and children are percents, and including up to four decimal points upstream had a noticeable impact.

Edge case, sure, but something to keep in mind.

What is a NullReferenceException, and how do I fix it?

Simon Mourier gave this example:

object o = null;
DateTime d = (DateTime)o;  // NullReferenceException

where an unboxing conversion (cast) from object (or from one of the classes System.ValueType or System.Enum, or from an interface type) to a value type (other than Nullable<>) in itself gives the NullReferenceException.

In the other direction, a boxing conversion from a Nullable<> which has HasValue equal to false to a reference type, can give a null reference which can then later lead to a NullReferenceException. The classic example is:

DateTime? d = null;
var s = d.ToString();  // OK, no exception (no boxing), returns ""
var t = d.GetType();   // Bang! d is boxed, NullReferenceException

Sometimes the boxing happens in another way. For example with this non-generic extension method:

public static void MyExtension(this object x)
{
  x.ToString();
}

the following code will be problematic:

DateTime? d = null;
d.MyExtension();  // Leads to boxing, NullReferenceException occurs inside the body of the called method, not here.

These cases arise because of the special rules the runtime uses when boxing Nullable<> instances.

How to avoid the "Windows Defender SmartScreen prevented an unrecognized app from starting warning"

If you have a standard code signing certificate, some time will be needed for your application to build trust. Microsoft affirms that an Extended Validation (EV) Code Signing Certificate allows us to skip this period of trust-building. According to Microsoft, extended validation certificates allow the developer to immediately establish a reputation with SmartScreen. Otherwise, the users will see a warning like "Windows Defender SmartScreen prevented an unrecognized app from starting. Running this app might put your PC at risk.", with the two buttons: "Run anyway" and "Don't run".

Another Microsoft resource states the following (quote): "Although not required, programs signed by an EV code signing certificate can immediately establish a reputation with SmartScreen reputation services even if no prior reputation exists for that file or publisher. EV code signing certificates also have a unique identifier which makes it easier to maintain reputation across certificate renewals."

My experience is as follows. Since 2005, we have been using regular (non-EV) code signing certificates to sign .MSI, .EXE and .DLL files with time stamps, and there has never been a problem with SmartScreen until 2018, when there was just one case when it took 3 days for a beta version of our application to build trust since we have released it to beta testers, and it was in the middle of certificate validity period. I don't know what SmartScreen might not like in that specific version of our application, but there have been no SmartScreen complaints since then. Therefore, if your certificate is a non-EV, it is a signed application (such as an .MSI file) that will build trust over time, not a certificate. For example, a certificate can be issued a few months ago and used to sign many files, but for each signed file you publish, it may take a few days for SmartScreen to stop complaining about the file after publishing, as was in our case in 2018.

As a conclusion, to avoid the warning completely, i.e. prevent it from happening even suddenly, you need an Extended Validation (EV) code signing certificate.

"X does not name a type" error in C++

When the compiler compiles the class User and gets to the MyMessageBox line, MyMessageBox has not yet been defined. The compiler has no idea MyMessageBox exists, so cannot understand the meaning of your class member.

You need to make sure MyMessageBox is defined before you use it as a member. This is solved by reversing the definition order. However, you have a cyclic dependency: if you move MyMessageBox above User, then in the definition of MyMessageBox the name User won't be defined!

What you can do is forward declare User; that is, declare it but don't define it. During compilation, a type that is declared but not defined is called an incomplete type. Consider the simpler example:

struct foo; // foo is *declared* to be a struct, but that struct is not yet defined

struct bar
{
    // this is okay, it's just a pointer;
    // we can point to something without knowing how that something is defined
    foo* fp; 

    // likewise, we can form a reference to it
    void some_func(foo& fr);

    // but this would be an error, as before, because it requires a definition
    /* foo fooMember; */
};

struct foo // okay, now define foo!
{
    int fooInt;
    double fooDouble;
};

void bar::some_func(foo& fr)
{
    // now that foo is defined, we can read that reference:
    fr.fooInt = 111605;
    fr.foDouble = 123.456;
}

By forward declaring User, MyMessageBox can still form a pointer or reference to it:

class User; // let the compiler know such a class will be defined

class MyMessageBox
{
public:
    // this is ok, no definitions needed yet for User (or Message)
    void sendMessage(Message *msg, User *recvr); 

    Message receiveMessage();
    vector<Message>* dataMessageList;
};

class User
{
public:
    // also ok, since it's now defined
    MyMessageBox dataMsgBox;
};

You cannot do this the other way around: as mentioned, a class member needs to have a definition. (The reason is that the compiler needs to know how much memory User takes up, and to know that it needs to know the size of its members.) If you were to say:

class MyMessageBox;

class User
{
public:
    // size not available! it's an incomplete type
    MyMessageBox dataMsgBox;
};

It wouldn't work, since it doesn't know the size yet.


On a side note, this function:

 void sendMessage(Message *msg, User *recvr);

Probably shouldn't take either of those by pointer. You can't send a message without a message, nor can you send a message without a user to send it to. And both of those situations are expressible by passing null as an argument to either parameter (null is a perfectly valid pointer value!)

Rather, use a reference (possibly const):

 void sendMessage(const Message& msg, User& recvr);

How to find largest objects in a SQL Server database?

I've been using this SQL script (which I got from someone, somewhere - can't reconstruct who it came from) for ages and it's helped me quite a bit understanding and determining the size of indices and tables:

SELECT 
    t.name AS TableName,
    i.name as indexName,
    sum(p.rows) as RowCounts,
    sum(a.total_pages) as TotalPages, 
    sum(a.used_pages) as UsedPages, 
    sum(a.data_pages) as DataPages,
    (sum(a.total_pages) * 8) / 1024 as TotalSpaceMB, 
    (sum(a.used_pages) * 8) / 1024 as UsedSpaceMB, 
    (sum(a.data_pages) * 8) / 1024 as DataSpaceMB
FROM 
    sys.tables t
INNER JOIN      
    sys.indexes i ON t.object_id = i.object_id
INNER JOIN 
    sys.partitions p ON i.object_id = p.object_id AND i.index_id = p.index_id
INNER JOIN 
    sys.allocation_units a ON p.partition_id = a.container_id
WHERE 
    t.name NOT LIKE 'dt%' AND
    i.object_id > 255 AND  
    i.index_id <= 1
GROUP BY 
    t.name, i.object_id, i.index_id, i.name 
ORDER BY 
    object_name(i.object_id) 

Of course, you can use another ordering criteria, e.g.

ORDER BY SUM(p.rows) DESC

to get the tables with the most rows, or

ORDER BY SUM(a.total_pages) DESC

to get the tables with the most pages (8K blocks) used.

Split string into individual words Java

you can use Apache commons' StringUtils class

    String[] partsOfString = StringUtils.split("I want to walk my dog",StringUtils.SPACE)

How do I run a terminal inside of Vim?

If enabled in your version of Vim, a terminal can be started with the :term command.

Terminal window support was added to Vim 8. It is an optional feature that can be enabled when compiling Vim with the +terminal feature. If your version of Vim has terminal support, :echo has('terminal') will output "1".

Entering :term will place you in Terminal-Job mode, where you can use the terminal as expected.

Within Terminal-Job mode, pressing Ctrl-W N or Ctrl-\ Ctrl-N switches the mode to Terminal-Normal, which allows the cursor to be moved and commands to be ran similarly to Vim's Normal mode. To switch back to Terminal-Job mode, press i.

Other answers mention similar functionality in Neovim.

Pan & Zoom Image

I also tried this answer but was not entirely happy with the result. I kept googling around and finally found a Nuget Package that helped me to manage the result I wanted, anno 2021. I would like to share it with the former developers of Stack Overflow.

I used this Nuget Package Gu.WPF.Geometry found via this Github Repository. All credits for develoment should go to Johan Larsson, the owner of this package.

How I used it? I wanted to have the commands as buttons below the zoombox, as shown here in MachineLayoutControl.xaml .

<UserControl
   x:Class="MyLib.MachineLayoutControl"
   xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
   xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
   xmlns:csmachinelayoutdrawlib="clr-namespace:CSMachineLayoutDrawLib"
   xmlns:effects="http://gu.se/Geometry">
   <UserControl.Resources>
       <ResourceDictionary Source="Resources/ResourceDictionaries/AllResourceDictionariesCombined.xaml" />
   </UserControl.Resources>

   <Grid Margin="0">
       <Grid.RowDefinitions>
           <RowDefinition Height="*" />
           <RowDefinition Height="Auto" />
       </Grid.RowDefinitions>

       <Border
           Grid.Row="0"
           Margin="0,0"
           Padding="0"
           BorderThickness="1"
           Style="{StaticResource Border_Head}"
           Visibility="Visible">
           <effects:Zoombox
               x:Name="ImageBox"
               IsManipulationEnabled="True"
               MaxZoom="10"
               MinZoom="0.1"
               Visibility="{Binding Zoombox_Visibility}">
               <ContentControl Content="{Binding Viewing_Canvas}" />
           </effects:Zoombox>
       </Border>
           <StackPanel
               Grid.Column="1"
               Margin="10"
               HorizontalAlignment="Right"
               Orientation="Horizontal">
               <Button
                   Command="effects:ZoomCommands.Increase"
                   CommandParameter="2.0"
                   CommandTarget="{Binding ElementName=ImageBox}"
                   Content="Zoom In"
                   Style="{StaticResource StyleForResizeButtons}" />

               <Button
                   Command="effects:ZoomCommands.Decrease"
                   CommandParameter="2.0"
                   CommandTarget="{Binding ElementName=ImageBox}"
                   Content="Zoom Out"
                   Style="{StaticResource StyleForResizeButtons}" />

               <Button
                   Command="effects:ZoomCommands.Uniform"
                   CommandTarget="{Binding ElementName=ImageBox}"
                   Content="See Full Machine"
                   Style="{StaticResource StyleForResizeButtons}" />

               <Button
                   Command="effects:ZoomCommands.UniformToFill"
                   CommandTarget="{Binding ElementName=ImageBox}"
                   Content="Zoom To Machine Width"
                   Style="{StaticResource StyleForResizeButtons}" />
   
           </StackPanel>

</Grid>
</UserControl>

In the underlying Viewmodel, I had the following relevant code:

public Visibility Zoombox_Visibility { get => movZoombox_Visibility; set { movZoombox_Visibility = value; OnPropertyChanged(nameof(Zoombox_Visibility)); } }
public Canvas Viewing_Canvas { get => mdvViewing_Canvas; private set => mdvViewing_Canvas = value; }

Also, I wanted that immediately on loading, the Uniform to Fill Command was executed, this is something that I managed to do in the code-behind MachineLayoutControl.xaml.cs . You see that I only set the Zoombox to visible if the command is executed, to avoid "flickering" when the usercontrol is loading.

    public partial class MachineLayoutControl : UserControl
    {
        #region Constructors

        public MachineLayoutControl()
        {
            InitializeComponent();
            Loaded += MyWindow_Loaded;
        }

        #endregion Constructors

        #region EventHandlers

        private void MyWindow_Loaded(object sender, RoutedEventArgs e)
        {
            Application.Current.Dispatcher.BeginInvoke(
               DispatcherPriority.ApplicationIdle,
               new Action(() =>
               {
                   ZoomCommands.Uniform.Execute(null, ImageBox);
                   ((MachineLayoutControlViewModel)DataContext).Zoombox_Visibility = Visibility.Visible;
               }));
        }

        #endregion EventHandlers
    }

Result

Is it possible to set UIView border properties from interface builder?

Similar answer to iHulk's one, but in Swift

Add a file named UIView.swift in your project (or just paste this in any file) :

import UIKit

@IBDesignable extension UIView {
    @IBInspectable var borderColor: UIColor? {
        set {
            layer.borderColor = newValue?.cgColor
        }
        get {
            guard let color = layer.borderColor else {
                return nil
            }
            return UIColor(cgColor: color)
        }
    }
    @IBInspectable var borderWidth: CGFloat {
        set {
            layer.borderWidth = newValue
        }
        get {
            return layer.borderWidth
        }
    }
    @IBInspectable var cornerRadius: CGFloat {
        set {
            layer.cornerRadius = newValue
            clipsToBounds = newValue > 0
        }
        get {
            return layer.cornerRadius
        }
    }
}

Then this will be available in Interface Builder for every button, imageView, label, etc. in the Utilities Panel > Attributes Inspector :

Attributes Inspector

Note: the border will only appear at runtime.

Unlink of file Failed. Should I try again?

On Windows 8: I ran git gc and it said git gc was already running, I ran git gc --force and the garbage collector ran.

I could then switch branches and merge without any issues, try git gc --force.

Perhaps the gc process didn't stop gracefully for one reason or another.

HTTP GET with request body

What you're trying to achieve has been done for a long time with a much more common method, and one that doesn't rely on using a payload with GET.

You can simply build your specific search mediatype, or if you want to be more RESTful, use something like OpenSearch, and POST the request to the URI the server instructed, say /search. The server can then generate the search result or build the final URI and redirect using a 303.

This has the advantage of following the traditional PRG method, helps cache intermediaries cache the results, etc.

That said, URIs are encoded anyway for anything that is not ASCII, and so are application/x-www-form-urlencoded and multipart/form-data. I'd recommend using this rather than creating yet another custom json format if your intention is to support ReSTful scenarios.

Changing website favicon dynamically

I use this feature all the time when developing sites ... so I can see at-a-glance which tab has local, dev or prod running in it.

Now that Chrome supports SVG favicons it makes it a whole lot easier.

Tampermonkey Script

Have a gander at https://gist.github.com/elliz/bb7661d8ed1535c93d03afcd0609360f for a tampermonkey script that points to a demo site I chucked up at https://elliz.github.io/svg-favicon/

Basic code

Adapted this from another answer ... could be improved but good enough for my needs.

(function() {
    'use strict';

    // play with https://codepen.io/elliz/full/ygvgay for getting it right
    // viewBox is required but does not need to be 16x16
    const svg = `
    <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16">
      <circle cx="8" cy="8" r="7.2" fill="gold" stroke="#000" stroke-width="1" />
      <circle cx="8" cy="8" r="3.1" fill="#fff" stroke="#000" stroke-width="1" />
    </svg>
    `;

    var favicon_link_html = document.createElement('link');
    favicon_link_html.rel = 'icon';
    favicon_link_html.href = svgToDataUri(svg);
    favicon_link_html.type = 'image/svg+xml';

    try {
        let favicons = document.querySelectorAll('link[rel~="icon"]');
        favicons.forEach(function(favicon) {
            favicon.parentNode.removeChild(favicon);
        });

        const head = document.getElementsByTagName('head')[0];
        head.insertBefore( favicon_link_html, head.firstChild );
    }
    catch(e) { }

    // functions -------------------------------
    function escapeRegExp(str) {
        return str.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, "\\$1");
    }

    function replaceAll(str, find, replace) {
        return str.replace(new RegExp(escapeRegExp(find), 'g'), replace);
    }

    function svgToDataUri(svg) {
        // these may not all be needed - used to be for uri-encoded svg in old browsers
        var encoded = svg.replace(/\s+/g, " ")
        encoded = replaceAll(encoded, "%", "%25");
        encoded = replaceAll(encoded, "> <", "><"); // normalise spaces elements
        encoded = replaceAll(encoded, "; }", ";}"); // normalise spaces css
        encoded = replaceAll(encoded, "<", "%3c");
        encoded = replaceAll(encoded, ">", "%3e");
        encoded = replaceAll(encoded, "\"", "'"); // normalise quotes ... possible issues with quotes in <text>
        encoded = replaceAll(encoded, "#", "%23"); // needed for ie and firefox
        encoded = replaceAll(encoded, "{", "%7b");
        encoded = replaceAll(encoded, "}", "%7d");
        encoded = replaceAll(encoded, "|", "%7c");
        encoded = replaceAll(encoded, "^", "%5e");
        encoded = replaceAll(encoded, "`", "%60");
        encoded = replaceAll(encoded, "@", "%40");
        var dataUri = 'data:image/svg+xml;charset=UTF-8,' + encoded.trim();
        return dataUri;
    }

})();

Just pop your own SVG (maybe cleaned with Jake Archibald's SVGOMG if you're using a tool) into the const at the top. Make sure it is square (using the viewBox attribute) and you're good to go.

Effect of NOLOCK hint in SELECT statements

  • The answer is Yes if the query is run multiple times at once, because each transaction won't need to wait for the others to complete. However, If the query is run once on its own then the answer is No.

  • Yes. There's a significant probability that careful use of WITH(NOLOCK) will speed up your database overall. It means that other transactions won't have to wait for this SELECT statement to finish, but on the other hand, other transactions will slow down as they're now sharing their processing time with a new transaction.

Be careful to only use WITH (NOLOCK) in SELECT statements on tables that have a clustered index.

WITH(NOLOCK) is often exploited as a magic way to speed up database read transactions.

The result set can contain rows that have not yet been committed, that are often later rolled back.

If WITH(NOLOCK) is applied to a table that has a non-clustered index then row-indexes can be changed by other transactions as the row data is being streamed into the result-table. This means that the result-set can be missing rows or display the same row multiple times.

READ COMMITTED adds an additional issue where data is corrupted within a single column where multiple users change the same cell simultaneously.

iPhone/iPad browser simulator?

For now i think best emulator is https://app.crossbrowsertesting.com

It has real sizes and virtual keyboard (that is the most important thing) , zooming events...

Also https://appetize.io/demo has same things but it has time limit.

How do I copy a range of formula values and paste them to a specific range in another sheet?

You can change

Range("B3:B65536").Copy Destination:=Sheets("DB").Range("B" & lastrow)

to

Range("B3:B65536").Copy 
Sheets("DB").Range("B" & lastrow).PasteSpecial xlPasteValues

BTW, if you have xls file (excel 2003), you would get an error if your lastrow would be greater 3.

Try to use this code instead:

Sub Get_Data()
    Dim lastrowDB As Long, lastrow As Long
    Dim arr1, arr2, i As Integer

    With Sheets("DB")
        lastrowDB = .Cells(.Rows.Count, "A").End(xlUp).Row + 1
    End With

    arr1 = Array("B", "C", "D", "E", "F", "AH", "AI", "AJ", "J", "P", "AF")
    arr2 = Array("B", "A", "C", "P", "D", "E", "G", "F", "H", "I", "J")

    For i = LBound(arr1) To UBound(arr1)
        With Sheets("Sheet1")
             lastrow = Application.Max(3, .Cells(.Rows.Count, arr1(i)).End(xlUp).Row)
             .Range(.Cells(3, arr1(i)), .Cells(lastrow, arr1(i))).Copy
             Sheets("DB").Range(arr2(i) & lastrowDB).PasteSpecial xlPasteValues
        End With
    Next
    Application.CutCopyMode = False
End Sub

Note, above code determines last non empty row on DB sheet in column A (variable lastrowDB). If you need to find lastrow for each destination column in DB sheet, use next modification:

For i = LBound(arr1) To UBound(arr1)
   With Sheets("DB")
       lastrowDB = .Cells(.Rows.Count, arr2(i)).End(xlUp).Row + 1
   End With

   ' NEXT CODE

Next

You could also use next approach instead Copy/PasteSpecial. Replace

.Range(.Cells(3, arr1(i)), .Cells(lastrow, arr1(i))).Copy
Sheets("DB").Range(arr2(i) & lastrowDB).PasteSpecial xlPasteValues

with

Sheets("DB").Range(arr2(i) & lastrowDB).Resize(lastrow - 2).Value = _
      .Range(.Cells(3, arr1(i)), .Cells(lastrow, arr1(i))).Value

What is the way of declaring an array in JavaScript?

To declare it:

var myArr = ["apples", "oranges", "bananas"];

To use it:

document.write("In my shopping basket I have " + myArr[0] + ", " + myArr[1] + ", and " + myArr[2]);

error: invalid initialization of non-const reference of type ‘int&’ from an rvalue of type ‘int’

References are "hidden pointers" (non-null) to things which can change (lvalues). You cannot define them to a constant. It should be a "variable" thing.

EDIT::

I am thinking of

int &x = y;

as almost equivalent of

int* __px = &y;
#define x (*__px)

where __px is a fresh name, and the #define x works only inside the block containing the declaration of x reference.

Map isn't showing on Google Maps JavaScript API v3 when nested in a div tag

Add style="width:100%; height:100%;" to the div see what that does

not to the #map_canvas but the main div

example

<body>
    <div style="height:100%; width:100%;">
         <div id="map-canvas"></div>
    </div>
</body> 

There are some other answers on here the explain why this is necessary

How to send authorization header with axios

You are nearly correct, just adjust your code this way

const headers = { Authorization: `Bearer ${token}` };
return axios.get(URLConstants.USER_URL, { headers });

notice where I place the backticks, I added ' ' after Bearer, you can omit if you'll be sure to handle at the server-side

Hibernate show real SQL

Can I see (...) the real SQL

If you want to see the SQL sent directly to the database (that is formatted similar to your example), you'll have to use some kind of jdbc driver proxy like P6Spy (or log4jdbc).

Alternatively you can enable logging of the following categories (using a log4j.properties file here):

log4j.logger.org.hibernate.SQL=DEBUG
log4j.logger.org.hibernate.type=TRACE

The first is equivalent to hibernate.show_sql=true, the second prints the bound parameters among other things.

Reference

Try-catch speeding up my code?

Jon's disassemblies show, that the difference between the two versions is that the fast version uses a pair of registers (esi,edi) to store one of the local variables where the slow version doesn't.

The JIT compiler makes different assumptions regarding register use for code that contains a try-catch block vs. code which doesn't. This causes it to make different register allocation choices. In this case, this favors the code with the try-catch block. Different code may lead to the opposite effect, so I would not count this as a general-purpose speed-up technique.

In the end, it's very hard to tell which code will end up running the fastest. Something like register allocation and the factors that influence it are such low-level implementation details that I don't see how any specific technique could reliably produce faster code.

For example, consider the following two methods. They were adapted from a real-life example:

interface IIndexed { int this[int index] { get; set; } }
struct StructArray : IIndexed { 
    public int[] Array;
    public int this[int index] {
        get { return Array[index]; }
        set { Array[index] = value; }
    }
}

static int Generic<T>(int length, T a, T b) where T : IIndexed {
    int sum = 0;
    for (int i = 0; i < length; i++)
        sum += a[i] * b[i];
    return sum;
}
static int Specialized(int length, StructArray a, StructArray b) {
    int sum = 0;
    for (int i = 0; i < length; i++)
        sum += a[i] * b[i];
    return sum;
}

One is a generic version of the other. Replacing the generic type with StructArray would make the methods identical. Because StructArray is a value type, it gets its own compiled version of the generic method. Yet the actual running time is significantly longer than the specialized method's, but only for x86. For x64, the timings are pretty much identical. In other cases, I've observed differences for x64 as well.

How to write a confusion matrix in Python?

Only with numpy, we can do as follow considering efficiency:

def confusion_matrix(pred, label, nc=None):
    assert pred.size == label.size
    if nc is None:
        nc = len(unique(label))
        logging.debug("Number of classes assumed to be {}".format(nc))

    confusion = np.zeros([nc, nc])
    # avoid the confusion with `0`
    tran_pred = pred + 1
    for i in xrange(nc):    # current class
        mask = (label == i)
        masked_pred = mask * tran_pred
        cls, counts = unique(masked_pred, return_counts=True)
        # discard the first item
        cls = [cl - 1 for cl in cls][1:]
        counts = counts[1:]
        for cl, count in zip(cls, counts):
            confusion[i, cl] = count
    return confusion

For other features such as plot, mean-IoU, see my repositories.

How to make an element width: 100% minus padding?

You can try some positioning tricks. You can put the input in a div with position: relative and a fixed height, then on the input have position: absolute; left: 0; right: 0;, and any padding you like.

Live example

Good font for code presentations?

  • Lucida Console (good, but a little short)
  • Lucida Sans Typewriter (taller, smaller character set)
  • Andale Mono is very clear

But this has been answered here before.

jQuery: If this HREF contains

$("a").each(function() {
    if (this.href.indexOf('?') != -1) {
        alert("Contains questionmark");
    }
});

How to convert milliseconds to seconds with precision

I had this problem too, somehow my code did not present the exact values but rounded the number in seconds to 0.0 (if milliseconds was under 1 second). What helped me out is adding the decimal to the division value.

double time_seconds = time_milliseconds / 1000.0;   // add the decimal
System.out.println(time_milliseconds);              // Now this should give you the right value.

How do I vertically center an H1 in a div?

HTML

<div id='sample'>
<span class='vertical'>Test Message</span>
</div>

CSS

    #sample 
    {
        height:100px;
         width:100%;
        background-color:#003366;
        display:table;
        text-align: center;

    }
    .vertical 
    {
           color:white;
         display:table-cell;
        vertical-align:middle;
}

Fiddle : Demo

CSS text-overflow: ellipsis; not working?

In bootstrap 4, you can add a .text-truncate class to truncate the text with an ellipsis.

_x000D_
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet" />_x000D_
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script>_x000D_
_x000D_
<!-- Inline level -->_x000D_
<span class="d-inline-block text-truncate" style="max-width: 250px;">_x000D_
  The quick brown fox jumps over the lazy dog._x000D_
</span>
_x000D_
_x000D_
_x000D_

What is the difference between for and foreach?

It depends on what you are doing, and what you need.

If you are iterating through a collection of items, and do not care about the index values then foreach is more convenient, easier to write and safer: you can't get the number of items wrong.

If you need to process every second item in a collection for example, or process them ion the reverse order, then a for loop is the only practical way.

The biggest differences are that a foreach loop processes an instance of each element in a collection in turn, while a for loop can work with any data and is not restricted to collection elements alone. This means that a for loop can modify a collection - which is illegal and will cause an error in a foreach loop.

For more detail, see MSDN : foreach and for

How to add a button to UINavigationBar?

swift 3

    let cancelBarButton = UIBarButtonItem(title: "Cancel", style: .done, target: self, action: #selector(cancelPressed(_:)))
    cancelBarButton.setTitleTextAttributes( [NSFontAttributeName : UIFont.cancelBarButtonFont(),
                                                          NSForegroundColorAttributeName : UIColor.white], for: .normal)
    self.navigationItem.leftBarButtonItem = cancelBarButton


    func cancelPressed(_ sender: UIBarButtonItem ) {
        self.dismiss(animated: true, completion: nil)
    }

Execute an action when an item on the combobox is selected

this is how you do it with ActionLIstener

import java.awt.FlowLayout;
import java.awt.event.*;

import javax.swing.*;

public class MyWind extends JFrame{

    public MyWind() {
        initialize();
    }

    private void initialize() {
        setSize(300, 300);
        setLayout(new FlowLayout(FlowLayout.LEFT));
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        final JTextField field = new JTextField();
        field.setSize(200, 50);
        field.setText("              ");

        JComboBox comboBox = new JComboBox();
        comboBox.setEditable(true);
        comboBox.addItem("item1");
        comboBox.addItem("item2");

        //
        // Create an ActionListener for the JComboBox component.
        //
        comboBox.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent event) {
                //
                // Get the source of the component, which is our combo
                // box.
                //
                JComboBox comboBox = (JComboBox) event.getSource();

                Object selected = comboBox.getSelectedItem();
                if(selected.toString().equals("item1"))
                field.setText("30");
                else if(selected.toString().equals("item2"))
                    field.setText("40");

            }
        });
        getContentPane().add(comboBox);
        getContentPane().add(field);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                new MyWind().setVisible(true);
            }
        });
    }
}

Trying to use fetch and pass in mode: no-cors

So if you're like me and developing a website on localhost where you're trying to fetch data from Laravel API and use it in your Vue front-end, and you see this problem, here is how I solved it:

  1. In your Laravel project, run command php artisan make:middleware Cors. This will create app/Http/Middleware/Cors.php for you.
  2. Add the following code inside the handles function in Cors.php:

    return $next($request)
        ->header('Access-Control-Allow-Origin', '*')
        ->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
    
  3. In app/Http/kernel.php, add the following entry in $routeMiddleware array:

    ‘cors’ => \App\Http\Middleware\Cors::class
    

    (There would be other entries in the array like auth, guest etc. Also make sure you're doing this in app/Http/kernel.php because there is another kernel.php too in Laravel)

  4. Add this middleware on route registration for all the routes where you want to allow access, like this:

    Route::group(['middleware' => 'cors'], function () {
        Route::get('getData', 'v1\MyController@getData');
        Route::get('getData2', 'v1\MyController@getData2');
    });
    
  5. In Vue front-end, make sure you call this API in mounted() function and not in data(). Also make sure you use http:// or https:// with the URL in your fetch() call.

Full credits to Pete Houston's blog article.

POI setting Cell Background to a Custom Color

Slot free in NPOI excel indexedcolors from 57+

            Color selColor;

        var wb = new HSSFWorkbook();

        var sheet = wb.CreateSheet("NPOI");
        var style = wb.CreateCellStyle();
        var font = wb.CreateFont();
        var palette = wb.GetCustomPalette();

        short indexColor = 57; 
        palette.SetColorAtIndex(indexColor, (byte)selColor.R, (byte)selColor.G, (byte)selColor.B);

        font.Color = palette.GetColor(indexColor).Indexed;

SQL variable to hold list of integers

For SQL Server 2016+ and Azure SQL Database, the STRING_SPLIT function was added that would be a perfect solution for this problem. Here is the documentation: https://docs.microsoft.com/en-us/sql/t-sql/functions/string-split-transact-sql

Here is an example:

/*List of ids in a comma delimited string
  Note: the ') WAITFOR DELAY ''00:00:02''' is a way to verify that your script 
        doesn't allow for SQL injection*/
DECLARE @listOfIds VARCHAR(MAX) = '1,3,a,10.1,) WAITFOR DELAY ''00:00:02''';

--Make sure the temp table was dropped before trying to create it
IF OBJECT_ID('tempdb..#MyTable') IS NOT NULL DROP TABLE #MyTable;

--Create example reference table
CREATE TABLE #MyTable
([Id] INT NOT NULL);

--Populate the reference table
DECLARE @i INT = 1;
WHILE(@i <= 10)
BEGIN
    INSERT INTO #MyTable
    SELECT @i;

    SET @i = @i + 1;
END

/*Find all the values
  Note: I silently ignore the values that are not integers*/
SELECT t.[Id]
FROM #MyTable as t
    INNER JOIN 
        (SELECT value as [Id] 
        FROM STRING_SPLIT(@listOfIds, ',')
        WHERE ISNUMERIC(value) = 1 /*Make sure it is numeric*/
            AND ROUND(value,0) = value /*Make sure it is an integer*/) as ids
    ON t.[Id] = ids.[Id];

--Clean-up
DROP TABLE #MyTable;

The result of the query is 1,3

~Cheers

Email address validation using ASP.NET MVC data type attributes

Used the above code in MVC5 project and it works completely fine with the validation error. Just try this code:

   [Required]
   [Display(Name = "Email")]
   [EmailAddress]

   [RegularExpression(@"^([A-Za-z0-9][^'!&\\#*$%^?<>()+=:;`~\[\]{}|/,?€@ ][a-zA-z0- 
    9-._][^!&\\#*$%^?<>()+=:;`~\[\]{}|/,?€@ ]*\@[a-zA-Z0-9][^!&@\\#*$%^?<> 
        ()+=':;~`.\[\]{}|/,?€ ]*\.[a-zA-Z]{2,6})$", ErrorMessage = "Please enter a 
   valid Email")]


   public string ReceiverMail { get; set; }

How do I vertically align something inside a span tag?

CSS vertical center image and text

I have Create one demo for vertical image center and text also i have test on firefox ,chrome,safari, internet explorer 9 and 8 too.

It is very short and easy css and html, Please check below code and you can find output on screenshort.

HTML

<div class="frame">
    <img src="capabilities_icon1.png" alt="" />
</div>

CSS

  .frame {
        height: 160px;      
        width: 160px;
        border: 1px solid red;
        white-space: nowrap;
        text-align: center; margin: 1em 0;
    }

    .frame::before {
        display: inline-block;
        height: 100%;
        vertical-align: middle;
        content:"";
    }

    img {
        background: #3A6F9A;
        vertical-align: middle;
    }

Output enter image description here

Java 8 stream map on entry set

On Java 9 or later, Map.entry can be used, so long as you know that neither the key nor value will be null. If either value could legitimately be null, AbstractMap.SimpleEntry (as suggested in another answer) or AbstractMap.SimpleImmutableEntry would be the way to go.

private Map<String, AttributeType> mapConfig(Map<String, String> input, String prefix) {
   int subLength = prefix.length();
   return input.entrySet().stream().map(e -> 
      Map.entry(e.getKey().substring(subLength), AttributeType.GetByName(e.getValue())));
   }).collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
}

How to find the array index with a value?

It is possible to use a ES6 function Array.prototype.findIndex.

MDN says:

The findIndex() method returns the index of the first element in the array that satisfies the provided testing function. Otherwise -1 is returned.

var fooArray = [5, 10, 15, 20, 25];
console.log(fooArray.findIndex(num=> { return num > 5; }));

// expected output: 1

Find an index by object property.

To find an index by object property:

yourArray.findIndex(obj => obj['propertyName'] === yourValue)

For example, there is a such array:

let someArray = [
    { property: 'OutDate' },
    { property: 'BeginDate'},
    { property: 'CarNumber' },
    { property: 'FirstName'}
];

Then, code to find an index of necessary property looks like that:

let carIndex = someArray.findIndex( filterCarObj=> 
    filterCarObj['property'] === 'CarNumber');

Returning an empty array

return new File[0];

This is better and efficient approach.

Setting DIV width and height in JavaScript

Fix the typos in your code ("document" is spelled wrong on lines 3 & 4 of your function, and change the onclick event handler to read: onclick="show_update_profile()" and then you'll be fine. You should really follow jmort's advice and simply set up 2 css classes that you switch between in javascript -- it would make your life a lot easier and save yourself from all the extra typing. The typos you've committed are a perfect example of why this is the better approach.

For brownie points, you should also check out element.addEventListener for assigning event handlers to your elements.

How to strip HTML tags from string in JavaScript?

var html = "<p>Hello, <b>World</b>";
var div = document.createElement("div");
div.innerHTML = html;
alert(div.innerText); // Hello, World

That pretty much the best way of doing it, you're letting the browser do what it does best -- parse HTML.


Edit: As noted in the comments below, this is not the most cross-browser solution. The most cross-browser solution would be to recursively go through all the children of the element and concatenate all text nodes that you find. However, if you're using jQuery, it already does it for you:

alert($("<p>Hello, <b>World</b></p>").text());

Check out the text method.

Convert a string into an int

To convert an String number to an Int, you should do this:

let stringNumber = "5"
let number = Int(stringNumber)

Change auto increment starting number?

How to auto increment by one, starting at 10 in MySQL:

create table foobar(
  id             INT PRIMARY KEY AUTO_INCREMENT,
  moobar         VARCHAR(500)
); 
ALTER TABLE foobar AUTO_INCREMENT=10;

INSERT INTO foobar(moobar) values ("abc");
INSERT INTO foobar(moobar) values ("def");
INSERT INTO foobar(moobar) values ("xyz");

select * from foobar;

'10', 'abc'
'11', 'def'
'12', 'xyz'

This auto increments the id column by one starting at 10.

Auto increment in MySQL by 5, starting at 10:

drop table foobar
create table foobar(
  id             INT PRIMARY KEY AUTO_INCREMENT,
  moobar         VARCHAR(500)
); 
SET @@auto_increment_increment=5;
ALTER TABLE foobar AUTO_INCREMENT=10;

INSERT INTO foobar(moobar) values ("abc");
INSERT INTO foobar(moobar) values ("def");
INSERT INTO foobar(moobar) values ("xyz");

select * from foobar;
'11', 'abc'
'16', 'def'
'21', 'xyz'

This auto increments the id column by 5 each time, starting at 10.

What is the simplest way to convert a Java string from all caps (words separated by underscores) to CamelCase (no word separators)?

public String CamelCase(String str)
{
    String CamelCase="";
    String parts[] = str.split("_");
    for(String part:parts)
    {
        String as=part.toLowerCase();
        int a=as.length();
        CamelCase = CamelCase + as.substring(0, 1).toUpperCase()+ as.substring(1,a);    
    }
    return CamelCase;
}

This is the Simplest Program to convert into CamelCase. hope it Will Help You..

How to get the mysql table columns data type?

You can use the information_schema columns table:

SELECT DATA_TYPE FROM INFORMATION_SCHEMA.COLUMNS 
  WHERE table_name = 'tbl_name' AND COLUMN_NAME = 'col_name';

Compare 2 arrays which returns difference

use underscore as :

_.difference(array1,array2)

How do I update/upsert a document in Mongoose?

app.put('url', function(req, res) {

        // use our bear model to find the bear we want
        Bear.findById(req.params.bear_id, function(err, bear) {

            if (err)
                res.send(err);

            bear.name = req.body.name;  // update the bears info

            // save the bear
            bear.save(function(err) {
                if (err)
                    res.send(err);

                res.json({ message: 'Bear updated!' });
            });

        });
    });

Here is a better approach to solving the update method in mongoose, you can check Scotch.io for more details. This definitely worked for me!!!

'and' (boolean) vs '&' (bitwise) - Why difference in behavior with lists vs numpy arrays?

The short-circuiting boolean operators (and, or) can't be overriden because there is no satisfying way to do this without introducing new language features or sacrificing short circuiting. As you may or may not know, they evaluate the first operand for its truth value, and depending on that value, either evaluate and return the second argument, or don't evaluate the second argument and return the first:

something_true and x -> x
something_false and x -> something_false
something_true or x -> something_true
something_false or x -> x

Note that the (result of evaluating the) actual operand is returned, not truth value thereof.

The only way to customize their behavior is to override __nonzero__ (renamed to __bool__ in Python 3), so you can affect which operand gets returned, but not return something different. Lists (and other collections) are defined to be "truthy" when they contain anything at all, and "falsey" when they are empty.

NumPy arrays reject that notion: For the use cases they aim at, two different notions of truth are common: (1) Whether any element is true, and (2) whether all elements are true. Since these two are completely (and silently) incompatible, and neither is clearly more correct or more common, NumPy refuses to guess and requires you to explicitly use .any() or .all().

& and | (and not, by the way) can be fully overriden, as they don't short circuit. They can return anything at all when overriden, and NumPy makes good use of that to do element-wise operations, as they do with practically any other scalar operation. Lists, on the other hand, don't broadcast operations across their elements. Just as mylist1 - mylist2 doesn't mean anything and mylist1 + mylist2 means something completely different, there is no & operator for lists.

VBA equivalent to Excel's mod function

In vba the function is MOD. e.g

 5 MOD 2

Here is a useful link.

How to automatically generate N "distinct" colors?

This is trivial in MATLAB (there is an hsv command):

cmap = hsv(number_of_colors)

How to Convert Datetime to Date in dd/MM/yyyy format

You need to use convert in order by as well:

SELECT  Convert(varchar,A.InsertDate,103) as Tran_Date
order by Convert(varchar,A.InsertDate,103)

How to get subarray from array?

Take a look at Array.slice(begin, end)

_x000D_
_x000D_
const ar  = [1, 2, 3, 4, 5];

// slice from 1..3 - add 1 as the end index is not included

const ar2 = ar.slice(1, 3 + 1);

console.log(ar2);
_x000D_
_x000D_
_x000D_

How do I get an OAuth 2.0 authentication token in C#

Clearly:

Server side generating a token example

private string GenerateToken(string userName)
{
    var someClaims = new Claim[]{
        new Claim(JwtRegisteredClaimNames.UniqueName, userName),
        new Claim(JwtRegisteredClaimNames.Email, GetEmail(userName)),
        new Claim(JwtRegisteredClaimNames.NameId,Guid.NewGuid().ToString())
    };

    SecurityKey securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_settings.Tokenizer.Key));
    var token = new JwtSecurityToken(
        issuer: _settings.Tokenizer.Issuer,
        audience: _settings.Tokenizer.Audience,
        claims: someClaims,
        expires: DateTime.Now.AddHours(_settings.Tokenizer.ExpiryHours),
        signingCredentials: new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256)
    );

    return new JwtSecurityTokenHandler().WriteToken(token);
}

(note: Tokenizer is my helper class that contains Issuer Audience etc..)

Definitely:

Client side getting a token for authentication

    public async Task<string> GetToken()
    {
        string token = "";
        var siteSettings = DependencyResolver.Current.GetService<SiteSettings>();

        var client = new HttpClient();
        client.BaseAddress = new Uri(siteSettings.PopularSearchRequest.StaticApiUrl);
        client.DefaultRequestHeaders.Accept.Clear();
        //client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

        StatisticUserModel user = new StatisticUserModel()
        {
            Password = siteSettings.PopularSearchRequest.Password,
            Username = siteSettings.PopularSearchRequest.Username
        };

        string jsonUser = JsonConvert.SerializeObject(user, Formatting.Indented);
        var stringContent = new StringContent(jsonUser, Encoding.UTF8, "application/json");
        var response = await client.PostAsync(siteSettings.PopularSearchRequest.StaticApiUrl + "/api/token/new", stringContent);
        token = await response.Content.ReadAsStringAsync();

        return token;
    }

You can use this token for the authorization (that is in the subsequent requests)

Difference between Interceptor and Filter in Spring MVC

A HandlerInterceptor gives you more fine-grained control than a filter, because you have access to the actual target "handler" - this means that whatever action you perform can vary depending on what the request is actually doing (whereas the servlet filter is generically applied to all requests - only able to take into account the parameters of each request). The handlerInterceptor also provides 3 different methods, so that you can apply behavior prior to calling a handler, after the handler has completed but prior to view rendering (where you may even bypass view rendering altogether), or after the view itself has been rendered. Also, you can set up different interceptors for different groups of handlers - the interceptors are configured on the handlerMapping, and there may be multiple handlerMappings.

Therefore, if you have a need to do something completely generic (e.g. log all requests), then a filter is sufficient - but if the behavior depends on the target handler or you want to do something between the request handling and view rendering, then the HandlerInterceptor provides that flexibility.

Reference: http://static.springframework.org/sp...ng-interceptor

Highlight Bash/shell code in Markdown files

If you are looking to highlight a shell session command sequence as it looks to the user (with prompts, not just as contents of a hypothetical script file), then the right identifier to use at the moment is console:

```console
foo@bar:~$ whoami
foo
```

GitHub Markdown preview tab screenshot

How to play only the audio of a Youtube video using HTML 5?

_x000D_
_x000D_
var vid = "bpt84ceWAY0",_x000D_
    audio_streams = {},_x000D_
    audio_tag = document.getElementById('youtube');_x000D_
_x000D_
fetch("https://"+vid+"-focus-opensocial.googleusercontent.com/gadgets/proxy?container=none&url=https%3A%2F%2Fwww.youtube.com%2Fget_video_info%3Fvideo_id%3D" + vid).then(response => {_x000D_
    if (response.ok) {_x000D_
        response.text().then(data => {_x000D_
_x000D_
            var data = parse_str(data),_x000D_
                streams = (data.url_encoded_fmt_stream_map + ',' + data.adaptive_fmts).split(',');_x000D_
_x000D_
            streams.forEach(function(s, n) {_x000D_
                var stream = parse_str(s),_x000D_
                    itag = stream.itag * 1,_x000D_
                    quality = false;_x000D_
                console.log(stream);_x000D_
                switch (itag) {_x000D_
                    case 139:_x000D_
                        quality = "48kbps";_x000D_
                        break;_x000D_
                    case 140:_x000D_
                        quality = "128kbps";_x000D_
                        break;_x000D_
                    case 141:_x000D_
                        quality = "256kbps";_x000D_
                        break;_x000D_
                }_x000D_
                if (quality) audio_streams[quality] = stream.url;_x000D_
            });_x000D_
_x000D_
            console.log(audio_streams);_x000D_
_x000D_
            audio_tag.src = audio_streams['128kbps'];_x000D_
            audio_tag.play();_x000D_
        })_x000D_
    }_x000D_
});_x000D_
_x000D_
function parse_str(str) {_x000D_
    return str.split('&').reduce(function(params, param) {_x000D_
        var paramSplit = param.split('=').map(function(value) {_x000D_
            return decodeURIComponent(value.replace('+', ' '));_x000D_
        });_x000D_
        params[paramSplit[0]] = paramSplit[1];_x000D_
        return params;_x000D_
    }, {});_x000D_
}
_x000D_
<audio id="youtube" autoplay controls loop></audio>
_x000D_
_x000D_
_x000D_

How to clone object in C++ ? Or Is there another solution?

If your object is not polymorphic (and a stack implementation likely isn't), then as per other answers here, what you want is the copy constructor. Please note that there are differences between copy construction and assignment in C++; if you want both behaviors (and the default versions don't fit your needs), you'll have to implement both functions.

If your object is polymorphic, then slicing can be an issue and you might need to jump through some extra hoops to do proper copying. Sometimes people use as virtual method called clone() as a helper for polymorphic copying.

Finally, note that getting copying and assignment right, if you need to replace the default versions, is actually quite difficult. It is usually better to set up your objects (via RAII) in such a way that the default versions of copy/assign do what you want them to do. I highly recommend you look at Meyer's Effective C++, especially at items 10,11,12.

How to create a drop shadow only on one side of an element?

UPDATE 4

Same like update 3 but with modern css (=less rules) so that no special positioning on the pseudo element is required.

_x000D_
_x000D_
#box {_x000D_
    background-color: #3D6AA2;_x000D_
    width: 160px;_x000D_
    height: 90px;_x000D_
    position: absolute;_x000D_
    top: calc(10% - 10px);_x000D_
    left: calc(50% - 80px);_x000D_
}_x000D_
_x000D_
.box-shadow:after {_x000D_
    content:"";_x000D_
    position:absolute;_x000D_
    width:100%;_x000D_
    bottom:1px;_x000D_
    z-index:-1;_x000D_
    transform:scale(.9);_x000D_
    box-shadow: 0px 0px 8px 2px #000000;_x000D_
}
_x000D_
<div id="box" class="box-shadow"></div>
_x000D_
_x000D_
_x000D_

UPDATE 3

All my previous answers have been using extra markup to get create this effect, which is not necessarily needed. I think this a much cleaner solution... the only trick is playing around with the values to get the right positioning of the shadow as well as the right strength/opacity of the shadow. Here's a new fiddle, using pseudo-elements:

http://jsfiddle.net/UnsungHero97/ARRRZ/2/

HTML

<div id="box" class="box-shadow"></div>

CSS

#box {
    background-color: #3D6AA2;
    width: 160px;
    height: 90px;
    margin-top: -45px;
    margin-left: -80px;
    position: absolute;
    top: 50%;
    left: 50%;
}

.box-shadow:after {
    content: "";
    width: 150px;
    height: 1px;
    margin-top: 88px;
    margin-left: -75px;
    display: block;
    position: absolute;
    left: 50%;
    z-index: -1;
    -webkit-box-shadow: 0px 0px 8px 2px #000000;
       -moz-box-shadow: 0px 0px 8px 2px #000000;
            box-shadow: 0px 0px 8px 2px #000000;
}

UPDATE 2

Apparently, you can do this with just an extra parameter to the box-shadow CSS as everyone else just pointed out. Here's the demo:

http://jsfiddle.net/K88H9/821/

CSS

-webkit-box-shadow: 0 4px 4px -2px #000000;
   -moz-box-shadow: 0 4px 4px -2px #000000;
        box-shadow: 0 4px 4px -2px #000000;

This would be a better solution. The extra parameter that is added is described as:

The fourth length is a spread distance. Positive values cause the shadow shape to expand in all directions by the specified radius. Negative values cause the shadow shape to contract.

UPDATE

Check out the demo at jsFiddle: http://jsfiddle.net/K88H9/4/

What I did was create a "shadow element" that would hide behind the actual element that you would want to have a shadow. I made the width of the "shadow element" to be exactly less wide than the actual element by 2 times the shadow you specify; then I aligned it properly.

HTML

<div id="wrapper">
    <div id="element"></div>
    <div id="shadow"></div>
</div>

CSS

#wrapper {
    width: 84px;
    position: relative;
}
#element {
    background-color: #3D668F;
    height: 54px;
    width: 100%;
    position: relative;
    z-index: 10;
}
#shadow {
    background-color: #3D668F;
    height: 8px;
    width: 80px;
    margin-left: -40px;
    position: absolute;
    bottom: 0px;
    left: 50%;
    z-index: 5;
    -webkit-box-shadow: 0px 2px 4px #000000;
       -moz-box-shadow: 0px 2px 4px #000000;
            box-shadow: 0px 2px 4px #000000;
}

Original Answer

Yes, you can do this with the same syntax you have provided. The first value controls the horizontal positioning and the second value controls the vertical positioning. So just set the first value to 0px and the second to whatever offset you'd like as follows:

-webkit-box-shadow: 0px 5px #000000;
   -moz-box-shadow: 0px 5px #000000;
        box-shadow: 0px 5px #000000;

For more info on box shadows, check out these:

I hope this helps.

When to use MongoDB or other document oriented database systems?

Note that Mongo essentially stores JSON. If your app is dealing with a lot of JS Objects (with nesting) and you want to persist these objects then there is a very strong argument for using Mongo. It makes your DAL and MVC layers ultra thin, because they are not un-packaging all the JS object properties and trying to force-fit them into a structure (schema) that they don't naturally fit into.

We have a system that has several complex JS Objects at its heart, and we love Mongo because we can persist everything really, really easily. Our objects are also rather amorphous and unstructured, and Mongo soaks up that complication without blinking. We have a custom reporting layer that deciphers the amorphous data for human consumption, and that wasn't that difficult to develop.

How to update one file in a zip archive

You can use: zip -u file.zip path/file_to_update