Programs & Examples On #Google doodle

How do I get the type of a variable?

I'm not sure if my answer would help.

The short answer is, you don't really need/want to know the type of a variable to use it.

If you need to give a type to a static variable, then you may simply use auto.

In more sophisticated case where you want to use "auto" in a class or struct, I would suggest use template with decltype.

For example, say you are using someone else's library and it has a variable called "unknown_var" and you would want to put it in a vector or struct, you can totally do this:

template <typename T>
struct my_struct {
    int some_field;
    T my_data;
};
vector<decltype(unknown_var)> complex_vector;
vector<my_struct<decltype(unknown_var)> > simple_vector

Hope this helps.

EDIT: For good measure, here is the most complex case that I can think of: having a global variable of unknown type. In this case you would need c++14 and template variable.

Something like this:

template<typename T> vector<T> global_var;

void random_func (auto unknown_var) {
    global_var<decltype(unknown_var)>.push_back(unknown_var);
}

It's still a bit tedious but it's as close as you can get to typeless languages. Just make sure whenever you reference template variable, always put the template specification there.

how to remove multiple columns in r dataframe?

If you only want to remove columns 5 and 7 but not 6 try:

album2 <- album2[,-c(5,7)] #deletes columns 5 and 7

CSS - Expand float child DIV height to parent's height

I have recently done this on my website using jQuery. The code calculates the height of the tallest div and sets the other divs to the same height. Here's the technique:

http://www.broken-links.com/2009/01/20/very-quick-equal-height-columns-in-jquery/

I don't believe height:100% will work, so if you don't explicitly know the div heights I don't think there is a pure CSS solution.

How to embed PDF file with responsive width

If you're using Bootstrap 3, you can use the embed-responsive class and set the padding bottom as the height divided by the width plus a little extra for toolbars. For example, to display an 8.5 by 11 PDF, use 130% (11/8.5) plus a little extra (20%).

<div class='embed-responsive' style='padding-bottom:150%'>
    <object data='URL.pdf' type='application/pdf' width='100%' height='100%'></object>
</div>

Here's the Bootstrap CSS:

.embed-responsive {
    position: relative;
    display: block;
    height: 0;
    padding: 0;
    overflow: hidden;
}

What does %s and %d mean in printf in the C language?

The first argument denotes placeholders for the variables / parameters that follow.
For example, %s indicates that you're expecting a String to be your first print parameter.

Java also has a printf, which is very similar.

Android: How to handle right to left swipe gestures

I've been doing similar things, but for horizontal swipes only

import android.content.Context
import android.view.GestureDetector
import android.view.MotionEvent
import android.view.View

abstract class OnHorizontalSwipeListener(val context: Context) : View.OnTouchListener {    

    companion object {
         const val SWIPE_MIN = 50
         const val SWIPE_VELOCITY_MIN = 100
    }

    private val detector = GestureDetector(context, GestureListener())

    override fun onTouch(view: View, event: MotionEvent) = detector.onTouchEvent(event)    

    abstract fun onRightSwipe()

    abstract fun onLeftSwipe()

    private inner class GestureListener : GestureDetector.SimpleOnGestureListener() {    

        override fun onDown(e: MotionEvent) = true

        override fun onFling(e1: MotionEvent, e2: MotionEvent, velocityX: Float, velocityY: Float)
            : Boolean {

            val deltaY = e2.y - e1.y
            val deltaX = e2.x - e1.x

            if (Math.abs(deltaX) < Math.abs(deltaY)) return false

            if (Math.abs(deltaX) < SWIPE_MIN
                    && Math.abs(velocityX) < SWIPE_VELOCITY_MIN) return false

            if (deltaX > 0) onRightSwipe() else onLeftSwipe()

            return true
        }
    }
}

And then it can be used for view components

private fun listenHorizontalSwipe(view: View) {
    view.setOnTouchListener(object : OnHorizontalSwipeListener(context!!) {
            override fun onRightSwipe() {
                Log.d(TAG, "Swipe right")
            }

            override fun onLeftSwipe() {
                Log.d(TAG, "Swipe left")
            }

        }
    )
}

Downloading all maven dependencies to a directory NOT in repository?

The maven dependency plugin can potentially solve your problem.

If you have a pom with all your project dependencies specified, all you would need to do is run

mvn dependency:copy-dependencies

and you will find the target/dependencies folder filled with all the dependencies, including transitive.

Adding Gustavo's answer from below: To download the dependency sources, you can use

mvn dependency:copy-dependencies -Dclassifier=sources

(via Apache Maven Dependency Plugin doc).

How to gzip all files in all sub-directories into one compressed file in bash

tar -zcvf compressFileName.tar.gz folderToCompress

everything in folderToCompress will go to compressFileName

Edit: After review and comments I realized that people may get confused with compressFileName without an extension. If you want you can use .tar.gz extension(as suggested) with the compressFileName

Detect if a browser in a mobile device (iOS/Android phone/tablet) is used

Many mobile devices have resolutions so high that it's hard to distinguish between them and much larger screens. There are two ways to deal with this problem:

Use the following HTML code to scale the pixels (grouping smaller pixels into groups the size of the unit pixel - 96dpi, so px units will have the same physical size on all screens). Note that this will affect the scale of pretty much everything in your website, but this is generally the way to go when making sites mobile-friendly.

<meta name="viewport" content="width=device-width, initial-scale=1">

Alternatively, measuring the screen width in @media queries using cm instead of px units can tell you if you're dealing with a physically small screen regardless of resolution.

mysql.h file can't be found

You have to let the compiler know where the mysql.h file can be found. This can be done by giving the path to the header before compiling. In IDEs you have a setting where you can give these paths.

This link gives you more info on what options to use while compiling.

To your second problem You need to link the libraries. The linker needs to know where the library files are which has the implementation for the mysql functions that you use.

This link gives you more info on how to link libraries.

Rails ActiveRecord date between

there are several ways. You can use this method:

start = @selected_date.beginning_of_day
end = @selected_date.end_of_day
@comments = Comment.where("DATE(created_at) BETWEEN ? AND ?", start, end)

Or this:

@comments = Comment.where(:created_at => @selected_date.beginning_of_day..@selected_date.end_of_day)

jQuery Array of all selected checkboxes (by class)

You can use the :checkbox and :checked pseudo-selectors and the .class selector, with that you will make sure that you are getting the right elements, only checked checkboxes with the class you specify.

Then you can easily use the Traversing/map method to get an array of values:

var values = $('input:checkbox:checked.group1').map(function () {
  return this.value;
}).get(); // ["18", "55", "10"]

How can moment.js be imported with typescript?

Update

Apparently, moment now provides its own type definitions (according to sivabudh at least from 2.14.1 upwards), thus you do not need typings or @types at all.

import * as moment from 'moment' should load the type definitions provided with the npm package.

That said however, as said in moment/pull/3319#issuecomment-263752265 the moment team seems to have some issues in maintaining those definitions (they are still searching someone who maintains them).


You need to install moment typings without the --ambient flag.

Then include it using import * as moment from 'moment'

How to make Twitter Bootstrap tooltips have multiple lines?

You can use the html property: http://jsfiddle.net/UBr6c/

My <a href="#" title="This is a<br />test...<br />or not" class="my_tooltip">Tooltip</a> test.

$('.my_tooltip').tooltip({html: true})

Is there a CSS selector for elements containing certain text?

As of Jan 2021, there IS something that will do just this. :has() ... only one catch: this is not supported in any browser yet

Example: The following selector matches only elements that directly contain an child:

a:has(> img)

References:

https://developer.mozilla.org/en-US/docs/Web/CSS/:has

https://caniuse.com/?search=has

Convert Array to Object

For completeness, ECMAScript 2015(ES6) spreading. Will require either a transpiler(Babel) or an environment running at least ES6.

_x000D_
_x000D_
console.log(_x000D_
   { ...['a', 'b', 'c'] }_x000D_
)
_x000D_
_x000D_
_x000D_

Preprocessing in scikit learn - single sample - Depreciation warning

.values.reshape(-1,1) will be accepted without alerts/warnings

.reshape(-1,1) will be accepted, but with deprecation war

Fully change package name including company domain

This worked for me, from https://stackoverflow.com/a/18637004/127434

Another good method is: First create a new package with the desired name by right clicking on the java folder -> new -> package.

Then, select and drag all your classes to the new package. AndroidStudio will refactor the package name everywhere.

Finally, delete the old package.

Exit single-user mode

SSMS in general uses several connections to the database behind the scenes.

You will need to kill these connections before changing the access mode.

First, make sure the object explorer is pointed to a system database like master.

Second, execute a sp_who2 and find all the connections to database 'my_db'. Kill all the connections by doing KILL { session id } where session id is the SPID listed by sp_who2.

Third, open a new query window.

Execute the following code.

-- Start in master
USE MASTER;

-- Add users
ALTER DATABASE [my_db] SET MULTI_USER
GO

See my blog article on managing database files. This was written for moving files, but user management is the same.

Writing unit tests in Python: How do I start?

The free Python book Dive Into Python has a chapter on unit testing that you might find useful.

If you follow modern practices you should probably write the tests while you are writing your project, and not wait until your project is nearly finished.

Bit late now, but now you know for next time. :)

JOptionPane YES/No Options Confirm Dialog Box Issue

Try this,

int dialogButton = JOptionPane.YES_NO_OPTION;
int dialogResult = JOptionPane.showConfirmDialog(this, "Your Message", "Title on Box", dialogButton);
if(dialogResult == 0) {
  System.out.println("Yes option");
} else {
  System.out.println("No Option");
} 

Symbolicating iPhone App Crash Reports

In Xcode 4.2.1, open Organizer, then go to Library/Device Logs and drag your .crash file into the list of crash logs. It will be symbolicated for you after a few seconds.

Note that you must use the same instance of Xcode that the original build was archived on (i.e. the archive for your build must exist in Organizer).

React Js conditionally applying class attributes

Replace:

<div className="btn-group pull-right {this.props.showBulkActions ? 'show' : 'hidden'}">`

with:

<div className={`btn-group pull-right ${this.props.showBulkActions ? 'show' : 'hidden'}`}

Failed: Error in connection establishment: net::ERR_CONNECTION_REFUSED

CONNECTION_REFUSED is standard when the port is closed, but it could be rejected because SSL is failing authentication (one of a billion reasons). Did you configure SSL with Ratchet? (Apache is bypassed) Did you try without SSL in JavaScript?

I don't think Ratchet has built-in support for SSL. But even if it does you'll want to try the ws:// protocol first; it's a lot simpler, easier to debug, and closer to telnet. Chrome or the socket service may also be generating the REFUSED error if the service doesn't support SSL (because you explicitly requested SSL).

However the refused message is likely a server side problem, (usually port closed).

Best way to represent a Grid or Table in AngularJS with Bootstrap 3?

Adapt-Strap. Here is the fiddle.

It is extremely lightweight and has dynamic row heights.

<ad-table-lite table-name="carsForSale"
               column-definition="carsTableColumnDefinition"
               local-data-source="models.carsForSale"
               page-sizes="[7, 20]">
</ad-table-lite>

Delete multiple rows by selecting checkboxes using PHP

Delete Multiple checkbox using PHP Code

<input type="checkbox" name="chkbox[]  value=".$row[0]."/>
<input type="submit" name="delete" value="delete"/>
<?php
if(isset($_POST['delete']))
{
 $cnt=array();
 $cnt=count($_POST['chkbox']);
 for($i=0;$i<$cnt;$i++)
  {
     $del_id=$_POST['chkbox'][$i];
     $query="delete from $tablename where Id=".$del_id;
     mysql_query($query);
  }
}

Create PDF with Java

Another alternative would be JasperReports: JasperReports Library. It uses iText itself and is more than a PDF library you asked for, but if it fits your needs I'd go for it.

Simply put, it allows you to design reports that can be filled during runtime. If you use a custom datasource, you might be able to integrate JasperReports easily into the existing system. It would save you the whole layouting troubles, e.g. when invoices span over more sites where each side should have a footer and so on.

Case statement with multiple values in each 'when' block

Another nice way to put your logic in data is something like this:

# Initialization.
CAR_TYPES = {
  foo_type: ['honda', 'acura', 'mercedes'],
  bar_type: ['toyota', 'lexus']
  # More...
}
@type_for_name = {}
CAR_TYPES.each { |type, names| names.each { |name| @type_for_name[type] = name } }

case @type_for_name[car]
when :foo_type
  # do foo things
when :bar_type
  # do bar things
end

How to access environment variable values?

You can also try this

First, install python-decouple

pip install python-decouple

import it in your file

from decouple import config

Then get the env variable

SECRET_KEY=config('SECRET_KEY')

Read more about the python library here

How can you get the active users connected to a postgreSQL database via SQL?

Using balexandre's info:

SELECT usesysid, usename FROM pg_stat_activity;

How can I add private key to the distribution certificate?

"Valid Signing identity not found" This is because you don't have the private key for distribution certificate.

If the distribution certificate was created originally on a different Mac you may need to import this private key from that Mac. This private key is not available to download from your provisioning portal.

When you import the correct private key to your mac , XCode's organizer will recognize your already downloaded distribution profile as a "Valid profile"

However if you do not have access to the original Mac which created those profiles, the only option you have is revoking profiles.

Python: Maximum recursion depth exceeded

You can increment the stack depth allowed - with this, deeper recursive calls will be possible, like this:

import sys
sys.setrecursionlimit(10000) # 10000 is an example, try with different values

... But I'd advise you to first try to optimize your code, for instance, using iteration instead of recursion.

generate a random number between 1 and 10 in c

You need a different seed at every execution.

You can start to call at the beginning of your program:

srand(time(NULL));

Note that % 10 yields a result from 0 to 9 and not from 1 to 10: just add 1 to your % expression to get 1 to 10.

redirect while passing arguments

I'm a little confused. "foo.html" is just the name of your template. There's no inherent relationship between the route name "foo" and the template name "foo.html".

To achieve the goal of not rewriting logic code for two different routes, I would just define a function and call that for both routes. I wouldn't use redirect because that actually redirects the client/browser which requires them to load two pages instead of one just to save you some coding time - which seems mean :-P

So maybe:

def super_cool_logic():
    # execute common code here

@app.route("/foo")
def do_foo():
    # do some logic here
    super_cool_logic()
    return render_template("foo.html")

@app.route("/baz")
def do_baz():
    if some_condition:
        return render_template("baz.html")
    else:
        super_cool_logic()
        return render_template("foo.html", messages={"main":"Condition failed on page baz"})

I feel like I'm missing something though and there's a better way to achieve what you're trying to do (I'm not really sure what you're trying to do)

Is there a limit on how much JSON can hold?

The maximum length of JSON strings. The default is 2097152 characters, which is equivalent to 4 MB of Unicode string data.

Refer below URL

https://docs.microsoft.com/en-us/dotnet/api/system.web.script.serialization.javascriptserializer.maxjsonlength?view=netframework-4.7.2

Multiline strings in VB.NET

you can use XML for this like

dim vrstr as string = <s>
    some words
    some words
    some
    words
</s>

What's the difference between fill_parent and wrap_content?

fill_parent :

A component is arranged layout for the fill_parent will be mandatory to expand to fill the layout unit members, as much as possible in the space. This is consistent with the dockstyle property of the Windows control. A top set layout or control to fill_parent will force it to take up the entire screen.

wrap_content

Set up a view of the size of wrap_content will be forced to view is expanded to show all the content. The TextView and ImageView controls, for example, is set to wrap_content will display its entire internal text and image. Layout elements will change the size according to the content. Set up a view of the size of Autosize attribute wrap_content roughly equivalent to set a Windows control for True.

For details Please Check out this link : http://developer.android.com/reference/android/view/ViewGroup.LayoutParams.html

Prevent row names to be written to file when using write.csv

For completeness, write_csv() from the readr package is faster and never writes row names

# install.packages('readr', dependencies = TRUE)
library(readr)
write_csv(t, "t.csv")

If you need to write big data out, use fwrite() from the data.table package. It's much faster than both write.csv and write_csv

# install.packages('data.table')
library(data.table)
fwrite(t, "t.csv")

Below is a benchmark that Edouard published on his site

microbenchmark(write.csv(data, "baseR_file.csv", row.names = F),
               write_csv(data, "readr_file.csv"),
               fwrite(data, "datatable_file.csv"),
               times = 10, unit = "s")

## Unit: seconds
##                                              expr        min         lq       mean     median         uq        max neval
##  write.csv(data, "baseR_file.csv", row.names = F) 13.8066424 13.8248250 13.9118324 13.8776993 13.9269675 14.3241311    10
##                 write_csv(data, "readr_file.csv")  3.6742610  3.7999409  3.8572456  3.8690681  3.8991995  4.0637453    10
##                fwrite(data, "datatable_file.csv")  0.3976728  0.4014872  0.4097876  0.4061506  0.4159007  0.4355469    10

fast way to copy formatting in excel

For me, you can't. But if that suits your needs, you could have speed and formatting by copying the whole range at once, instead of looping:

range("B2:B5002").Copy Destination:=Sheets("Output").Cells(startrow, 2)

And, by the way, you can build a custom range string, like Range("B2:B4, B6, B11:B18")


edit: if your source is "sparse", can't you just format the destination at once when the copy is finished ?

How to use delimiter for csv in python

ok, here is what i understood from your question. You are writing a csv file from python but when you are opening that file into some other application like excel or open office they are showing the complete row in one cell rather than each word in individual cell. I am right??

if i am then please try this,

import csv

with open(r"C:\\test.csv", "wb") as csv_file:
    writer = csv.writer(csv_file, delimiter =",",quoting=csv.QUOTE_MINIMAL)
    writer.writerow(["a","b"])

you have to set the delimiter = ","

Trigger Change event when the Input value changed programmatically?

You are using jQuery, right? Separate JavaScript from HTML.

You can use trigger or triggerHandler.

var $myInput = $('#changeProgramatic').on('change', ChangeValue);

var anotherFunction = function() {
  $myInput.val('Another value');
  $myInput.trigger('change');
};

When to use static methods

Static methods are not associated with an instance, so they can not access any non-static fields in the class.

You would use a static method if the method does not use any fields (or only static fields) of a class.

If any non-static fields of a class are used you must use a non-static method.

How do I pass JavaScript variables to PHP?

PHP runs on the server before the page is sent to the user, JavaScript is run on the user's computer once it is received, so the PHP script has already executed.

If you want to pass a JavaScript value to a PHP script, you'd have to do an XMLHttpRequest to send the data back to the server.

Here's a previous question that you can follow for more information: Ajax Tutorial

Now if you just need to pass a form value to the server, you can also just do a normal form post, that does the same thing, but the whole page has to be refreshed.

<?php
if(isset($_POST))
{
  print_r($_POST);
}
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
  <input type="text" name="data" value="1" />
  <input type="submit" value="Submit" />
</form>

Clicking submit will submit the page, and print out the submitted data.

Solving "DLL load failed: %1 is not a valid Win32 application." for Pygame

It could be due to the architecture of your OS. Is your OS 64 Bit and have you installed 64 bit version of Python? It may help to install both 32 bit version Python 3.1 and Pygame, which is available officially only in 32 bit and you won't face this problem.

I see that 64 bit pygame is maintained here, you might also want to try uninstalling Pygame only and install the 64 bit version on your existing python3.1, if not choose go for both 32-bit version.

error::make_unique is not a member of ‘std’

If you have latest compiler, you can change the following in your build settings:

 C++ Language Dialect    C++14[-std=c++14]

This works for me.

android listview item height

You need to use padding on the list item layout so space is added on the edges of the item (just increasing the font size won't do that).

<?xml version="1.0" encoding="utf-8"?>
<TextView android:id="@+id/text1"
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content"
    android:padding="8dp" />

String.Replace ignoring case

Doesn't this work: I cant imaging anything else being much quicker or easier.

public static class ExtensionMethodsString
{
    public static string Replace(this String thisString, string oldValue, string newValue, StringComparison stringComparison)
    {
        string working = thisString;
        int index = working.IndexOf(oldValue, stringComparison);
        while (index != -1)
        {
            working = working.Remove(index, oldValue.Length);
            working = working.Insert(index, newValue);
            index = index + newValue.Length;
            index = working.IndexOf(oldValue, index, stringComparison);
        }
        return working;
    }
}

Python 3.4.0 with MySQL database

for fedora and python3 use: dnf install mysql-connector-python3

How to get my Android device Internal Download Folder path

if a device has an SD card, you use:

Environment.getExternalStorageState() 

if you don't have an SD card, you use:

Environment.getDataDirectory()

if there is no SD card, you can create your own directory on the device locally.

    //if there is no SD card, create new directory objects to make directory on device
        if (Environment.getExternalStorageState() == null) {
                        //create new file directory object
            directory = new File(Environment.getDataDirectory()
                    + "/RobotiumTestLog/");
            photoDirectory = new File(Environment.getDataDirectory()
                    + "/Robotium-Screenshots/");
            /*
             * this checks to see if there are any previous test photo files
             * if there are any photos, they are deleted for the sake of
             * memory
             */
            if (photoDirectory.exists()) {
                File[] dirFiles = photoDirectory.listFiles();
                if (dirFiles.length != 0) {
                    for (int ii = 0; ii <= dirFiles.length; ii++) {
                        dirFiles[ii].delete();
                    }
                }
            }
            // if no directory exists, create new directory
            if (!directory.exists()) {
                directory.mkdir();
            }

            // if phone DOES have sd card
        } else if (Environment.getExternalStorageState() != null) {
            // search for directory on SD card
            directory = new File(Environment.getExternalStorageDirectory()
                    + "/RobotiumTestLog/");
            photoDirectory = new File(
                    Environment.getExternalStorageDirectory()
                            + "/Robotium-Screenshots/");
            if (photoDirectory.exists()) {
                File[] dirFiles = photoDirectory.listFiles();
                if (dirFiles.length > 0) {
                    for (int ii = 0; ii < dirFiles.length; ii++) {
                        dirFiles[ii].delete();
                    }
                    dirFiles = null;
                }
            }
            // if no directory exists, create new directory to store test
            // results
            if (!directory.exists()) {
                directory.mkdir();
            }
        }// end of SD card checking

add permissions on your manifest.xml

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

Happy coding..

How to change the name of an iOS app?

For Xcode 10.2:

Although this question has many answers but I wanted to explain the whole concept in detail so that everyone can apply this knowledge to further or previous versions of Xcode too.

Every Xcode project consists of one or more targets. According to apple, A target specifies a product to build and contains the instructions for building the product from a set of files in a project or workspace. So every target is a product (app) on its own.

Steps to change the name:

Step 1: Go to the Targets and open the Info tab of the target whose name you want to change.

Step 2: View the Bundle name key under the Custom iOS Target Properties that is set to the default property of $(PRODUCT_NAME).

enter image description here

Step 3: You can either change the Bundle name directly (not recommended) or if you open the Build Settings tab then on searching for Product Name under Setting you will see that Product Name is set to $(TARGET_NAME).

enter image description here

Step 3A: You can change the Product Name or you can also change the Target Name by double clicking on the target.

enter image description here

So changing the Product Name (App Name) or Target Name both will result into similar results. But if you only want to change the App Name and want to keep using the same Target Name then only change the Product Name.

How to add empty spaces into MD markdown readme on GitHub?

Markdown really changes everything to html and html collapses spaces so you really can't do anything about it. You have to use the &nbsp; for it. A funny example here that I'm writing in markdown and I'll use couple of         here.

Above there are some &nbsp; without backticks

In Javascript, how do I check if an array has duplicate values?

If you have an ES2015 environment (as of this writing: io.js, IE11, Chrome, Firefox, WebKit nightly), then the following will work, and will be fast (viz. O(n)):

function hasDuplicates(array) {
    return (new Set(array)).size !== array.length;
}

If you only need string values in the array, the following will work:

function hasDuplicates(array) {
    var valuesSoFar = Object.create(null);
    for (var i = 0; i < array.length; ++i) {
        var value = array[i];
        if (value in valuesSoFar) {
            return true;
        }
        valuesSoFar[value] = true;
    }
    return false;
}

We use a "hash table" valuesSoFar whose keys are the values we've seen in the array so far. We do a lookup using in to see if that value has been spotted already; if so, we bail out of the loop and return true.


If you need a function that works for more than just string values, the following will work, but isn't as performant; it's O(n2) instead of O(n).

function hasDuplicates(array) {
    var valuesSoFar = [];
    for (var i = 0; i < array.length; ++i) {
        var value = array[i];
        if (valuesSoFar.indexOf(value) !== -1) {
            return true;
        }
        valuesSoFar.push(value);
    }
    return false;
}

The difference is simply that we use an array instead of a hash table for valuesSoFar, since JavaScript "hash tables" (i.e. objects) only have string keys. This means we lose the O(1) lookup time of in, instead getting an O(n) lookup time of indexOf.

How to trim white space from all elements in array?

In Java 8, Arrays.parallelSetAll seems ready made for this purpose:

import java.util.Arrays;

Arrays.parallelSetAll(array, (i) -> array[i].trim());

This will modify the original array in place, replacing each element with the result of the lambda expression.

Eclipse EGit Checkout conflict with files: - EGit doesn't want to continue

If error comes for ".settings/language.settings.xml" or any such file you don't need to git.

  1. Team -> Commit -> Staged filelist, check if unwanted file exists, -> Right click on each-> remove from index.
  2. From UnStaged filelist, check if unwanted file exists, -> Right click on each-> Ignore.

Now if Staged file list empty, and Unstaged file list all files are marked as Ignored. You can pull. Otherwise, follow other answers.

Column standard deviation R

Use colSds function from matrixStats library.

library(matrixStats)
set.seed(42)
M <- matrix(rnorm(40),ncol=4)
colSds(M)

[1] 0.8354488 1.6305844 1.1560580 1.1152688

Assignment inside lambda expression in Python

TL;DR: When using functional idioms it's better to write functional code

As many people have pointed out, in Python lambdas assignment is not allowed. In general when using functional idioms your better off thinking in a functional manner which means wherever possible no side effects and no assignments.

Here is functional solution which uses a lambda. I've assigned the lambda to fn for clarity (and because it got a little long-ish).

from operator import add
from itertools import ifilter, ifilterfalse
fn = lambda l, pred: add(list(ifilter(pred, iter(l))), [ifilterfalse(pred, iter(l)).next()])
objs = [Object(name=""), Object(name="fake_name"), Object(name="")]
fn(objs, lambda o: o.name != '')

You can also make this deal with iterators rather than lists by changing things around a little. You also have some different imports.

from itertools import chain, islice, ifilter, ifilterfalse
fn = lambda l, pred: chain(ifilter(pred, iter(l)), islice(ifilterfalse(pred, iter(l)), 1))

You can always reoganize the code to reduce the length of the statements.

AngularJS : Prevent error $digest already in progress when calling $scope.$apply()

When you get this error, it basically means that it's already in the process of updating your view. You really shouldn't need to call $apply() within your controller. If your view isn't updating as you would expect, and then you get this error after calling $apply(), it most likely means you're not updating the the model correctly. If you post some specifics, we could figure out the core problem.

Laravel - Eloquent or Fluent random row

Use Laravel function

ModelName::inRandomOrder()->first();

How to create a sticky footer that plays well with Bootstrap 3

Sticky footer solutions that rely upon fixed-height footers are falling out of favour in with responsive approaches (where the height of the footer often changes at different break points). The simplest responsive sticky footer solution I've seen involves using display: table on a top-level container, e.g.:

http://galengidman.com/2014/03/25/responsive-flexible-height-sticky-footers-in-css/

http://timothy-long.com/responsive-sticky-footer/

http://www.visualdecree.co.uk/posts/2013/12/17/responsive-sticky-footers/

Run local python script on remote server

It is possible using ssh. Python accepts hyphen(-) as argument to execute the standard input,

cat hello.py | ssh [email protected] python -

Run python --help for more info.

How do I replace a character at a particular index in JavaScript?

I know this is old but the solution does not work for negative index so I add a patch to it. hope it helps someone

String.prototype.replaceAt=function(index, character) {
    if(index>-1) return this.substr(0, index) + character + this.substr(index+character.length);
    else return this.substr(0, this.length+index) + character + this.substr(index+character.length);

}

How to find the first and second maximum number?

If you want the second highest number you can use

=LARGE(E4:E9;2)

although that doesn't account for duplicates so you could get the same result as the Max

If you want the largest number that is smaller than the maximum number you can use this version

=LARGE(E4:E9;COUNTIF(E4:E9;MAX(E4:E9))+1)

How to retry after exception?

The retrying package is a nice way to retry a block of code on failure.

For example:

@retry(wait_random_min=1000, wait_random_max=2000)
def wait_random_1_to_2_s():
    print("Randomly wait 1 to 2 seconds between retries")

Handling multiple IDs in jQuery

Solution:

To your secondary question

var elem1 = $('#elem1'),
    elem2 = $('#elem2'),
    elem3 = $('#elem3');

You can use the variable as the replacement of selector.

elem1.css({'display':'none'}); //will work

In the below case selector is already stored in a variable.

$(elem1,elem2,elem3).css({'display':'none'}); // will not work

React Native Border Radius with background color

Apply the below line of code :

<TextInput
  style={{ height: 40, width: "95%", borderColor: 'gray', borderWidth: 2, borderRadius: 20,  marginBottom: 20, fontSize: 18, backgroundColor: '#68a0cf' }}
  // Adding hint in TextInput using Placeholder option.
  placeholder=" Enter Your First Name"
  // Making the Under line Transparent.
  underlineColorAndroid="transparent"
/>

Alternative to iFrames with HTML5

You can use object and embed, like so:

<object data="http://www.web-source.net" width="600" height="400">
    <embed src="http://www.web-source.net" width="600" height="400"> </embed>
    Error: Embedded data could not be displayed.
</object>

Which isn't new, but still works. I'm not sure if it has the same functionality though.

How can I send an HTTP POST request to a server from Excel using VBA?

I did this before using the MSXML library and then using the XMLHttpRequest object, see here.

how to clear the screen in python

If you mean the screen where you have that interpreter prompt >>> you can do CTRL+L on Bash shell can help. Windows does not have equivalent. You can do

import os
os.system('cls')  # on windows

or

os.system('clear')  # on linux / os x

How to get content body from a httpclient call?

If you are not wanting to use async you can add .Result to force the code to execute synchronously:

private string GetResponseString(string text)
{
    var httpClient = new HttpClient();

    var parameters = new Dictionary<string, string>();
    parameters["text"] = text;

    var response = httpClient.PostAsync(BaseUri, new FormUrlEncodedContent(parameters)).Result;
    var contents = response.Content.ReadAsStringAsync().Result;

    return contents;
 }  

How to send HTML email using linux command line

The problem is that when redirecting a file into 'mail' like that, it's used for the message body only. Any headers you embed in the file will go into the body instead.

Try:

mail --append="Content-type: text/html" -s "Built notification" [email protected] < /var/www/report.csv

--append lets you add arbitrary headers to the mail, which is where you should specify the content-type and content-disposition. There's no need to embed the To and Subject headers in your file, or specify them with --append, since you're implicitly setting them on the command line already (-s is the subject, and [email protected] automatically becomes the To).

How do I use this JavaScript variable in HTML?

You don't "use" JavaScript variables in HTML. HTML is not a programming language, it's a markup language, it just "describes" what the page should look like.

If you want to display a variable on the screen, this is done with JavaScript.

First, you need somewhere for it to write to:

<body>
    <p id="output"></p>
</body>

Then you need to update your JavaScript code to write to that <p> tag. Make sure you do so after the page is ready.

<script>
window.onload = function(){
    var name = prompt("What's your name?");
    var lengthOfName = name.length

    document.getElementById('output').innerHTML = lengthOfName;
};
</script>

_x000D_
_x000D_
window.onload = function() {_x000D_
  var name = prompt("What's your name?");_x000D_
  var lengthOfName = name.length_x000D_
_x000D_
  document.getElementById('output').innerHTML = lengthOfName;_x000D_
};
_x000D_
<p id="output"></p>
_x000D_
_x000D_
_x000D_

How to replace NaN values by Zeroes in a column of a Pandas Dataframe?

To replace na values in pandas

df['column_name'].fillna(value_to_be_replaced,inplace=True)

if inplace = False, instead of updating the df (dataframe) it will return the modified values.

jQuery Scroll to bottom of page/iframe

The scripts mentioned in previous answers, like:

$("body, html").animate({
    scrollTop: $(document).height()
}, 400)

or

$(window).scrollTop($(document).height());

will not work in Chrome and will be jumpy in Safari in case html tag in CSS has overflow: auto; property set. It took me nearly an hour to figure out.

Access denied for user 'root'@'localhost' (using password: Yes) after password reset LINUX

You may need to clear the plugin column for your root account. On my fresh install, all of the root user accounts had unix_socket set in the plugin column. This was causing the root sql account to be locked only to the root unix account, since only system root could login via socket.

If you update user set plugin='' where User='root';flush privileges;, you should now be able to login to the root account from any localhost unix account (with a password).

See this AskUbuntu question and answer for more details.

Generating Random Passwords

Here Is what i put together quickly.

    public string GeneratePassword(int len)
    {
        string res = "";
        Random rnd = new Random();
        while (res.Length < len) res += (new Func<Random, string>((r) => {
            char c = (char)((r.Next(123) * DateTime.Now.Millisecond % 123)); 
            return (Char.IsLetterOrDigit(c)) ? c.ToString() : ""; 
        }))(rnd);
        return res;
    }

How to use npm with ASP.NET Core

I've found a better way how to manage JS packages in my project with NPM Gulp/Grunt task runners. I don't like the idea to have a NPM with another layer of javascript library to handle the "automation", and my number one requirement is to simple run the npm update without any other worries about to if I need to run gulp stuff, if it successfully copied everything and vice versa.

The NPM way:

  • The JS minifier is already bundled in the ASP.net core, look for bundleconfig.json so this is not an issue for me (not compiling something custom)
  • The good thing about NPM is that is have a good file structure so I can always find the pre-compiled/minified versions of the dependencies under the node_modules/module/dist
  • I'm using an NPM node_modules/.hooks/{eventname} script which is handling the copy/update/delete of the Project/wwwroot/lib/module/dist/.js files, you can find the documentation here https://docs.npmjs.com/misc/scripts (I'll update the script that I'm using to git once it'll be more polished) I don't need additional task runners (.js tools which I don't like) what keeps my project clean and simple.

The python way:

https://pypi.python.org/pyp... but in this case you need to maintain the sources manually

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

Well, data.str().c_str() yields a char const* but your function Printfunc() wants to have char*s. Based on the name, it doesn't change the arguments but merely prints them and/or uses them to name a file, in which case you should probably fix your declaration to be

void Printfunc(int a, char const* loc, char const* stream)

The alternative might be to turn the char const* into a char* but fixing the declaration is preferable:

Printfunc(num, addr, const_cast<char*>(data.str().c_str()));

Iterator invalidation rules

C++11 (Source: Iterator Invalidation Rules (C++0x))


Insertion

Sequence containers

  • vector: all iterators and references before the point of insertion are unaffected, unless the new container size is greater than the previous capacity (in which case all iterators and references are invalidated) [23.3.6.5/1]
  • deque: all iterators and references are invalidated, unless the inserted member is at an end (front or back) of the deque (in which case all iterators are invalidated, but references to elements are unaffected) [23.3.3.4/1]
  • list: all iterators and references unaffected [23.3.5.4/1]
  • forward_list: all iterators and references unaffected (applies to insert_after) [23.3.4.5/1]
  • array: (n/a)

Associative containers

  • [multi]{set,map}: all iterators and references unaffected [23.2.4/9]

Unsorted associative containers

  • unordered_[multi]{set,map}: all iterators invalidated when rehashing occurs, but references unaffected [23.2.5/8]. Rehashing does not occur if the insertion does not cause the container's size to exceed z * B where z is the maximum load factor and B the current number of buckets. [23.2.5/14]

Container adaptors

  • stack: inherited from underlying container
  • queue: inherited from underlying container
  • priority_queue: inherited from underlying container

Erasure

Sequence containers

  • vector: every iterator and reference at or after the point of erase is invalidated [23.3.6.5/3]
  • deque: erasing the last element invalidates only iterators and references to the erased elements and the past-the-end iterator; erasing the first element invalidates only iterators and references to the erased elements; erasing any other elements invalidates all iterators and references (including the past-the-end iterator) [23.3.3.4/4]
  • list: only the iterators and references to the erased element is invalidated [23.3.5.4/3]
  • forward_list: only the iterators and references to the erased element is invalidated (applies to erase_after) [23.3.4.5/1]
  • array: (n/a)

Associative containers

  • [multi]{set,map}: only iterators and references to the erased elements are invalidated [23.2.4/9]

Unordered associative containers

  • unordered_[multi]{set,map}: only iterators and references to the erased elements are invalidated [23.2.5/13]

Container adaptors

  • stack: inherited from underlying container
  • queue: inherited from underlying container
  • priority_queue: inherited from underlying container

Resizing

  • vector: as per insert/erase [23.3.6.5/12]
  • deque: as per insert/erase [23.3.3.3/3]
  • list: as per insert/erase [23.3.5.3/1]
  • forward_list: as per insert/erase [23.3.4.5/25]
  • array: (n/a)

Note 1

Unless otherwise specified (either explicitly or by defining a function in terms of other functions), invoking a container member function or passing a container as an argument to a library function shall not invalidate iterators to, or change the values of, objects within that container. [23.2.1/11]

Note 2

no swap() function invalidates any references, pointers, or iterators referring to the elements of the containers being swapped. [ Note: The end() iterator does not refer to any element, so it may be invalidated. —end note ] [23.2.1/10]

Note 3

Other than the above caveat regarding swap(), it's not clear whether "end" iterators are subject to the above listed per-container rules; you should assume, anyway, that they are.

Note 4

vector and all unordered associative containers support reserve(n) which guarantees that no automatic resizing will occur at least until the size of the container grows to n. Caution should be taken with unordered associative containers because a future proposal will allow the specification of a minimum load factor, which would allow rehashing to occur on insert after enough erase operations reduce the container size below the minimum; the guarantee should be considered potentially void after an erase.

How to create a inset box-shadow only on one side?

Quite a bit late, but a duplicate answer that doesn't require altering the padding or adding extra divs can be found here: Have an issue with box-shadow Inset bottom only. It says, "Use a negative value for the fourth length which defines the spread distance. This is often overlooked, but supported by all major browsers"

From the answerer's fiddle:

box-shadow: inset 0 -10px 10px -10px #000000;

How to upgrade Git on Windows to the latest version?

to check out your PATH variable, act as follow:

  1. From the Desktop, right-click My Computer and click Properties.
  2. Click Advanced System Settings link in the left column.
  3. In the System Properties window click the Environment Variables button.

Once there, scroll to get the Path row, you'll get a long string of paths (e.g. C:\windows\bin;C:\program files\git, etc)

Find the line or lines where git is referenced. Then, make sure this path point to your Git 1.8.x installation. If not, delete it and add the real path to the newest Git version. At the end, you should only have one path in the string linking to Git.

How to git commit a single file/directory

Try:

git commit -m 'my notes' path/to/my/file.ext 

How to import an Oracle database from dmp file and log file?

How was the database exported?

  • If it was exported using exp and a full schema was exported, then

    1. Create the user:

      create user <username> identified by <password> default tablespace <tablespacename> quota unlimited on <tablespacename>;
      
    2. Grant the rights:

      grant connect, create session, imp_full_database to <username>;
      
    3. Start the import with imp:

      imp <username>/<password>@<hostname> file=<filename>.dmp log=<filename>.log full=y;
      
  • If it was exported using expdp, then start the import with impdp:

    impdp <username>/<password> directory=<directoryname> dumpfile=<filename>.dmp logfile=<filename>.log full=y;
    

Looking at the error log, it seems you have not specified the directory, so Oracle tries to find the dmp file in the default directory (i.e., E:\app\Vensi\admin\oratest\dpdump\).

Either move the export file to the above path or create a directory object to pointing to the path where the dmp file is present and pass the object name to the impdp command above.

Getting hold of the outer class object from the inner class object

You could (but you shouldn't) use reflection for the job:

import java.lang.reflect.Field;

public class Outer {
    public class Inner {
    }

    public static void main(String[] args) throws Exception {

        // Create the inner instance
        Inner inner = new Outer().new Inner();

        // Get the implicit reference from the inner to the outer instance
        // ... make it accessible, as it has default visibility
        Field field = Inner.class.getDeclaredField("this$0");
        field.setAccessible(true);

        // Dereference and cast it
        Outer outer = (Outer) field.get(inner);
        System.out.println(outer);
    }
}

Of course, the name of the implicit reference is utterly unreliable, so as I said, you shouldn't :-)

How do I call Objective-C code from Swift?

Apple has provided official guide in this doc: how-to-call-objective-c-code-from-swift

Here is the relevant part:

To import a set of Objective-C files into Swift code within the same app target, you rely on an Objective-C bridging header file to expose those files to Swift. Xcode offers to create this header when you add a Swift file to an existing Objective-C app, or an Objective-C file to an existing Swift app.

If you accept, Xcode creates the bridging header file along with the file you were creating, and names it by using your product module name followed by "-Bridging-Header.h". Alternatively, you can create a bridging header yourself by choosing File > New > File > [operating system] > Source > Header File

Edit the bridging header to expose your Objective-C code to your Swift code:

  1. In your Objective-C bridging header, import every Objective-C header you want to expose to Swift.
  2. In Build Settings, in Swift Compiler - Code Generation, make sure the Objective-C Bridging Header build setting has a path to the bridging header file. The path should be relative to your project, similar to the way your Info.plist path is specified in Build Settings. In most cases, you won't need to modify this setting.

Any public Objective-C headers listed in the bridging header are visible to Swift.

Android app unable to start activity componentinfo

Your null pointer exception seems to be on this line:

String url = intent.getExtras().getString("userurl");

because intent.getExtras() returns null when the intent doesn't have any extras.

You have to realize that this piece of code:

Intent Main = new Intent(this, ToClass.class);
Main.putExtra("userurl", url);
startActivity(Main);

doesn't start the activity you wrote in Main.java, it will attempt to start an activity called ToClass and if that doesn't exist, your app crashes.

Also, there is no such thing as "android.intent.action.start" so the manifest should look more like:

<activity android:name=".start" android:label="@string/app_name">
    <intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>
</activity>
<activity android:name= ".Main">
</activity>

I hope this fixes some of the issues you are encountering but I strongly suggest you check out some "getting started" tutorials for android development and build up from there.

How can I split a text into sentences?

I had to read subtitles files and split them into sentences. After pre-processing (like removing time information etc in the .srt files), the variable fullFile contained the full text of the subtitle file. The below crude way neatly split them into sentences. Probably I was lucky that the sentences always ended (correctly) with a space. Try this first and if it has any exceptions, add more checks and balances.

# Very approximate way to split the text into sentences - Break after ? . and !
fullFile = re.sub("(\!|\?|\.) ","\\1<BRK>",fullFile)
sentences = fullFile.split("<BRK>");
sentFile = open("./sentences.out", "w+");
for line in sentences:
    sentFile.write (line);
    sentFile.write ("\n");
sentFile.close;

Oh! well. I now realize that since my content was Spanish, I did not have the issues of dealing with "Mr. Smith" etc. Still, if someone wants a quick and dirty parser...

SQL Server 2008 can't login with newly created user

Login to Server as Admin

Go To Security > Logins > New Login

Step 1:

Login Name : SomeName

Step 2:

Select  SQL Server / Windows Authentication.

More Info on, what is the differences between sql server authentication and windows authentication..?

Choose Default DB and Language of your choice

Click OK

Try to connect with the New User Credentials, It will prompt you to change the password. Change and login

OR

Try with query :

USE [master] -- Default DB
GO

CREATE LOGIN [Username] WITH PASSWORD=N'123456', DEFAULT_DATABASE=[master], DEFAULT_LANGUAGE=[us_english], CHECK_EXPIRATION=ON, CHECK_POLICY=ON
GO

--123456 is the Password And Username is Login User 
ALTER LOGIN [Username] enable -- Enable or to Disable User
GO

MySQL Cannot Add Foreign Key Constraint

I had same problem and the solution was very simple. Solution : foreign keys declared in table should not set to be not null.

reference : If you specify a SET NULL action, make sure that you have not declared the columns in the child table as NOT NULL. (ref )

React.js, wait for setState to finish before triggering a function?

setState takes new state and optional callback function which is called after the state has been updated.

this.setState(
  {newState: 'whatever'},
  () => {/*do something after the state has been updated*/}
)

CSS flexbox not working in IE10

IE10 has uses the old syntax. So:

display: -ms-flexbox; /* will work on IE10 */
display: flex; /* is new syntax, will not work on IE10 */

see css-tricks.com/snippets/css/a-guide-to-flexbox:

(tweener) means an odd unofficial syntax from [2012] (e.g. display: flexbox;)

Make the current Git branch a master branch

I found the answer I wanted in the blog post Replace the master branch with another branch in git:

git checkout feature_branch
git merge -s ours --no-commit master
git commit      # Add a message regarding the replacement that you just did
git checkout master
git merge feature_branch

It's essentially the same as Cascabel's answer. Except that the "option" he added below his solution is already embedded in my main code block.

It's easier to find this way.

I'm adding this as a new answer, because if I need this solution later, I want to have all the code I am going to use in one code block.

Otherwise, I may copy-paste, then read details below to see the line that I should have changed - after I already executed it.

Using NotNull Annotation in method argument

@Nullable and @NotNull do nothing on their own. They are supposed to act as Documentation tools.

The @Nullable Annotation reminds you about the necessity to introduce an NPE check when:

  1. Calling methods that can return null.
  2. Dereferencing variables (fields, local variables, parameters) that can be null.

The @NotNull Annotation is, actually, an explicit contract declaring the following:

  1. A method should not return null.
  2. A variable (like fields, local variables, and parameters) cannot should not hold null value.

For example, instead of writing:

/**
 * @param aX should not be null
 */
public void setX(final Object aX ) {
    // some code
}

You can use:

public void setX(@NotNull final Object aX ) {
    // some code
}

Additionally, @NotNull is often checked by ConstraintValidators (eg. in spring and hibernate).

The @NotNull annotation doesn't do any validation on its own because the annotation definition does not provide any ConstraintValidator type reference.

For more info see:

  1. Bean validation
  2. NotNull.java
  3. Constraint.java
  4. ConstraintValidator.java

How to parse XML using shellscript?

Do you have xml_grep installed? It's a perl based utility standard on some distributions (it came pre-installed on my CentOS system). Rather than giving it a regular expression, you give it an xpath expression.

Why are #ifndef and #define used in C++ header files?

Those are called #include guards.

Once the header is included, it checks if a unique value (in this case HEADERFILE_H) is defined. Then if it's not defined, it defines it and continues to the rest of the page.

When the code is included again, the first ifndef fails, resulting in a blank file.

That prevents double declaration of any identifiers such as types, enums and static variables.

Validating parameters to a Bash script

Not as bulletproof as the above answer, however still effective:

#!/bin/bash
if [ "$1" = "" ]
then
  echo "Usage: $0 <id number to be cleaned up>"
  exit
fi

# rm commands go here

Deserializing JSON data to C# using JSON.NET

Use

var rootObject =  JsonConvert.DeserializeObject<RootObject>(string json);

Create your classes on JSON 2 C#


Json.NET documentation: Serializing and Deserializing JSON with Json.NET

How to access URL segment(s) in blade in Laravel 5?

BASED ON LARAVEL 5.7 & ABOVE

To get all segments of current URL:

$current_uri = request()->segments();

To get segment posts from http://example.com/users/posts/latest/

NOTE: Segments are an array that starts at index 0. The first element of array starts after the TLD part of the url. So in the above url, segment(0) will be users and segment(1) will be posts.

//get segment 0
$segment_users = request()->segment(0); //returns 'users'
//get segment 1
$segment_posts = request()->segment(1); //returns 'posts'

You may have noted that the segment method only works with the current URL ( url()->current() ). So I designed a method to work with previous URL too by cloning the segment() method:

public function index()
{
    $prev_uri_segments = $this->prev_segments(url()->previous());
}

 /**
 * Get all of the segments for the previous uri.
 *
 * @return array
 */
public function prev_segments($uri)
{
    $segments = explode('/', str_replace(''.url('').'', '', $uri));

    return array_values(array_filter($segments, function ($value) {
        return $value !== '';
    }));
}

One line if/else condition in linux shell scripting

To summarize the other answers, for general use:

Multi-line if...then statement

if [ foo ]; then
    a; b
elif [ bar ]; then
    c; d
else
    e; f
fi

Single-line version

if [ foo ]; then a && b; elif [ bar ]; c && d; else e && f; fi

Using the OR operator

( foo && a && b ) || ( bar && c && d ) || e && f;

Notes

Remember that the AND and OR operators evaluate whether or not the result code of the previous operation was equal to true/success (0). So if a custom function returns something else (or nothing at all), you may run into problems with the AND/OR shorthand. In such cases, you may want to replace something like ( a && b ) with ( [ a == 'EXPECTEDRESULT' ] && b ), etc.

Also note that ( and [ are technically commands, so whitespace is required around them.

Instead of a group of && statements like then a && b; else, you could also run statements in a subshell like then $( a; b ); else, though this is less efficient. The same is true for doing something like result1=$( foo; a; b ); result2=$( bar; c; d ); [ "$result1" -o "$result2" ] instead of ( foo && a && b ) || ( bar && c && d ). Though at that point you'd be getting more into less-compact, multi-line stuff anyway.

How to get primary key of table?

You should use PRIMARY from key_column_usage.constraint_name = "PRIMARY"

sample query,

SELECT k.column_name as PK, concat(tbl.TABLE_SCHEMA, '.`', tbl.TABLE_NAME, '`') as TABLE_NAME
FROM information_schema.TABLES tbl
JOIN information_schema.key_column_usage k on k.table_name = tbl.table_name
WHERE k.constraint_name='PRIMARY'
  AND tbl.table_schema='MYDB'
  AND tbl.table_type="BASE TABLE";

Passing an array of data as an input parameter to an Oracle procedure

This is one way to do it:

SQL> set serveroutput on
SQL> CREATE OR REPLACE TYPE MyType AS VARRAY(200) OF VARCHAR2(50);
  2  /

Type created

SQL> CREATE OR REPLACE PROCEDURE testing (t_in MyType) IS
  2  BEGIN
  3    FOR i IN 1..t_in.count LOOP
  4      dbms_output.put_line(t_in(i));
  5    END LOOP;
  6  END;
  7  /

Procedure created

SQL> DECLARE
  2    v_t MyType;
  3  BEGIN
  4    v_t := MyType();
  5    v_t.EXTEND(10);
  6    v_t(1) := 'this is a test';
  7    v_t(2) := 'A second test line';
  8    testing(v_t);
  9  END;
 10  /

this is a test
A second test line

To expand on my comment to @dcp's answer, here's how you could implement the solution proposed there if you wanted to use an associative array:

SQL> CREATE OR REPLACE PACKAGE p IS
  2    TYPE p_type IS TABLE OF VARCHAR2(50) INDEX BY BINARY_INTEGER;
  3  
  4    PROCEDURE pp (inp p_type);
  5  END p;
  6  /

Package created
SQL> CREATE OR REPLACE PACKAGE BODY p IS
  2    PROCEDURE pp (inp p_type) IS
  3    BEGIN
  4      FOR i IN 1..inp.count LOOP
  5        dbms_output.put_line(inp(i));
  6      END LOOP;
  7    END pp;
  8  END p;
  9  /

Package body created
SQL> DECLARE
  2    v_t p.p_type;
  3  BEGIN
  4    v_t(1) := 'this is a test of p';
  5    v_t(2) := 'A second test line for p';
  6    p.pp(v_t);
  7  END;
  8  /

this is a test of p
A second test line for p

PL/SQL procedure successfully completed

SQL> 

This trades creating a standalone Oracle TYPE (which cannot be an associative array) with requiring the definition of a package that can be seen by all in order that the TYPE it defines there can be used by all.

Convert string to Color in C#

(It would really have been nice if you'd mentioned which Color type you were interested in to start with...)

One simple way of doing this is to just build up a dictionary via reflection:

public static class Colors
{
    private static readonly Dictionary<string, Color> dictionary =
        typeof(Color).GetProperties(BindingFlags.Public | 
                                    BindingFlags.Static)
                     .Where(prop => prop.PropertyType == typeof(Color))
                     .ToDictionary(prop => prop.Name,
                                   prop => (Color) prop.GetValue(null, null)));

    public static Color FromName(string name)
    {
        // Adjust behaviour for lookup failure etc
        return dictionary[name];
    }
}

That will be relatively slow for the first lookup (while it uses reflection to find all the properties) but should be very quick after that.

If you want it to be case-insensitive, you can pass in something like StringComparer.OrdinalIgnoreCase as an extra argument in the ToDictionary call. You can easily add TryParse etc methods should you wish.

Of course, if you only need this in one place, don't bother with a separate class etc :)

Defining a `required` field in Bootstrap

If wont work in case you have something like : novalidate="novalidate" attached to your form.

On a CSS hover event, can I change another div's styling?

Yes, you can do that, but only if #b is after #a in the HTML.

If #b comes immediately after #a: http://jsfiddle.net/u7tYE/

#a:hover + #b {
    background: #ccc
}

<div id="a">Div A</div>
<div id="b">Div B</div>

That's using the adjacent sibling combinator (+).

If there are other elements between #a and #b, you can use this: http://jsfiddle.net/u7tYE/1/

#a:hover ~ #b {
    background: #ccc
}

<div id="a">Div A</div>
<div>random other elements</div>
<div>random other elements</div>
<div>random other elements</div>
<div id="b">Div B</div>

That's using the general sibling combinator (~).

Both + and ~ work in all modern browsers and IE7+

If #b is a descendant of #a, you can simply use #a:hover #b.

ALTERNATIVE: You can use pure CSS to do this by positioning the second element before the first. The first div is first in markup, but positioned to the right or below the second. It will work as if it were a previous sibling.

Perl regular expression (using a variable as a search string with Perl operator characters included)

Use \Q to autoescape any potentially problematic characters in your variable.

if($text_to_search =~ m/\Q$search_string/) print "wee";

Launching Google Maps Directions via an intent on Android

You can Launch Google Maps Directions via an intent on Android through this way

btn_search_route.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            String source = et_source.getText().toString();
            String destination = et_destination.getText().toString();

            if (TextUtils.isEmpty(source)) {
                et_source.setError("Enter Soruce point");
            } else if (TextUtils.isEmpty(destination)) {
                et_destination.setError("Enter Destination Point");
            } else {
                String sendstring="http://maps.google.com/maps?saddr=" +
                        source +
                        "&daddr=" +
                        destination;
                Intent intent = new Intent(android.content.Intent.ACTION_VIEW,
                        Uri.parse(sendstring));
                startActivity(intent);
            }
        }

    });

CSS 3 slide-in from left transition

You can use CSS3 transitions or maybe CSS3 animations to slide in an element.

For browser support: http://caniuse.com/

I made two quick examples just to show you how I mean.

CSS transition (on hover)

Demo One

Relevant Code

.wrapper:hover #slide {
    transition: 1s;
    left: 0;
}

In this case, Im just transitioning the position from left: -100px; to 0; with a 1s. duration. It's also possible to move the element using transform: translate();

CSS animation

Demo Two

#slide {
    position: absolute;
    left: -100px;
    width: 100px;
    height: 100px;
    background: blue;
    -webkit-animation: slide 0.5s forwards;
    -webkit-animation-delay: 2s;
    animation: slide 0.5s forwards;
    animation-delay: 2s;
}

@-webkit-keyframes slide {
    100% { left: 0; }
}

@keyframes slide {
    100% { left: 0; }
}

Same principle as above (Demo One), but the animation starts automatically after 2s, and in this case I've set animation-fill-mode to forwards, which will persist the end state, keeping the div visible when the animation ends.

Like I said, two quick example to show you how it could be done.

EDIT: For details regarding CSS Animations and Transitions see:

Animations

https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Using_CSS_animations

Transitions

https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Using_CSS_transitions

Hope this helped.

Undefined Symbols for architecture x86_64: Compiling problems

There's no mystery here, the linker is telling you that you haven't defined the missing symbols, and you haven't.

Similarity::Similarity() or Similarity::~Similarity() are just missing and you have defined the others incorrectly,

void Similarity::readData(Scanner& inStream){
}

not

void readData(Scanner& inStream){
}

etc. etc.

The second one is a function called readData, only the first is the readData method of the Similarity class.

To be clear about this, in Similarity.h

void readData(Scanner& inStream);

but in Similarity.cpp

void Similarity::readData(Scanner& inStream){
}

How to have stored properties in Swift, the same way I had on Objective-C?

You can't define categories (Swift extensions) with new storage; any additional properties must be computed rather than stored. The syntax works for Objective C because @property in a category essentially means "I'll provide the getter and setter". In Swift, you'll need to define these yourself to get a computed property; something like:

extension String {
    public var Foo : String {
        get
        {
            return "Foo"
        }

        set
        {
            // What do you want to do here?
        }
    }
}

Should work fine. Remember, you can't store new values in the setter, only work with the existing available class state.

Reset push notification settings for app

I agree with micmdk.. I had a development environment setup with Push Notifications and needed a way to reset my phone to look like an initial install… and only these precise steps worked for me… requires TWO reboots of Device:

From APPLE TECH DOC:

Resetting the Push Notifications Permissions Alert on iOS The first time a push-enabled app registers for push notifications, iOS asks the user if they wish to receive notifications for that app. Once the user has responded to this alert it is not presented again unless the device is restored or the app has been uninstalled for at least a day.

If you want to simulate a first-time run of your app, you can leave the app uninstalled for a day. You can achieve the latter without actually waiting a day by following these steps:

  1. Delete your app from the device.

  2. Turn the device off completely and turn it back on.

  3. Go to Settings > General > Date & Time and set the date ahead a day or more.

  4. Turn the device off completely again and turn it back on.

How to add System.Windows.Interactivity to project?

Alternative solution is to modify your current Visual Studio installation in the Visual Studio Installer

Win+R %ProgramFiles(x86)%\Microsoft Visual Studio\Installer\vs_installer.exe

adding the Blend for Visual Studio SDK for .NET 'Individual component' under 'SDKs, libraries, and frameworks':

enter image description here after adding this component System.Windows.Interactivity should appear in its regular location Add Reference/Assemblies/Extensions.


It appears this would only work for VS2017 or earlier. For later versions, please refer to other answers.

How do pointer-to-pointer's work in C? (and when might you use them?)

I like this "real world" code example of pointer to pointer usage, in Git 2.0, commit 7b1004b:

Linus once said:

I actually wish more people understood the really core low-level kind of coding. Not big, complex stuff like the lockless name lookup, but simply good use of pointers-to-pointers etc.
For example, I've seen too many people who delete a singly-linked list entry by keeping track of the "prev" entry, and then to delete the entry, doing something like:


   if (prev)
     prev->next = entry->next;
   else
     list_head = entry->next;

and whenever I see code like that, I just go "This person doesn't understand pointers". And it's sadly quite common.

People who understand pointers just use a "pointer to the entry pointer", and initialize that with the address of the list_head. And then as they traverse the list, they can remove the entry without using any conditionals, by just doing a

*pp =  entry->next

pointers

Applying that simplification lets us lose 7 lines from this function even while adding 2 lines of comment.

- struct combine_diff_path *p, *pprev, *ptmp;
+ struct combine_diff_path *p, **tail = &curr;

Chris points out in the comments to the 2016 video "Linus Torvalds's Double Pointer Problem".


kumar points out in the comments the blog post "Linus on Understanding Pointers", where Grisha Trubetskoy explains:

Imagine you have a linked list defined as:

   typedef struct list_entry {
       int val;
       struct list_entry *next;
   } list_entry;

You need to iterate over it from the beginning to end and remove a specific element whose value equals the value of to_remove.
The more obvious way to do this would be:

   list_entry *entry = head; /* assuming head exists and is the first entry of the list */
   list_entry *prev = NULL;
   
   while (entry) { /* line 4 */
       if (entry->val == to_remove)     /* this is the one to remove ; line 5 */
           if (prev)
              prev->next = entry->next; /* remove the entry ; line 7 */
           else
               head = entry->next;      /* special case - first entry ; line 9 */
   
       /* move on to the next entry */
       prev = entry;
       entry = entry->next;
   }

What we are doing above is:

  • iterating over the list until entry is NULL, which means we’ve reached the end of the list (line 4).
  • When we come across an entry we want removed (line 5),
  • we assign the value of current next pointer to the previous one,
  • thus eliminating the current element (line 7).

There is a special case above - at the beginning of the iteration there is no previous entry (prev is NULL), and so to remove the first entry in the list you have to modify head itself (line 9).

What Linus was saying is that the above code could be simplified by making the previous element a pointer to a pointer rather than just a pointer.
The code then looks like this:

   list_entry **pp = &head; /* pointer to a pointer */
   list_entry *entry = head;

   while (entry) {
       if (entry->val == to_remove)
           *pp = entry->next;
       else
            pp = &entry->next;
       entry = entry->next;
   }

The above code is very similar to the previous variant, but notice how we no longer need to watch for the special case of the first element of the list, since pp is not NULL at the beginning. Simple and clever.

Also, someone in that thread commented that the reason this is better is because *pp = entry->next is atomic. It is most certainly NOT atomic.
The above expression contains two dereference operators (* and ->) and one assignment, and neither of those three things is atomic.
This is a common misconception, but alas pretty much nothing in C should ever be assumed to be atomic (including the ++ and -- operators)!

Use string in switch case in java

We can apply Switch just on data type compatible int :short,Shor,byte,Byte,int,Integer,char,Character or enum type.

Visual Studio 2013 error MS8020 Build tools v140 cannot be found

That's the platform toolset for VS2015. You uninstalled it, therefore it is no longer available.

To change your Platform Toolset:

  1. Right click your project, go to Properties.
  2. Under Configuration Properties, go to General.
  3. Change your Platform Toolset to one of the available ones.

How can I split and parse a string in Python?

"2.7.0_bf4fda703454".split("_") gives a list of strings:

In [1]: "2.7.0_bf4fda703454".split("_")
Out[1]: ['2.7.0', 'bf4fda703454']

This splits the string at every underscore. If you want it to stop after the first split, use "2.7.0_bf4fda703454".split("_", 1).

If you know for a fact that the string contains an underscore, you can even unpack the LHS and RHS into separate variables:

In [8]: lhs, rhs = "2.7.0_bf4fda703454".split("_", 1)

In [9]: lhs
Out[9]: '2.7.0'

In [10]: rhs
Out[10]: 'bf4fda703454'

An alternative is to use partition(). The usage is similar to the last example, except that it returns three components instead of two. The principal advantage is that this method doesn't fail if the string doesn't contain the separator.

Cygwin - Makefile-error: recipe for target `main.o' failed

You see the two empty -D entries in the g++ command line? They're causing the problem. You must have values in the -D items e.g. -DWIN32

if you're insistent on using something like -D$(SYSTEM) -D$(ENVIRONMENT) then you can use something like:

SYSTEM ?= generic
ENVIRONMENT ?= generic

in the makefile which gives them default values.

Your output looks to be missing the all important output:

<command-line>:0:1: error: macro names must be identifiers
<command-line>:0:1: error: macro names must be identifiers

just to clarify, what actually got sent to g++ was -D -DWindows_NT, i.e. define a preprocessor macro called -DWindows_NT; which is of course not a valid identifier (similarly for -D -I.)

MySQL : transaction within a stored procedure

Just an alternative to the code by rkosegi,

BEGIN

    .. Declare statements ..

    DECLARE EXIT HANDLER FOR SQLEXCEPTION 
    BEGIN
          .. set any flags etc  eg. SET @flag = 0; ..
          ROLLBACK;
    END;

    START TRANSACTION;

        .. Query 1 ..
        .. Query 2 ..
        .. Query 3 ..

    COMMIT;
    .. eg. SET @flag = 1; ..

END

error: Unable to find vcvarsall.bat

You can use easy_install instead of pip it works for me.

How to check if mod_rewrite is enabled in php?

Another idea, indeed more a dirty hack, regarding mod rewrite is server dependend an not necessary a php issue: Why not, if you have the possibillity, create a test directory put a .htaccess in it rewriting to test.php, call the directory via http and check if you get the expected result you put in test.php.

Indeed, dirty.

How to access static resources when mapping a global front controller servlet on /*

I'd recommend trying to use a Filter instead of a default servlet whenever possible.

Other two possibilities:

Write a FileServlet yourself. You'll find plenty examples, it should just open the file by URL and write its contents into output stream. Then, use it to serve static file request.

Instantiate a FileServlet class used by Google App Engine and call service(request, response) on that FileServlet when you need to serve the static file at a given URL.

You can map /res/* to YourFileServlet or whatever to exclude it from DispatcherServlets' handling, or call it directly from DispatcherServlet.

And, I have to ask, what does Spring documentation say about this collision? I've never used it.

How to restart a node.js server

During development the best way to restart server for seeing changes made is to use nodemon

npm install nodemon -g

nodemon [your app name]

nodemon will watch the files in the directory that nodemon was started, and if they change, it will automatically restart your node application.

Check nodemon git repo: https://github.com/remy/nodemon

Add a list item through javascript

I was recently presented with this same challenge and stumbled on this thread but found a simpler solution using append...

var firstname = $('#firstname').val();

$('ol').append( '<li>' + firstname + '</li>' );

Store the firstname value and then use append to add that value as an li to the ol. I hope this helps :)

How to implement infinity in Java?

The Double and Float types have the POSITIVE_INFINITY constant.

Google OAUTH: The redirect URI in the request did not match a registered redirect URI

I was able to get mine working using the following Client Credentials:

Authorized JavaScript origins

http://localhost

Authorized redirect URIs

http://localhost:8090/oauth2callback

Note: I used port 8090 instead of 8080, but that doesn't matter as long as your python script uses the same port as your client_secret.json file.

Reference: Python Quickstart

Error: Cannot access file bin/Debug/... because it is being used by another process

I understand this is an old question. Unfortunately I was facing the same issue with my .net core 2.0 application in visual studio 2017. So, I thought of sharing the solution which worked for me. Before this solution I had tried the below steps.

  1. Restarted visual studio
  2. Closed all the application
  3. Clean my solution and rebuild

None of the above steps didn't fix the issue.

And then I opened my Task Manager and selected dotnet process and then clicked End task button. Later I opened my Visual Studio and everything was working fine.

enter image description here

span with onclick event inside a tag

Fnd the answer.

I have use some styles inorder to achive this.

<span 
   class="pseudolink" 
   onclick="location='https://jsfiddle.net/'">
Go TO URL
</span>

.pseudolink { 
   color:blue; 
   text-decoration:underline; 
   cursor:pointer; 
   }

https://jsfiddle.net/mafais/bys46d5w/

TypeError: 'float' object is not subscriptable

It looks like you are trying to set elements 0 through 11 of PriceList to new values. The syntax would usually look like this:

prompt = "What would you like the new price for all standard pizzas to be? "
PizzaChange = float(input(prompt))
for i in [0, 1, 2, 3, 4, 5, 6]: PriceList[i] = PizzaChange
for i in [7, 8, 9, 10, 11]: PriceList[i] = PizzaChange + 3

If they are always consecutive ranges, then it's even simpler to write:

prompt = "What would you like the new price for all standard pizzas to be? "
PizzaChange = float(input(prompt))
for i in range(0, 7): PriceList[i] = PizzaChange
for i in range(7, 12): PriceList[i] = PizzaChange + 3

For reference, PriceList[0][1][2][3][4][5][6] refers to "Element 6 of element 5 of element 4 of element 3 of element 2 of element 1 of element 0 of PriceList. Put another way, it's the same as ((((((PriceList[0])[1])[2])[3])[4])[5])[6].

How to make a div with no content have a width?

Either use padding , height or &nbsp for width to take effect with empty div

EDIT:

Non zero min-height also works great

How to include clean target in Makefile?

In makefile language $@ means "name of the target", so rm -f $@ translates to rm -f clean.

You need to specify to rm what exactly you want to delete, like rm -f *.o code1 code2

PHP - Getting the index of a element from a array

PHP arrays are both integer-indexed and string-indexed. You can even mix them:

array('red', 'green', 'white', 'color3'=>'blue', 3=>'yellow');

What do you want the index to be for the value 'blue'? Is it 3? But that's actually the index of the value 'yellow', so that would be an ambiguity.

Another solution for you is to coerce the array to an integer-indexed list of values.

foreach (array_values($array) as $i => $value) {
  echo "$i: $value\n";
}

Output:

0: red
1: green
2: white
3: blue
4: yellow

How to format strings in Java

public class StringFormat {

    public static void main(String[] args) {
            Scanner sc=new Scanner(System.in);
            System.out.println("================================");
            for(int i=0;i<3;i++){
                String s1=sc.next();
                int x=sc.nextInt();
                System.out.println(String.format("%-15s%03d",s1,x));
            }
            System.out.println("================================");

    }
}

outpot "================================"
ved15space123 ved15space123 ved15space123 "================================

Java solution

  • The "-" is used to left indent

  • The "15" makes the String's minimum length it takes up be 15

  • The "s" (which is a few characters after %) will be substituted by our String
  • The 0 pads our integer with 0s on the left
  • The 3 makes our integer be a minimum length of 3

@JsonProperty annotation on field as well as getter/setter

In addition to existing good answers, note that Jackson 1.9 improved handling by adding "property unification", meaning that ALL annotations from difference parts of a logical property are combined, using (hopefully) intuitive precedence.

In Jackson 1.8 and prior, only field and getter annotations were used when determining what and how to serialize (writing JSON); and only and setter annotations for deserialization (reading JSON). This sometimes required addition of "extra" annotations, like annotating both getter and setter.

With Jackson 1.9 and above these extra annotations are NOT needed. It is still possible to add those; and if different names are used, one can create "split" properties (serializing using one name, deserializing using other): this is occasionally useful for sort of renaming.

Pandas: Setting no. of max rows

Set display.max_rows:

pd.set_option('display.max_rows', 500)

For older versions of pandas (<=0.11.0) you need to change both display.height and display.max_rows.

pd.set_option('display.height', 500)
pd.set_option('display.max_rows', 500)

See also pd.describe_option('display').

You can set an option only temporarily for this one time like this:

from IPython.display import display
with pd.option_context('display.max_rows', 100, 'display.max_columns', 10):
    display(df) #need display to show the dataframe when using with in jupyter
    #some pandas stuff

You can also reset an option back to its default value like this:

pd.reset_option('display.max_rows')

And reset all of them back:

pd.reset_option('all')

Copy directory to another directory using ADD command

Indeed ADD go /usr/local/ will add content of go folder and not the folder itself, you can use Thomasleveil solution or if that did not work for some reason you can change WORKDIR to /usr/local/ then add your directory to it like:

WORKDIR /usr/local/
COPY go go/

or

WORKDIR /usr/local/go
COPY go ./

But if you want to add multiple folders, it will be annoying to add them like that, the only solution for now as I see it from my current issue is using COPY . . and exclude all unwanted directories and files in .dockerignore, let's say I got folders and files:

- src 
- tmp 
- dist 
- assets 
- go 
- justforfun 
- node_modules 
- scripts 
- .dockerignore 
- Dockerfile 
- headache.lock 
- package.json 

and I want to add src assets package.json justforfun go so:

in Dockerfile:

FROM galaxy:latest

WORKDIR /usr/local/
COPY . .

in .dockerignore file:

node_modules
headache.lock
tmp
dist

Or for more fun (or you like to confuse more people make them suffer as well :P) can be:

*
!src 
!assets 
!go 
!justforfun 
!scripts 
!package.json 

In this way you ignore everything, but excluding what you want to be copied or added only from "ignore list".

It is a late answer but adding more ways to do the same covering even more cases.

Undo git pull, how to bring repos to old state

If there is a failed merge, which is the most common reason for wanting to undo a git pull, running git reset --merge does exactly what one would expect: keep the fetched files, but undo the merge that git pull attempted to merge. Then one can decide what to do without the clutter that git merge sometimes generates. And it does not need one to find the exact commit ID which --hard mentioned in every other answer requires.

How does one remove a Docker image?

In my case the probleme is that I have tow images withe same name the solution is to add the tag after the name or the id

sudo docker rmi <NAME>:<TAG>

ex:

sudo docker rmi php:7.0.4-fpm

How do you parse and process HTML/XML in PHP?

For HTML5, html5 lib has been abandoned for years now. The only HTML5 library I can find with a recent update and maintenance records is html5-php which was just brought to beta 1.0 a little over a week ago.

Websocket connections with Postman

Postman doesn't support websocket. Most of the extension and app I had ever seen were not working properly.

Solution which I found

Just login/ open your application in your browser, and open browser console. Then enter your socket event, and press enter.

socket.emit("event_name", {"id":"123"}, (res)=>{console.log(res); });

enter image description here

location.host vs location.hostname and cross-browser compatibility?

If you are insisting to use the window.location.origin You can put this in top of your code before reading the origin

if (!window.location.origin) {
  window.location.origin = window.location.protocol + "//" + window.location.hostname + (window.location.port ? ':' + window.location.port: '');
}

Solution

PS: For the record, it was actually the original question. It was already edited :)

How to get current route in Symfony 2?

if you want to get route name in your controller than you have to inject the request (instead of getting from container due to Symfony UPGRADE and than call get('_route').

public function indexAction(Request $request)
{
    $routeName = $request->get('_route');
}

if you want to get route name in twig than you have to get it like

{{ app.request.attributes.get('_route') }}

Entity Framework vs LINQ to SQL

I found that I couldn't use multiple databases within the same database model when using EF. But in linq2sql I could just by prefixing the schema names with database names.

This was one of the reasons I originally began working with linq2sql. I do not know if EF has yet allowed this functionality, but I remember reading that it was intended for it not to allow this.

Pyspark replace strings in Spark dataframe column

For Spark 1.5 or later, you can use the functions package:

from pyspark.sql.functions import *
newDf = df.withColumn('address', regexp_replace('address', 'lane', 'ln'))

Quick explanation:

  • The function withColumn is called to add (or replace, if the name exists) a column to the data frame.
  • The function regexp_replace will generate a new column by replacing all substrings that match the pattern.

Int or Number DataType for DataAnnotation validation attribute

For any number validation you have to use different different range validation as per your requirements :

For Integer

[Range(0, int.MaxValue, ErrorMessage = "Please enter valid integer Number")]

for float

[Range(0, float.MaxValue, ErrorMessage = "Please enter valid float Number")]

for double

[Range(0, double.MaxValue, ErrorMessage = "Please enter valid doubleNumber")]

What is the difference among col-lg-*, col-md-* and col-sm-* in Bootstrap?

I think the confusing aspect of this is the fact that BootStrap 3 is a mobile first responsive system and fails to explain how this affects the col-xx-n hierarchy in that part of the Bootstrap documentation. This makes you wonder what happens on smaller devices if you choose a value for larger devices and makes you wonder if there is a need to specify multiple values. (You don't)

I would attempt to clarify this by stating that... Lower grain types (xs, sm) attempt retain layout appearance on smaller screens and larger types (md,lg) will display correctly only on larger screens but will wrap columns on smaller devices. The values quoted in previous examples refer to the threshold as which bootstrap degrades the appearance to fit the available screen estate.

What this means in practice is that if you make the columns col-xs-n then they will retain correct appearance even on very small screens, until the window drops to a size that is so restrictive that the page cannot be displayed correctly. This should mean that devices that have a width of 768px or less should show your table as you designed it rather than in degraded (single or wrapped column form). Obviously this still depends on the content of the columns and that's the whole point. If the page attempts to display multiple columns of large data, side by side on a small screen then the columns will naturally wrap in a horrible way if you did not account for it. Therefore, depending on the data within the columns you can decide the point at which the layout is sacificed to display the content adequately.

e.g. If your page contains three col-sm-n columns bootstrap would wrap the columns into rows when the page width drops below 992px. This means that the data is still visible but will require vertical scrolling to view it. If you do not want your layout to degrade, choose xs (as long as your data can be adequately displayed on a lower resolution device in three columns)

If the horizontal position of the data is important then you should try to choose lower granularity values to retain the visual nature. If the position is less important but the page must be visible on all devices then a higher value should be used.

If you choose col-lg-n then the columns will display correctly until the screen width drops below the xs threshold of 1200px.

How to use vertical align in bootstrap

I had to add width: 100%; to display table to fix some strange bahavior in IE and FF, when i used this example. IE and FF had some problems displaying the col-md-* tags at the right width

.display-table {
        display: table;
        table-layout: fixed;
        width: 100%;
}

.display-cell {
        display: table-cell;
        vertical-align: middle;
        float: none;
}

How to apply slide animation between two activities in Android?

Add this two file in res/anim folder.

R.anim.slide_out_bottom

<set xmlns:android="http://schemas.android.com/apk/res/android"
android:shareInterpolator="false">
<translate
    android:duration="@integer/time_duration_max"
    android:fromXDelta="0%"
    android:fromYDelta="100%"
    android:toXDelta="0%"
    android:toYDelta="0%" />
</set>

R.anim.slide_in_bottom

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
android:shareInterpolator="false">
<translate
    android:duration="@integer/time_duration_max"
    android:fromXDelta="0%"
    android:fromYDelta="0%"
    android:toXDelta="0%"
    android:toYDelta="100%" /> 
</set>

And write the below line of code in your view click listener.

startActivity(new Intent(MainActivity.this, NameOfTargetActivity.class));
overridePendingTransition(R.anim.slide_out_bottom, R.anim.slide_in_bottom);

Batch Renaming of Files in a Directory

as to me in my directory I have multiple subdir, each subdir has lots of images I want to change all the subdir images to 1.jpg ~ n.jpg

def batch_rename():
    base_dir = 'F:/ad_samples/test_samples/'
    sub_dir_list = glob.glob(base_dir + '*')
    # print sub_dir_list # like that ['F:/dir1', 'F:/dir2']
    for dir_item in sub_dir_list:
        files = glob.glob(dir_item + '/*.jpg')
        i = 0
        for f in files:
            os.rename(f, os.path.join(dir_item, str(i) + '.jpg'))
            i += 1

(mys own answer)https://stackoverflow.com/a/45734381/6329006

How to get the path of a running JAR file?

I have another way to get the String location of a class.

URL path = Thread.currentThread().getContextClassLoader().getResource("");
Path p = Paths.get(path.toURI());
String location = p.toString();

The output String will have the form of

C:\Users\Administrator\new Workspace\...

The spaces and other characters are handled, and in the form without file:/. So will be easier to use.

position: fixed doesn't work on iPad and iPhone

This might not be applicable to all scenarios, but I found that the position: sticky (same thing with position: fixed) only works on old iPhones when the scrolling container is not the body, but inside something else.

Example pseudo html:

body                         <- scrollbar
   relative div
       sticky div

The sticky div will be sticky on desktop browsers, but with certain devices, tested with: Chromium: dev tools: device emultation: iPhone 6/7/8, and with Android 4 Firefox, it will not.

What will work, however, is

body
    div overflow=auto       <- scrollbar
        relative div
            sticky div

Insert string in beginning of another string

It is better if you find quotation marks by using the indexof() method and then add a string behind that index.

string s="hai";
int s=s.indexof(""");

How to use conditional breakpoint in Eclipse?

Put your breakpoint. Right-click the breakpoint image on the margin and choose Breakpoint Properties:

enter image description here

Configure condition as you see fit:

enter image description here

Equals(=) vs. LIKE

To address the original question regarding performance, it comes down to index utilization. When a simple table scan occurs, "LIKE" and "=" are identical. When indexes are involved, it depends on how the LIKE clause is formed. More specifically, what is the location of the wildcard(s)?


Consider the following:

CREATE TABLE test(
    txt_col  varchar(10) NOT NULL
)
go

insert test (txt_col)
select CONVERT(varchar(10), row_number() over (order by (select 1))) r
  from master..spt_values a, master..spt_values b
go

CREATE INDEX IX_test_data 
    ON test (txt_col);
go 

--Turn on Show Execution Plan
set statistics io on

--A LIKE Clause with a wildcard at the beginning
DBCC DROPCLEANBUFFERS
SELECT txt_Col from test where txt_col like '%10000'
--Results in
--Table 'test'. Scan count 3, logical reads 15404, physical reads 2, read-ahead reads 15416, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.
--Index SCAN is 85% of Query Cost

--A LIKE Clause with a wildcard in the middle
DBCC DROPCLEANBUFFERS
SELECT txt_Col from test where txt_col like '1%99'
--Results in
--Table 'test'. Scan count 1, logical reads 3023, physical reads 3, read-ahead reads 3018, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.
--Index Seek is 100% of Query Cost for test data, but it may result in a Table Scan depending on table size/structure

--A LIKE Clause with no wildcards
DBCC DROPCLEANBUFFERS
SELECT txt_Col from test where txt_col like '10000'
--Results in
--Table 'test'. Scan count 1, logical reads 3, physical reads 2, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.
--Index Seek is 100% of Query Cost
GO

--an "=" clause = does Index Seek same as above
DBCC DROPCLEANBUFFERS
SELECT txt_Col from test where txt_col = '10000'
--Results in
--Table 'test'. Scan count 1, logical reads 3, physical reads 2, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.
--Index Seek is 100% of Query Cost
GO


DROP TABLE test

There may be also negligible difference in the creation of the query plan when using "=" vs "LIKE".

How does a Java HashMap handle different objects with the same hash code?

As it is said, a picture is worth 1000 words. I say: some code is better than 1000 words. Here's the source code of HashMap. Get method:

/**
     * Implements Map.get and related methods
     *
     * @param hash hash for key
     * @param key the key
     * @return the node, or null if none
     */
    final Node<K,V> getNode(int hash, Object key) {
        Node<K,V>[] tab; Node<K,V> first, e; int n; K k;
        if ((tab = table) != null && (n = tab.length) > 0 &&
            (first = tab[(n - 1) & hash]) != null) {
            if (first.hash == hash && // always check first node
                ((k = first.key) == key || (key != null && key.equals(k))))
                return first;
            if ((e = first.next) != null) {
                if (first instanceof TreeNode)
                    return ((TreeNode<K,V>)first).getTreeNode(hash, key);
                do {
                    if (e.hash == hash &&
                        ((k = e.key) == key || (key != null && key.equals(k))))
                        return e;
                } while ((e = e.next) != null);
            }
        }
        return null;
    }

So it becomes clear that hash is used to find the "bucket" and the first element is always checked in that bucket. If not, then equals of the key is used to find the actual element in the linked list.

Let's see the put() method:

  /**
     * Implements Map.put and related methods
     *
     * @param hash hash for key
     * @param key the key
     * @param value the value to put
     * @param onlyIfAbsent if true, don't change existing value
     * @param evict if false, the table is in creation mode.
     * @return previous value, or null if none
     */
    final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
                   boolean evict) {
        Node<K,V>[] tab; Node<K,V> p; int n, i;
        if ((tab = table) == null || (n = tab.length) == 0)
            n = (tab = resize()).length;
        if ((p = tab[i = (n - 1) & hash]) == null)
            tab[i] = newNode(hash, key, value, null);
        else {
            Node<K,V> e; K k;
            if (p.hash == hash &&
                ((k = p.key) == key || (key != null && key.equals(k))))
                e = p;
            else if (p instanceof TreeNode)
                e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
            else {
                for (int binCount = 0; ; ++binCount) {
                    if ((e = p.next) == null) {
                        p.next = newNode(hash, key, value, null);
                        if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
                            treeifyBin(tab, hash);
                        break;
                    }
                    if (e.hash == hash &&
                        ((k = e.key) == key || (key != null && key.equals(k))))
                        break;
                    p = e;
                }
            }
            if (e != null) { // existing mapping for key
                V oldValue = e.value;
                if (!onlyIfAbsent || oldValue == null)
                    e.value = value;
                afterNodeAccess(e);
                return oldValue;
            }
        }
        ++modCount;
        if (++size > threshold)
            resize();
        afterNodeInsertion(evict);
        return null;
    }

It's slightly more complicated, but it becomes clear that the new element is put in the tab at the position calculated based on hash:

i = (n - 1) & hash here i is the index where the new element will be put (or it is the "bucket"). n is the size of the tab array (array of "buckets").

First, it is tried to be put as the first element of in that "bucket". If there is already an element, then append a new node to the list.

Write a number with two decimal places SQL Server

Use Str() Function. It takes three arguments(the number, the number total characters to display, and the number of decimal places to display

  Select Str(12345.6789, 12, 3)

displays: ' 12345.679' ( 3 spaces, 5 digits 12345, a decimal point, and three decimal digits (679). - it rounds if it has to truncate, (unless the integer part is too large for the total size, in which case asterisks are displayed instead.)

for a Total of 12 characters, with 3 to the right of decimal point.

Java split string to array

This is expected. Refer to Javadocs for split.

Splits this string around matches of the given regular expression.

This method works as if by invoking the two-argument split(java.lang.String,int) method with the given expression and a limit argument of zero. Trailing empty strings are therefore not included in the resulting array.

How to pass payload via JSON file for curl?

curl sends POST requests with the default content type of application/x-www-form-urlencoded. If you want to send a JSON request, you will have to specify the correct content type header:

$ curl -vX POST http://server/api/v1/places.json -d @testplace.json \
--header "Content-Type: application/json"

But that will only work if the server accepts json input. The .json at the end of the url may only indicate that the output is json, it doesn't necessarily mean that it also will handle json input. The API documentation should give you a hint on whether it does or not.

The reason you get a 401 and not some other error is probably because the server can't extract the auth_token from your request.

Add default value of datetime field in SQL Server to a timestamp

In that table in SQL Server, specify the default value of that column to be CURRENT_TIMESTAMP. The datatype of that column may be datetime or datetime2.

e.g.

Create Table Student
(
  Name varchar(50),
  DateOfAddmission datetime default CURRENT_TIMESTAMP
);

How do negative margins in CSS work and why is (margin-top:-5 != margin-bottom:5)?

Margin is the spacing outside your element, just as padding is the spacing inside your element.

Setting the bottom margin indicates what distance you want below the current block. Setting a negative top margin indicates that you want negative spacing above your block. Negative spacing may in itself be a confusing concept, but just the way positive top margin pushes content down, a negative top margin pulls content up.

How to insert TIMESTAMP into my MySQL table?

You can try wiht TIMESTAMP(curdate(), curtime()) for use the current time.

Pass PDO prepared statement to variables

Instead of using ->bindParam() you can pass the data only at the time of ->execute():

$data = [   ':item_name' => $_POST['item_name'],   ':item_type' => $_POST['item_type'],   ':item_price' => $_POST['item_price'],   ':item_description' => $_POST['item_description'],   ':image_location' => 'images/'.$_FILES['file']['name'],   ':status' => 0,   ':id' => 0, ];  $stmt->execute($data); 

In this way you would know exactly what values are going to be sent.

How to hide the keyboard when I press return key in a UITextField?

Ok, I think for a novice things might be a bit confusing. I think the correct answer is a mix of all the above, at least in Swift4.

Either create an extension or use the ViewController in which you'd like to use this but make sure to implement UITextFieldDelegate. For reusability's sake I found it easier to use an extension:

extension UIViewController : UITextFieldDelegate {
    ...
}

but the alternative works as well:

class MyViewController: UIViewController {
    ...
}

Add the method textFieldShouldReturn (depending on your previous option, either in the extension or in your ViewController)

func textFieldShouldReturn(_ textField: UITextField) -> Bool {
    return textField.endEditing(false)
}

In your viewDidLoad method, set the textfield's delegate to self

@IBOutlet weak var myTextField: UITextField!
...

override func viewDidLoad() {
    ..
    myTextField.delegte = self;
    ..
}

That should be all. Now, when you press return the textFieldShouldReturn should be called.

Implement Validation for WPF TextBoxes

You can additionally implement IDataErrorInfo as follows in the view model. If you implement IDataErrorInfo, you can do the validation in that instead of the setter of a particular property, then whenever there is a error, return an error message so that the text box which has the error gets a red box around it, indicating an error.

class ViewModel : INotifyPropertyChanged, IDataErrorInfo
{
    private string m_Name = "Type Here";
    public ViewModel()
    {
    }

    public string Name
    {
        get
        {
            return m_Name;
        }
        set
        {
            if (m_Name != value)
            {
                m_Name = value;
                OnPropertyChanged("Name");
            }
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;

    protected void OnPropertyChanged(string propertyName)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }

    public string Error
    {
        get { return "...."; }
    }

    /// <summary>
    /// Will be called for each and every property when ever its value is changed
    /// </summary>
    /// <param name="columnName">Name of the property whose value is changed</param>
    /// <returns></returns>
    public string this[string columnName]
    {
        get 
        {
            return Validate(columnName);
        }
    }

    private string Validate(string propertyName)
    {
        // Return error message if there is error on else return empty or null string
        string validationMessage = string.Empty;
        switch (propertyName)
        {
            case "Name": // property name
                // TODO: Check validiation condition
                validationMessage = "Error";
                break;
        }

        return validationMessage;
    }
}

And you have to set ValidatesOnDataErrors=True in the XAML in order to invoke the methods of IDataErrorInfo as follows:

<TextBox Text="{Binding Name, UpdateSourceTrigger=PropertyChanged, ValidatesOnDataErrors=True}" />

Reading From A Text File - Batch

Your code "for /f "tokens=* delims=" %%x in (a.txt) do echo %%x" will work on most Windows Operating Systems unless you have modified commands.

So you could instead "cd" into the directory to read from before executing the "for /f" command to follow out the string. For instance if the file "a.txt" is located at C:\documents and settings\%USERNAME%\desktop\a.txt then you'd use the following.

cd "C:\documents and settings\%USERNAME%\desktop"
for /f "tokens=* delims=" %%x in (a.txt) do echo %%x
echo.
echo.
echo.
pause >nul
exit

But since this doesn't work on your computer for x reason there is an easier and more efficient way of doing this. Using the "type" command.

@echo off
color a
cls
cd "C:\documents and settings\%USERNAME%\desktop"
type a.txt
echo.
echo.
pause >nul
exit

Or if you'd like them to select the file from which to write in the batch you could do the following.

@echo off
:A
color a
cls
echo Choose the file that you want to read.
echo.
echo.
tree
echo.
echo.
echo.
set file=
set /p file=File:
cls
echo Reading from %file%
echo.
type %file%
echo.
echo.
echo.
set re=
set /p re=Y/N?:
if %re%==Y goto :A
if %re%==y goto :A
exit

Write to Windows Application Event Log

This is the logger class that I use. The private Log() method has EventLog.WriteEntry() in it, which is how you actually write to the event log. I'm including all of this code here because it's handy. In addition to logging, this class will also make sure the message isn't too long to write to the event log (it will truncate the message). If the message was too long, you'd get an exception. The caller can also specify the source. If the caller doesn't, this class will get the source. Hope it helps.

By the way, you can get an ObjectDumper from the web. I didn't want to post all that here. I got mine from here: C:\Program Files (x86)\Microsoft Visual Studio 10.0\Samples\1033\CSharpSamples.zip\LinqSamples\ObjectDumper

using System;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
using Xanico.Core.Utilities;

namespace Xanico.Core
{
    /// <summary>
    /// Logging operations
    /// </summary>
    public static class Logger
    {
        // Note: The actual limit is higher than this, but different Microsoft operating systems actually have
        //       different limits. So just use 30,000 to be safe.
        private const int MaxEventLogEntryLength = 30000;

        /// <summary>
        /// Gets or sets the source/caller. When logging, this logger class will attempt to get the
        /// name of the executing/entry assembly and use that as the source when writing to a log.
        /// In some cases, this class can't get the name of the executing assembly. This only seems
        /// to happen though when the caller is in a separate domain created by its caller. So,
        /// unless you're in that situation, there is no reason to set this. However, if there is
        /// any reason that the source isn't being correctly logged, just set it here when your
        /// process starts.
        /// </summary>
        public static string Source { get; set; }

        /// <summary>
        /// Logs the message, but only if debug logging is true.
        /// </summary>
        /// <param name="message">The message.</param>
        /// <param name="debugLoggingEnabled">if set to <c>true</c> [debug logging enabled].</param>
        /// <param name="source">The name of the app/process calling the logging method. If not provided,
        /// an attempt will be made to get the name of the calling process.</param>
        public static void LogDebug(string message, bool debugLoggingEnabled, string source = "")
        {
            if (debugLoggingEnabled == false) { return; }

            Log(message, EventLogEntryType.Information, source);
        }

        /// <summary>
        /// Logs the information.
        /// </summary>
        /// <param name="message">The message.</param>
        /// <param name="source">The name of the app/process calling the logging method. If not provided,
        /// an attempt will be made to get the name of the calling process.</param>
        public static void LogInformation(string message, string source = "")
        {
            Log(message, EventLogEntryType.Information, source);
        }

        /// <summary>
        /// Logs the warning.
        /// </summary>
        /// <param name="message">The message.</param>
        /// <param name="source">The name of the app/process calling the logging method. If not provided,
        /// an attempt will be made to get the name of the calling process.</param>
        public static void LogWarning(string message, string source = "")
        {
            Log(message, EventLogEntryType.Warning, source);
        }

        /// <summary>
        /// Logs the exception.
        /// </summary>
        /// <param name="ex">The ex.</param>
        /// <param name="source">The name of the app/process calling the logging method. If not provided,
        /// an attempt will be made to get the name of the calling process.</param>
        public static void LogException(Exception ex, string source = "")
        {
            if (ex == null) { throw new ArgumentNullException("ex"); }

            if (Environment.UserInteractive)
            {
                Console.WriteLine(ex.ToString());
            }

            Log(ex.ToString(), EventLogEntryType.Error, source);
        }

        /// <summary>
        /// Recursively gets the properties and values of an object and dumps that to the log.
        /// </summary>
        /// <param name="theObject">The object to log</param>
        [SuppressMessage("Microsoft.Globalization", "CA1303:Do not pass literals as localized parameters", MessageId = "Xanico.Core.Logger.Log(System.String,System.Diagnostics.EventLogEntryType,System.String)")]
        [SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames", MessageId = "object")]
        public static void LogObjectDump(object theObject, string objectName, string source = "")
        {
            const int objectDepth = 5;
            string objectDump = ObjectDumper.GetObjectDump(theObject, objectDepth);

            string prefix = string.Format(CultureInfo.CurrentCulture,
                                          "{0} object dump:{1}",
                                          objectName,
                                          Environment.NewLine);

            Log(prefix + objectDump, EventLogEntryType.Warning, source);
        }

        private static void Log(string message, EventLogEntryType entryType, string source)
        {
            // Note: I got an error that the security log was inaccessible. To get around it, I ran the app as administrator
            //       just once, then I could run it from within VS.

            if (string.IsNullOrWhiteSpace(source))
            {
                source = GetSource();
            }

            string possiblyTruncatedMessage = EnsureLogMessageLimit(message);
            EventLog.WriteEntry(source, possiblyTruncatedMessage, entryType);

            // If we're running a console app, also write the message to the console window.
            if (Environment.UserInteractive)
            {
                Console.WriteLine(message);
            }
        }

        private static string GetSource()
        {
            // If the caller has explicitly set a source value, just use it.
            if (!string.IsNullOrWhiteSpace(Source)) { return Source; }

            try
            {
                var assembly = Assembly.GetEntryAssembly();

                // GetEntryAssembly() can return null when called in the context of a unit test project.
                // That can also happen when called from an app hosted in IIS, or even a windows service.

                if (assembly == null)
                {
                    assembly = Assembly.GetExecutingAssembly();
                }


                if (assembly == null)
                {
                    // From http://stackoverflow.com/a/14165787/279516:
                    assembly = new StackTrace().GetFrames().Last().GetMethod().Module.Assembly;
                }

                if (assembly == null) { return "Unknown"; }

                return assembly.GetName().Name;
            }
            catch
            {
                return "Unknown";
            }
        }

        // Ensures that the log message entry text length does not exceed the event log viewer maximum length of 32766 characters.
        private static string EnsureLogMessageLimit(string logMessage)
        {
            if (logMessage.Length > MaxEventLogEntryLength)
            {
                string truncateWarningText = string.Format(CultureInfo.CurrentCulture, "... | Log Message Truncated [ Limit: {0} ]", MaxEventLogEntryLength);

                // Set the message to the max minus enough room to add the truncate warning.
                logMessage = logMessage.Substring(0, MaxEventLogEntryLength - truncateWarningText.Length);

                logMessage = string.Format(CultureInfo.CurrentCulture, "{0}{1}", logMessage, truncateWarningText);
            }

            return logMessage;
        }
    }
}

Detect when a window is resized using JavaScript ?

This can be achieved with the onresize property of the GlobalEventHandlers interface in JavaScript, by assigning a function to the onresize property, like so:

window.onresize = functionRef;

The following code snippet demonstrates this, by console logging the innerWidth and innerHeight of the window whenever it's resized. (The resize event fires after the window has been resized)

_x000D_
_x000D_
function resize() {_x000D_
  console.log("height: ", window.innerHeight, "px");_x000D_
  console.log("width: ", window.innerWidth, "px");_x000D_
}_x000D_
_x000D_
window.onresize = resize;
_x000D_
<p>In order for this code snippet to work as intended, you will need to either shrink your browser window down to the size of this code snippet, or fullscreen this code snippet and resize from there.</p>
_x000D_
_x000D_
_x000D_

JavaScript listener, "keypress" doesn't detect backspace?

Use one of keyup / keydown / beforeinput events instead.

based on this reference, keypress is deprecated and no longer recommended.

The keypress event is fired when a key that produces a character value is pressed down. Examples of keys that produce a character value are alphabetic, numeric, and punctuation keys. Examples of keys that don't produce a character value are modifier keys such as Alt, Shift, Ctrl, or Meta.

if you use "beforeinput" be careful about it's Browser compatibility. the difference between "beforeinput" and the other two is that "beforeinput" is fired when input value is about to changed, so with characters that can't change the input value, it is not fired (e.g shift, ctr ,alt).

I had the same problem and by using keyup it was solved.

position fixed is not working

My issue was that a parent element had transform: scale(1); this apparently makes it impossible for any element to be fixed inside it. By removing that everything works normally...

It seems to be like this in all browsers I tested (Chrome, Safari) so don't know if it comes from some strange web standard.

(It's a popup that goes from scale(0) to scale(1))

Can't import Numpy in Python

I was trying to import numpy in python 3.2.1 on windows 7.

Followed suggestions in above answer for numpy-1.6.1.zip as below after unzipping it

cd numpy-1.6
python setup.py install

but got an error with a statement as below

unable to find vcvarsall.bat

For this error I found a related question here which suggested installing mingW. MingW was taking some time to install.

In the meanwhile tried to install numpy 1.6 again using the direct windows installer available at this link the file name is "numpy-1.6.1-win32-superpack-python3.2.exe"

Installation went smoothly and now I am able to import numpy without using mingW.

Long story short try using windows installer for numpy, if one is available.

c# - approach for saving user settings in a WPF application?

Apart from a database, you can also have following options to save user related settings

  1. registry under HKEY_CURRENT_USER

  2. in a file in AppData folder

  3. using Settings file in WPF and by setting its scope as User

How can I reorder a list?

newList = [oldList[3]]
newList.extend(oldList[:3])
newList.extend(oldList[4:])

Getting a 500 Internal Server Error on Laravel 5+ Ubuntu 14.04

Create the .env file and also run :

php artisan key:generate

This worked for me after pulling a git project.

After creating .env file and generating the key, run the code below:

php artisan cache:clear 
php artisan config:clear

How to copy and edit files in Android shell?

You can do it without root permissions:

cat srcfile > /mnt/sdcard/dstfile

Default values in a C Struct

The most elegant way would be to update the struct fields directly, without having to use the update() function - but maybe there are good reasons for using it that don't come across in the question.

struct foo* bar = get_foo_ptr();
foo_ref.id = 42;
foo_ref.current_route = new_route;

Or you can, like Pukku suggested, create separate access functions for each field of the struct.

Otherwise the best solution I can think of is treating a value of '0' in a struct field as a 'do not update' flag - so you just create a funciton to return a zeroed out struct, and then use this to update.

struct foo empty_foo(void)
{
    struct foo bar;
    bzero(&bar, sizeof (struct bar));
    return bar;    
}

struct foo bar = empty_foo();
bar.id=42;
bar.current_route = new_route;
update(&bar);

However, this might not be very feasible, if 0 is a valid value for fields in the struct.

How to check if the user can go back in browser history or not

There is a snippet I use in my projects:

function back(url) {
    if (history.length > 2) {
        // if history is not empty, go back:
        window.History.back();
    } else if (url) {
        // go to specified fallback url:
        window.History.replaceState(null, null, url);
    } else {
        // go home:
        window.History.replaceState(null, null, '/');
    }
}

FYI: I use History.js to manage browser history.


Why to compare history.length to number 2?

Because Chrome's startpage is counted as first item in the browser's history.


There are few possibilities of history.length and user's behaviour:

  • User opens new empty tab in the browser and then runs a page. history.length = 2 and we want to disable back() in this case, because user will go to empty tab.
  • User opens the page in new tab by clicking a link somewhere before. history.length = 1 and again we want to disable back() method.
  • And finally, user lands at current page after reloading few pages. history.length > 2 and now back() can be enabled.

Note: I omit case when user lands at current page after clicking link from external website without target="_blank".

Note 2: document.referrer is empty when you open website by typing its address and also when website uses ajax to load subpages, so I discontinued checking this value in the first case.

Where is the Global.asax.cs file?

It don't create normally; you need to add it by yourself.

After adding Global.asax by

  • Right clicking your website -> Add New Item -> Global Application Class -> Add

You need to add a class

  • Right clicking App_Code -> Add New Item -> Class -> name it Global.cs -> Add

Inherit the newly generated by System.Web.HttpApplication and copy all the method created Global.asax to Global.cs and also add an inherit attribute to the Global.asax file.

Your Global.asax will look like this: -

<%@ Application Language="C#" Inherits="Global" %>

Your Global.cs in App_Code will look like this: -

public class Global : System.Web.HttpApplication
{
    public Global()
    {
        //
        // TODO: Add constructor logic here
        //
    }

    void Application_Start(object sender, EventArgs e)
    {
        // Code that runs on application startup

    }
    /// Many other events like begin request...e.t.c, e.t.c
}

Why do you need to invoke an anonymous function on the same line?

In summary of the previous comments:

function() {
  alert("hello");
}();

when not assigned to a variable, yields a syntax error. The code is parsed as a function statement (or definition), which renders the closing parentheses syntactically incorrect. Adding parentheses around the function portion tells the interpreter (and programmer) that this is a function expression (or invocation), as in

(function() {
  alert("hello");
})();

This is a self-invoking function, meaning it is created anonymously and runs immediately because the invocation happens in the same line where it is declared. This self-invoking function is indicated with the familiar syntax to call a no-argument function, plus added parentheses around the name of the function: (myFunction)();.

There is a good SO discussion JavaScript function syntax.

Intercept and override HTTP requests from WebView

Here is my solution I use for my app.

I have several asset folder with css / js / img anf font files.

The application gets all filenames and looks if a file with this name is requested. If yes, it loads it from asset folder.

//get list of files of specific asset folder
        private ArrayList listAssetFiles(String path) {

            List myArrayList = new ArrayList();
            String [] list;
            try {
                list = getAssets().list(path);
                for(String f1 : list){
                    myArrayList.add(f1);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            return (ArrayList) myArrayList;
        }

        //get mime type by url
        public String getMimeType(String url) {
            String type = null;
            String extension = MimeTypeMap.getFileExtensionFromUrl(url);
            if (extension != null) {
                if (extension.equals("js")) {
                    return "text/javascript";
                }
                else if (extension.equals("woff")) {
                    return "application/font-woff";
                }
                else if (extension.equals("woff2")) {
                    return "application/font-woff2";
                }
                else if (extension.equals("ttf")) {
                    return "application/x-font-ttf";
                }
                else if (extension.equals("eot")) {
                    return "application/vnd.ms-fontobject";
                }
                else if (extension.equals("svg")) {
                    return "image/svg+xml";
                }
                type = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
            }
            return type;
        }

        //return webresourceresponse
        public WebResourceResponse loadFilesFromAssetFolder (String folder, String url) {
            List myArrayList = listAssetFiles(folder);
            for (Object str : myArrayList) {
                if (url.contains((CharSequence) str)) {
                    try {
                        Log.i(TAG2, "File:" + str);
                        Log.i(TAG2, "MIME:" + getMimeType(url));
                        return new WebResourceResponse(getMimeType(url), "UTF-8", getAssets().open(String.valueOf(folder+"/" + str)));
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
            return null;
        }

        //@TargetApi(Build.VERSION_CODES.LOLLIPOP)
        @SuppressLint("NewApi")
        @Override
        public WebResourceResponse shouldInterceptRequest(final WebView view, String url) {
            //Log.i(TAG2, "SHOULD OVERRIDE INIT");
            //String url = webResourceRequest.getUrl().toString();
            String extension = MimeTypeMap.getFileExtensionFromUrl(url);
            //I have some folders for files with the same extension
            if (extension.equals("css") || extension.equals("js") || extension.equals("img")) {
                return loadFilesFromAssetFolder(extension, url);
            }
            //more possible extensions for font folder
            if (extension.equals("woff") || extension.equals("woff2") || extension.equals("ttf") || extension.equals("svg") || extension.equals("eot")) {
                return loadFilesFromAssetFolder("font", url);
            }

            return null;
        }

Convert an enum to List<string>

Use Enum's static method, GetNames. It returns a string[], like so:

Enum.GetNames(typeof(DataSourceTypes))

If you want to create a method that does only this for only one type of enum, and also converts that array to a List, you can write something like this:

public List<string> GetDataSourceTypes()
{
    return Enum.GetNames(typeof(DataSourceTypes)).ToList();
}

You will need Using System.Linq; at the top of your class to use .ToList()

Fatal error: Call to undefined function base_url() in C:\wamp\www\Test-CI\application\views\layout.php on line 5

There is only three way to solve. paste in following code in this path application/config/autoload.php.

most of them I use this

require_once BASEPATH . '/helpers/url_helper.php';

this is good but some time, it fail

$autoload['helper'] = array('url');

I never use it but I know it work

$this->load->helper('url');

How to open Android Device Monitor in latest Android Studio 3.1

If you're looking for the Hierarchy Viewer tool, it has been changed to Layout Inspector:

https://developer.android.com/studio/debug/layout-inspector.html

VBA EXCEL Multiple Nested FOR Loops that Set two variable for expression

I can't get to your google docs file at the moment but there are some issues with your code that I will try to address while answering

Sub stituterangersNEW()
Dim t As Range
Dim x As Range
Dim dify As Boolean
Dim difx As Boolean
Dim time2 As Date
Dim time1 As Date

    'You said time1 doesn't change, so I left it in a singe cell.
    'If that is not correct, you will have to play with this some more.
    time1 = Range("A6").Value

    'Looping through each of our output cells.
    For Each t In Range("B7:E9") 'Change these to match your real ranges.

        'Looping through each departure date/time.
        '(Only one row in your example. This can be adjusted if needed.)
        For Each x In Range("B2:E2") 'Change these to match your real ranges.
            'Check to see if our dep time corresponds to
            'the matching column in our output
            If t.Column = x.Column Then
                'If it does, then check to see what our time value is
                If x > 0 Then
                    time2 = x.Value
                    'Apply the change to the output cell.
                    t.Value = time1 - time2
                    'Exit out of this loop and move to the next output cell.
                    Exit For
                End If
            End If
            'If the columns don't match, or the x value is not a time
            'then we'll move to the next dep time (x)
        Next x
    Next t

End Sub

EDIT

I changed you worksheet to play with (see above for the new Sub). This probably does not suite your needs directly, but hopefully it will demonstrate the conept behind what I think you want to do. Please keep in mind that this code does not follow all the coding best preactices I would recommend (e.g. validating the time is actually a TIME and not some random other data type).

     A                      B                   C                   D                  E
1    LOAD_NUMBER            1                   2                   3                  4
2    DEPARTURE_TIME_DATE    11/12/2011 19:30    11/12/2011 19:30    11/12/2011 19:30    11/12/2011 20:00                
4    Dry_Refrig 7585.1  0   10099.8 16700
6    1/4/2012 19:30

Using the sub I got this output:

    A           B             C             D             E
7   Friday      1272:00:00    1272:00:00    1272:00:00    1271:30:00
8   Saturday    1272:00:00    1272:00:00    1272:00:00    1271:30:00
9   Thursday    1272:00:00    1272:00:00    1272:00:00    1271:30:00

Run bash script as daemon

A Daemon is just program that runs as a background process, rather than being under the direct control of an interactive user...

[The below bash code is for Debian systems - Ubuntu, Linux Mint distros and so on]

The simple way:

The simple way would be to edit your /etc/rc.local file and then just have your script run from there (i.e. everytime you boot up the system):

sudo nano /etc/rc.local

Add the following and save:

#For a BASH script
/bin/sh TheNameOfYourScript.sh > /dev/null &

The better way to do this would be to create a Daemon via Upstart:

sudo nano /etc/init/TheNameOfYourDaemon.conf

add the following:

description "My Daemon Job"
author "Your Name"
start on runlevel [2345]    

pre-start script
  echo "[`date`] My Daemon Starting" >> /var/log/TheNameOfYourDaemonJobLog.log
end script

exec /bin/sh TheNameOfYourScript.sh > /dev/null &

Save this.

Confirm that it looks ok:

init-checkconf /etc/init/TheNameOfYourDaemon.conf

Now reboot the machine:

sudo reboot

Now when you boot up your system, you can see the log file stating that your Daemon is running:

cat  /var/log/TheNameOfYourDaemonJobLog.log

• Now you may start/stop/restart/get the status of your Daemon via:

restart: this will stop, then start a service

sudo service TheNameOfYourDaemonrestart restart

start: this will start a service, if it's not running

sudo service TheNameOfYourDaemonstart start

stop: this will stop a service, if it's running

sudo service TheNameOfYourDaemonstop stop

status: this will display the status of a service

sudo service TheNameOfYourDaemonstatus status

How to make php display \t \n as tab and new line instead of characters

Put it in double quotes:

echo "\t";

Single quotes do not expand escaped characters.

Use the documentation when in doubt.

Dynamic Height Issue for UITableView Cells (Swift)

self.Itemtableview.estimatedRowHeight = 0;
self.Itemtableview.estimatedSectionHeaderHeight = 0;
self.Itemtableview.estimatedSectionFooterHeight = 0;


[ self.Itemtableview reloadData];
self.Itemtableview.frame = CGRectMake( self.Itemtableview.frame.origin.x,  self.Itemtableview.frame.origin.y,  self.Itemtableview.frame.size.width,self.Itemtableview.contentSize.height + self.Itemtableview.contentInset.bottom + self.Itemtableview.contentInset.top);

Linux command to print directory structure in the form of a tree

This command works to display both folders and files.

find . | sed -e "s/[^-][^\/]*\// |/g" -e "s/|\([^ ]\)/|-\1/"

Example output:

.
 |-trace.pcap
 |-parent
 | |-chdir1
 | | |-file1.txt
 | |-chdir2
 | | |-file2.txt
 | | |-file3.sh
 |-tmp
 | |-json-c-0.11-4.el7_0.x86_64.rpm

Source: Comment from @javasheriff here. Its submerged as a comment and posting it as answer helps users spot it easily.

How to enable SOAP on CentOS

For my point of view, First thing is to install soap into Centos

yum install php-soap


Second, see if the soap package exist or not

yum search php-soap

third, thus you must see some result of soap package you installed, now type a command in your terminal in the root folder for searching the location of soap for specific path

find -name soap.so

fourth, you will see the exact path where its installed/located, simply copy the path and find the php.ini to add the extension path,

usually the path of php.ini file in centos 6 is in

/etc/php.ini

fifth, add a line of code from below into php.ini file

extension='/usr/lib/php/modules/soap.so'

and then save the file and exit.

sixth run apache restart command in Centos. I think there is two command that can restart your apache ( whichever is easier for you )

service httpd restart

OR

apachectl restart

Lastly, check phpinfo() output in browser, you should see SOAP section where SOAP CLIENT, SOAP SERVER etc are listed and shown Enabled.

serialize/deserialize java 8 java.time with Jackson JSON mapper

all you need to know is in Jackson Documentation https://www.baeldung.com/jackson-serialize-dates

Ad.9 quick solved the problem for me.

ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(new JavaTimeModule());
mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);

Understanding INADDR_ANY for socket programming

INADDR_ANY is used when you don't need to bind a socket to a specific IP. When you use this value as the address when calling bind(), the socket accepts connections to all the IPs of the machine.

Python: importing a sub-package or sub-module

You seem to be misunderstanding how import searches for modules. When you use an import statement it always searches the actual module path (and/or sys.modules); it doesn't make use of module objects in the local namespace that exist because of previous imports. When you do:

import package.subpackage.module
from package.subpackage import module
from module import attribute1

The second line looks for a package called package.subpackage and imports module from that package. This line has no effect on the third line. The third line just looks for a module called module and doesn't find one. It doesn't "re-use" the object called module that you got from the line above.

In other words from someModule import ... doesn't mean "from the module called someModule that I imported earlier..." it means "from the module named someModule that you find on sys.path...". There is no way to "incrementally" build up a module's path by importing the packages that lead to it. You always have to refer to the entire module name when importing.

It's not clear what you're trying to achieve. If you only want to import the particular object attribute1, just do from package.subpackage.module import attribute1 and be done with it. You need never worry about the long package.subpackage.module once you've imported the name you want from it.

If you do want to have access to the module to access other names later, then you can do from package.subpackage import module and, as you've seen you can then do module.attribute1 and so on as much as you like.

If you want both --- that is, if you want attribute1 directly accessible and you want module accessible, just do both of the above:

from package.subpackage import module
from package.subpackage.module import attribute1
attribute1 # works
module.someOtherAttribute # also works

If you don't like typing package.subpackage even twice, you can just manually create a local reference to attribute1:

from package.subpackage import module
attribute1 = module.attribute1
attribute1 # works
module.someOtherAttribute #also works

NSRange from Swift Range?

For me this works perfectly:

let font = UIFont.systemFont(ofSize: 12, weight: .medium)
let text = "text"
let attString = NSMutableAttributedString(string: "exemple text :)")

attString.addAttributes([.font: font], range:(attString.string as NSString).range(of: text))

label.attributedText = attString

Detect if the device is iPhone X

To detect any of the devices by using simple methods. like below,

func isPhoneDevice() -> Bool {
    return UIDevice.current.userInterfaceIdiom == .phone
}

func isDeviceIPad() -> Bool {
    return UIDevice.current.userInterfaceIdiom == .pad
}

func isPadProDevice() -> Bool {
    let SCREEN_WIDTH: CGFloat = UIScreen.main.bounds.size.width
    let SCREEN_HEIGHT: CGFloat = UIScreen.main.bounds.size.height
    let SCREEN_MAX_LENGTH: CGFloat = fmax(SCREEN_WIDTH, SCREEN_HEIGHT)

    return UIDevice.current.userInterfaceIdiom == .pad && SCREEN_MAX_LENGTH == 1366.0
}

func isPhoneXandXSDevice() -> Bool {
    let SCREEN_WIDTH = CGFloat(UIScreen.main.bounds.size.width)
    let SCREEN_HEIGHT = CGFloat(UIScreen.main.bounds.size.height)
    let SCREEN_MAX_LENGTH: CGFloat = fmax(SCREEN_WIDTH, SCREEN_HEIGHT)

    return UIDevice.current.userInterfaceIdiom == .phone && SCREEN_MAX_LENGTH == 812.0
}

func isPhoneXSMaxandXRDevice() -> Bool {
    let SCREEN_WIDTH = CGFloat(UIScreen.main.bounds.size.width)
    let SCREEN_HEIGHT = CGFloat(UIScreen.main.bounds.size.height)
    let SCREEN_MAX_LENGTH: CGFloat = fmax(SCREEN_WIDTH, SCREEN_HEIGHT)

    return UIDevice.current.userInterfaceIdiom == .phone && SCREEN_MAX_LENGTH == 896.0
}

and call like this,

if isPhoneDevice() {
     // Your code
}

Return an empty Observable

With the new syntax of RxJS 5.5+, this becomes as the following:

// RxJS 6
import { EMPTY, empty, of } from "rxjs";

// rxjs 5.5+ (<6)
import { empty } from "rxjs/observable/empty";
import { of } from "rxjs/observable/of";

empty(); // deprecated use EMPTY
EMPTY;
of({});

Just one thing to keep in mind, EMPTY completes the observable, so it won't trigger next in your stream, but only completes. So if you have, for instance, tap, they might not get trigger as you wish (see an example below).

Whereas of({}) creates an Observable and emits next with a value of {} and then it completes the Observable.

E.g.:

EMPTY.pipe(
    tap(() => console.warn("i will not reach here, as i am complete"))
).subscribe();

of({}).pipe(
    tap(() => console.warn("i will reach here and complete"))
).subscribe();

Hiding the scroll bar on an HTML page

This works for me with simple CSS properties:

.container {
    -ms-overflow-style: none;  // Internet Explorer 10+
    scrollbar-width: none;  // Firefox
}
.container::-webkit-scrollbar { 
    display: none;  // Safari and Chrome
}

For older versions of Firefox, use: overflow: -moz-scrollbars-none;

Android open pdf file

Kotlin version below (Updated version of @paul-burke response:

fun openPDFDocument(context: Context, filename: String) {
    //Create PDF Intent
    val pdfFile = File(Environment.getExternalStorageDirectory().absolutePath + "/" + filename)
    val pdfIntent = Intent(Intent.ACTION_VIEW)
    pdfIntent.setDataAndType(Uri.fromFile(pdfFile), "application/pdf")
    pdfIntent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY)

    //Create Viewer Intent
    val viewerIntent = Intent.createChooser(pdfIntent, "Open PDF")
    context.startActivity(viewerIntent)
}

Tracking changes in Windows registry

PhiLho has mentioned AutoRuns in passing, but I think it deserves elaboration.

It doesn't scan the whole registry, just the parts containing references to things which get loaded automatically (EXEs, DLLs, drivers etc.) which is probably what you are interested in. It doesn't track changes but can export to a text file, so you can run it before and after installation and do a diff.

How does @synchronized lock/unlock in Objective-C?

It just associates a semaphore with every object, and uses that.

How to break nested loops in JavaScript?

See Aaron's. Otherwise: j=5;i=5 instead of break.

How to convert string to binary?

def method_a(sample_string):
    binary = ' '.join(format(ord(x), 'b') for x in sample_string)

def method_b(sample_string):
    binary = ' '.join(map(bin,bytearray(sample_string,encoding='utf-8')))


if __name__ == '__main__':

    from timeit import timeit

    sample_string = 'Convert this ascii strong to binary.'

    print(
        timeit(f'method_a("{sample_string}")',setup='from __main__ import method_a'),
        timeit(f'method_b("{sample_string}")',setup='from __main__ import method_b')
    )

# 9.564299999998184 2.943955828988692

method_b is substantially more efficient at converting to a byte array because it makes low level function calls instead of manually transforming every character to an integer, and then converting that integer into its binary value.