Programs & Examples On #Layout extraction

You don't have permission to access / on this server

Set required all granted in /etc/httpd/conf/httpd.conf

Accessing JPEG EXIF rotation data in JavaScript on the client side

You can use the exif-js library in combination with the HTML5 File API: http://jsfiddle.net/xQnMd/1/.

$("input").change(function() {
    var file = this.files[0];  // file
        fr   = new FileReader; // to read file contents

    fr.onloadend = function() {
        // get EXIF data
        var exif = EXIF.readFromBinaryFile(new BinaryFile(this.result));

        // alert a value
        alert(exif.Make);
    };

    fr.readAsBinaryString(file); // read the file
});

How to add spacing between columns?

Bootstrap 4, file custom.scss you can add following code:

$grid-gutter-width-base: 20px;

$grid-gutter-widths: ( xs: $grid-gutter-width-base, 
sm: $grid-gutter-width-base, 
md: $grid-gutter-width-base, 
lg: $grid-gutter-width-base, 
xl: $grid-gutter-width-base
);

by default $grid-gutter-width-base: 30px;

How to hide collapsible Bootstrap 4 navbar on click

You can call $.collapse('hide'); with an event handler on the links.

_x000D_
_x000D_
$('.nav-link').on('click',function() {_x000D_
  $('.navbar-collapse').collapse('hide');_x000D_
});
_x000D_
.navbar-toggler .icon-bar {_x000D_
  margin: 7px;_x000D_
  display: block;_x000D_
  width: 22px;_x000D_
  height: 1px;_x000D_
  background-color: #cccccc;_x000D_
  border-radius: 1px;_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-alpha.6/js/bootstrap.min.js"></script>_x000D_
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
<nav class="navbar navbar-toggleable-md fixed-top">_x000D_
  <button id="nav-btn" class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarDiv" aria-expanded="false" aria-label="Toggle navigation">_x000D_
        <span class="icon-bar"></span>_x000D_
        <span class="icon-bar"></span>_x000D_
        <span class="icon-bar"></span>_x000D_
 </button>_x000D_
  <div class="container">_x000D_
    <a class="navbar-brand" href="#"><img src="Images/logo.png" width="60px"></a>_x000D_
    <div class="collapse navbar-collapse" id="navbarDiv">_x000D_
      <ul class="navbar-nav mr-auto">_x000D_
        <li class="nav-item active">_x000D_
          <a class="nav-link" href="#home">Home <span class="sr-only">(current)</span></a>_x000D_
        </li>_x000D_
        <li class="nav-item">_x000D_
          <a class="nav-link" href="#about-us">About</a>_x000D_
        </li>_x000D_
        <li class="nav-item">_x000D_
          <a class="nav-link" href="#pricing">Pricing</a>_x000D_
        </li>_x000D_
      </ul>_x000D_
    </div>_x000D_
  </div>_x000D_
</nav>
_x000D_
_x000D_
_x000D_

PHP Fatal error when trying to access phpmyadmin mb_detect_encoding

Try to install mysqli and pdo. Put it in terminal:

./configure --with-mysql=/usr/bin/mysql_config  \
--with-mysqli=mysqlnd \
--with-pdo-mysql=mysqlnd

Can you autoplay HTML5 videos on the iPad?

In this Safari HTML5 reference, you can read

To prevent unsolicited downloads over cellular networks at the user’s expense, embedded media cannot be played automatically in Safari on iOS—the user always initiates playback. A controller is automatically supplied on iPhone or iPod touch once playback in initiated, but for iPad you must either set the controls attribute or provide a controller using JavaScript.

How do you change the character encoding of a postgres database?

Dumping a database with a specific encoding and try to restore it on another database with a different encoding could result in data corruption. Data encoding must be set BEFORE any data is inserted into the database.

Check this : When copying any other database, the encoding and locale settings cannot be changed from those of the source database, because that might result in corrupt data.

And this : Some locale categories must have their values fixed when the database is created. You can use different settings for different databases, but once a database is created, you cannot change them for that database anymore. LC_COLLATE and LC_CTYPE are these categories. They affect the sort order of indexes, so they must be kept fixed, or indexes on text columns would become corrupt. (But you can alleviate this restriction using collations, as discussed in Section 22.2.) The default values for these categories are determined when initdb is run, and those values are used when new databases are created, unless specified otherwise in the CREATE DATABASE command.


I would rather rebuild everything from the begining properly with a correct local encoding on your debian OS as explained here :

su root

Reconfigure your local settings :

dpkg-reconfigure locales

Choose your locale (like for instance for french in Switzerland : fr_CH.UTF8)

Uninstall and clean properly postgresql :

apt-get --purge remove postgresql\*
rm -r /etc/postgresql/
rm -r /etc/postgresql-common/
rm -r /var/lib/postgresql/
userdel -r postgres
groupdel postgres

Re-install postgresql :

aptitude install postgresql-9.1 postgresql-contrib-9.1 postgresql-doc-9.1

Now any new database will be automatically be created with correct encoding, LC_TYPE (character classification), and LC_COLLATE (string sort order).

Linux bash: Multiple variable assignment

I think this might help...

In order to break down user inputted dates (mm/dd/yyyy) in my scripts, I store the day, month, and year into an array, and then put the values into separate variables as follows:

DATE_ARRAY=(`echo $2 | sed -e 's/\// /g'`)
MONTH=(`echo ${DATE_ARRAY[0]}`)
DAY=(`echo ${DATE_ARRAY[1]}`)
YEAR=(`echo ${DATE_ARRAY[2]}`)

java.net.BindException: Address already in use: JVM_Bind <null>:80

I faced this problem while working in a spring project with tomcat:

Address already in use: JVM_Bind

screenshot of bin folder

To resolve the issue I ran a shutdown.bat file in tomcat/bin folder.

File is universal (three slices), but it does not contain a(n) ARMv7-s slice error for static libraries on iOS, anyway to bypass?

use menu Project -> Build Settings ->

then remove armv7s from the"valid architectures". If standard has been chosen then delete that and then add armv7.

Java: get greatest common divisor

You can use this implementation of Binary GCD algorithm

public class BinaryGCD {

public static int gcd(int p, int q) {
    if (q == 0) return p;
    if (p == 0) return q;

    // p and q even
    if ((p & 1) == 0 && (q & 1) == 0) return gcd(p >> 1, q >> 1) << 1;

    // p is even, q is odd
    else if ((p & 1) == 0) return gcd(p >> 1, q);

    // p is odd, q is even
    else if ((q & 1) == 0) return gcd(p, q >> 1);

    // p and q odd, p >= q
    else if (p >= q) return gcd((p-q) >> 1, q);

    // p and q odd, p < q
    else return gcd(p, (q-p) >> 1);
}

public static void main(String[] args) {
    int p = Integer.parseInt(args[0]);
    int q = Integer.parseInt(args[1]);
    System.out.println("gcd(" + p + ", " + q + ") = " + gcd(p, q));
}

}

From http://introcs.cs.princeton.edu/java/23recursion/BinaryGCD.java.html

How can you tell if a value is not numeric in Oracle?

REGEXP_LIKE(column, '^[[:digit:]]+$')

returns TRUE if column holds only numeric characters

Form/JavaScript not working on IE 11 with error DOM7011

I have seen exactly the same error, also with IE11. In my case the issue occurred when user clicked <button> element, which was inside <form> tags.

The issue was remedied, by placing the <button> outside of <form> tags.

Detect changes in the DOM

MutationObserver = window.MutationObserver || window.WebKitMutationObserver;

var observer = new MutationObserver(function(mutations, observer) {
    // fired when a mutation occurs
    console.log(mutations, observer);
    // ...
});

// define what element should be observed by the observer
// and what types of mutations trigger the callback
observer.observe(document, {
  subtree: true,
  attributes: true
  //...
});

Complete explanations: https://stackoverflow.com/a/11546242/6569224

Assign width to half available screen width declaratively

give width as 0dp to make sure its size is exactly as per its weight this will make sure that even if content of child views get bigger, they'll still be limited to exactly half(according to is weight)

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:weightSum="1"
     >

    <Button
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:text="click me"
    android:layout_weight="0.5"/>


    <TextView
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:text="Hello World"
    android:layout_weight="0.5"/>
  </LinearLayout>

Image change every 30 seconds - loop

You should take a look at various javascript libraries, they should be able to help you out:

All of them have tutorials, and fade in/fade out is a basic usage.

For e.g. in jQuery:

var $img = $("img"), i = 0, speed = 200;
window.setInterval(function() {
  $img.fadeOut(speed, function() {
    $img.attr("src", images[(++i % images.length)]);
    $img.fadeIn(speed);
  });
}, 30000);

Enum String Name from Value

If you need to get a string "Visible" without getting EnumDisplayStatus instance you can do this:

int dbValue = GetDBValue();
string stringValue = Enum.GetName(typeof(EnumDisplayStatus), dbValue);

Draw path between two points using Google Maps Android API v2

Dont know whether I should put this as answer or not...

I used @Zeeshan0026's solution to draw the path...and the problem was that if I draw path once, and then I do try to draw path once again, both two paths show and this continues...paths showing even when markers were deleted... while, ideally, old paths' shouldn't be there once new path is drawn / markers are deleted..

going through some other question over SO, I had the following solution

I add the following function in Zeeshan's class

 public void clearRoute(){

         for(Polyline line1 : polylines)
         {
             line1.remove();
         }

         polylines.clear();

     }

in my map activity, before drawing the path, I called this function.. example usage as per my app is

private Route rt;

rt.clearRoute();

            if (src == null) {
                Toast.makeText(getApplicationContext(), "Please select your Source", Toast.LENGTH_LONG).show();
            }else if (Destination == null) {
                Toast.makeText(getApplicationContext(), "Please select your Destination", Toast.LENGTH_LONG).show();
            }else if (src.equals(Destination)) {
                Toast.makeText(getApplicationContext(), "Source and Destinatin can not be the same..", Toast.LENGTH_LONG).show();
            }else{

                rt.drawRoute(mMap, MapsMainActivity.this, src,
                        Destination, false, "en");
            }

you can use rt.clearRoute(); as per your requirements.. Hoping that it will save a few minutes of someone else and will help some beginner in solving this issue..

Complete Class Code

see on github

Edit: here is part of code from mainactivity..

case R.id.mkrbtn_set_dest:
                    Destination = selmarker.getPosition();
                    destmarker = selmarker;
                    desShape = createRouteCircle(Destination, false);

                    if (src == null) {
                        Toast.makeText(getApplicationContext(),
                                "Please select your Source first...",
                                Toast.LENGTH_LONG).show();
                    } else if (src.equals(Destination)) {
                        Toast.makeText(getApplicationContext(),
                                "Source and Destinatin can not be the same..",
                                Toast.LENGTH_LONG).show();
                    } else {

                        if (isNetworkAvailable()) {
                            rt.drawRoute(mMap, MapsMainActivity.this, src,
                                    Destination, false, "en");
                            src = null;
                            Destination = null;

                        } else {
                            Toast.makeText(
                                    getApplicationContext(),
                                    "Internet Connection seems to be OFFLINE...!",
                                    Toast.LENGTH_LONG).show();

                        }

                    }

                    break;

Edit 2 as per comments

usage :

//variables as data members
GoogleMap mMap;
private Route rt;
static LatLng src;
static LatLng Destination;
//MapsMainActivity is my activity
//false for interim stops for traffic, google
// en language for html description returned

rt.drawRoute(mMap, MapsMainActivity.this, src,
                            Destination, false, "en");

Invert match with regexp

Okay, I have refined my regular expression based on the solution you came up with (which erroneously matches strings that start with 'test').

^((?!foo).)*$

This regular expression will match only strings that do not contain foo. The first lookahead will deny strings beginning with 'foo', and the second will make sure that foo isn't found elsewhere in the string.

How to modify the nodejs request default timeout time?

Linking to express issue #3330

You may set the timeout either globally for entire server:

var server = app.listen();
server.setTimeout(500000);

or just for specific route:

app.post('/xxx', function (req, res) {
   req.setTimeout(500000);
});

Add ripple effect to my button with button background color?

Add Ripple Effect/Animation to a Android Button

Just replace your button background attribute with android:background="?attr/selectableItemBackground" and your code looks like this.

      <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="?attr/selectableItemBackground"
        android:text="New Button" />

Another Way to Add Ripple Effect/Animation to an Android Button

Using this method, you can customize ripple effect color. First, you have to create a xml file in your drawable resource directory. Create a ripple_effect.xml file and add following code. res/drawable/ripple_effect.xml

<?xml version="1.0" encoding="utf-8"?>
<ripple xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:color="#f816a463"
    tools:targetApi="lollipop">
    <item android:id="@android:id/mask">
        <shape android:shape="rectangle">
            <solid android:color="#f816a463" />
        </shape>
    </item>
</ripple>

And set background of button to above drawable resource file

<Button
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@drawable/ripple_effect"
    android:padding="16dp"
    android:text="New Button" />

How do you list the primary key of a SQL Server table?

Sys.Objects Table contains row for each user-defined, schema-scoped object .

Constraints created like Primary Key or others will be the object and Table name will be the parent_object

Query sys.Objects and collect the Object's Ids of Required Type

declare @TableName nvarchar(50)='TblInvoice' -- your table name
declare @TypeOfKey nvarchar(50)='PK' -- For Primary key

SELECT Name FROM sys.objects
WHERE type = @TypeOfKey 
AND  parent_object_id = OBJECT_ID (@TableName)

Download a working local copy of a webpage

wget is capable of doing what you are asking. Just try the following:

wget -p -k http://www.example.com/

The -p will get you all the required elements to view the site correctly (css, images, etc). The -k will change all links (to include those for CSS & images) to allow you to view the page offline as it appeared online.

From the Wget docs:

‘-k’
‘--convert-links’
After the download is complete, convert the links in the document to make them
suitable for local viewing. This affects not only the visible hyperlinks, but
any part of the document that links to external content, such as embedded images,
links to style sheets, hyperlinks to non-html content, etc.

Each link will be changed in one of the two ways:

    The links to files that have been downloaded by Wget will be changed to refer
    to the file they point to as a relative link.

    Example: if the downloaded file /foo/doc.html links to /bar/img.gif, also
    downloaded, then the link in doc.html will be modified to point to
    ‘../bar/img.gif’. This kind of transformation works reliably for arbitrary
    combinations of directories.

    The links to files that have not been downloaded by Wget will be changed to
    include host name and absolute path of the location they point to.

    Example: if the downloaded file /foo/doc.html links to /bar/img.gif (or to
    ../bar/img.gif), then the link in doc.html will be modified to point to
    http://hostname/bar/img.gif. 

Because of this, local browsing works reliably: if a linked file was downloaded,
the link will refer to its local name; if it was not downloaded, the link will
refer to its full Internet address rather than presenting a broken link. The fact
that the former links are converted to relative links ensures that you can move
the downloaded hierarchy to another directory.

Note that only at the end of the download can Wget know which links have been
downloaded. Because of that, the work done by ‘-k’ will be performed at the end
of all the downloads. 

printf and long double

From the printf manpage:

l (ell) A following integer conversion corresponds to a long int or unsigned long int argument, or a following n conversion corresponds to a pointer to a long int argument, or a following c conversion corresponds to a wint_t argument, or a following s conversion corresponds to a pointer to wchar_t argument.

and

L A following a, A, e, E, f, F, g, or G conversion corresponds to a long double argument. (C99 allows %LF, but SUSv2 does not.)

So, you want %Le , not %le

Edit: Some further investigation seems to indicate that Mingw uses the MSVC/win32 runtime(for stuff like printf) - which maps long double to double. So mixing a compiler (like gcc) that provides a native long double with a runtime that does not seems to .. be a mess.

How to normalize a vector in MATLAB efficiently? Any related built-in function?

I don't know any MATLAB and I've never used it, but it seems to me you are dividing. Why? Something like this will be much faster:

d = 1/norm(V)
V1 = V * d

Convert python long/int to fixed size byte array

Python 2.7 does not implement the int.to- very slow_bytes() method.

I tried 3 methods:

  1. hex unpack/pack : very slow
  2. byte shifting 8 bits at a time: significantly faster.
  3. using a "C" module and packing into the lower (7 ia64 or 3 i32) bytes. This was about twice as fast as 2/ . It is the fastest option, but still too slow.

All these methods are very inefficient for two reasons:

  • Python 2.7 does not support this useful operation.
  • c does not support extended precision arithmetic using the carry/borrow/overflow flags available on most platforms.

MVC Razor Radio Button

<label>@Html.RadioButton("ABC", "YES")Yes</label>
<label>@Html.RadioButton("ABC", "NO")No</label>

Tomcat manager/html is not available?

After entering the roles and users in tomcat-users still if does not work make sure your tomact server location point to the right server location

VS 2012: Scroll Solution Explorer to current file

On Visual Studio 2017, the shortcut is: Ctrl+´,S.

enter image description here

How can I compare two strings in java and define which of them is smaller than the other alphabetically?

If you would like to ignore case you could use the following:

String s = "yip";
String best = "yodel";
int compare = s.compareToIgnoreCase(best);
if(compare < 0){
    //-1, --> s is less than best. ( s comes alphabetically first)
}
else if(compare > 0 ){
// best comes alphabetically first.
}
else{
    // strings are equal.
}

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

My problem was I'm using RVM and had the wrong Ruby version activated...

Hope this helps at least one person

How to save the contents of a div as a image?

Do something like this:

A <div> with ID of #imageDIV, another one with ID #download and a hidden <div> with ID #previewImage.

Include the latest version of jquery, and jspdf.debug.js from the jspdf CDN

Then add this script:

var element = $("#imageDIV"); // global variable
var getCanvas; // global variable
$('document').ready(function(){
  html2canvas(element, {
    onrendered: function (canvas) {
      $("#previewImage").append(canvas);
      getCanvas = canvas;
    }
  });
});
$("#download").on('click', function () {
  var imgageData = getCanvas.toDataURL("image/png");
  // Now browser starts downloading it instead of just showing it
  var newData = imageData.replace(/^data:image\/png/, "data:application/octet-stream");
  $("#download").attr("download", "image.png").attr("href", newData);
});

The div will be saved as a PNG on clicking the #download

JavaFX "Location is required." even though it is in the same package

The root directory for the loader is in the 'resources' folder for a maven project. So if you have src/main/java then the fxml file path should start from: src/main/resources

https://maven.apache.org/guides/introduction/introduction-to-the-standard-directory-layout.html

How to hide TabPage from TabControl

you can set the parent of the tabpage to null for hiding and to show just set tabpage parent to the tabcontrol

how to end ng serve or firebase serve

Try using ctrl + c twice to get the prompt for terminating the batch job.

How to add the text "ON" and "OFF" to toggle button

Square version of the toggle can be added by modifying the border radius

_x000D_
_x000D_
.switch {
  position: relative;
  display: inline-block;
  width: 90px;
  height: 36px;
}

.switch input {display:none;}

.slider {
  position: absolute;
  cursor: pointer;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: #ca2222;
  -webkit-transition: .4s;
  transition: .4s;
  border-radius: 6px;
}

.slider:before {
  position: absolute;
  content: "";
  height: 34px;
  width: 32px;
  top: 1px;
  left: 1px;
  right: 1px;
  bottom: 1px;
  background-color: white;
  transition: 0.4s;
  border-radius: 6px;
}

input:checked + .slider {
  background-color: #2ab934;
}

input:focus + .slider {
  box-shadow: 0 0 1px #2196F3;
}

input:checked + .slider:before {
  -webkit-transform: translateX(26px);
  -ms-transform: translateX(26px);
  transform: translateX(55px);
}

.slider:after {
  content:'OFF';
  color: white;
  display: block;
  position: absolute;
  transform: translate(-50%,-50%);
  top: 50%;
  left: 50%;
  font-size: 10px;
  font-family: Verdana, sans-serif;
}
input:checked + .slider:after {
  content:'ON';
}
_x000D_
<label class="switch">
  <input type="checkbox" id="togBtn">
  <div class="slider"></div>
</label>
_x000D_
_x000D_
_x000D_

enter image description here

How to find the width of a div using vanilla JavaScript?

You can also search the DOM using ClassName. For example:

document.getElementsByClassName("myDiv")

This will return an array. If there is one particular property you are interested in. For example:

var divWidth = document.getElementsByClassName("myDiv")[0].clientWidth;

divWidth will now be equal to the the width of the first element in your div array.

What to do on TransactionTooLargeException

There isn't one specific cause of this problem.For me, in my Fragment class I was doing this:

public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    super.onCreateView(inflater, container, savedInstanceState);
    View rootView = inflater.inflate(R.layout.snacks_layout, container); //<-- notice the absence of the false argument
    return rootView;
}

instead of this:

View rootView = inflater.inflate(R.layout.softs_layout, container, false);

Android: Storing username and password?

You should use the Android AccountManager. It's purpose-built for this scenario. It's a little bit cumbersome but one of the things it does is invalidate the local credentials if the SIM card changes, so if somebody swipes your phone and throws a new SIM in it, your credentials won't be compromised.

This also gives the user a quick and easy way to access (and potentially delete) the stored credentials for any account they have on the device, all from one place.

SampleSyncAdapter (like @Miguel mentioned) is an example that makes use of stored account credentials.

What’s the best way to reload / refresh an iframe?

document.getElementById('some_frame_id').contentWindow.location.reload();

be careful, in Firefox, window.frames[] cannot be indexed by id, but by name or index

How do you enable auto-complete functionality in Visual Studio C++ express edition?

Start writing, then just press CTRL+SPACE and there you go ...

Could not find method android() for arguments

This error appear because the compiler could not found "my-upload-key.keystore" file in your project

After you have generated the file you need to paste it into project's andorid/app folder

this worked for me!

Styling Password Fields in CSS

I found I could improve the situation a little with CSS dedicated to Webkit (Safari, Chrome). However, I had to set a fixed width and height on the field because the font change will resize the field.

@media screen and (-webkit-min-device-pixel-ratio:0){ /* START WEBKIT */
  INPUT[type="password"]{
  font-family:Verdana,sans-serif;
  height:28px;
  font-size:19px;
  width:223px;
  padding:5px;
  }
} /* END WEBKIT */

The CSRF token is invalid. Please try to resubmit the form

I hade the same issue recently, and my case was something that's not mentioned here yet:

The problem was I was testing it on localhost domain. I'm not sure why exactly was this an issue, but it started to work after I added a host name alias for localhost into /etc/hosts like this:

127.0.0.1        foobar

There's probably something wrong with the session while using Apache and localhost as a domain. If anyone can elaborate in the comments I'd be happy to edit this answer to include more details.

Cast object to T

Add a 'class' constraint (or more detailed, like a base class or interface of your exepected T objects):

private static T ReadData<T>(XmlReader reader, string value) where T : class
{
    reader.MoveToAttribute(value);
    object readData = reader.ReadContentAsObject();
    return (T)readData;
}

or where T : IMyInterface or where T : new(), etc

How to Convert date into MM/DD/YY format in C#

DateTime.Today.ToString("MM/dd/yy")

Look at the docs for custom date and time format strings for more info.

(Oh, and I hope this app isn't destined for other cultures. That format could really confuse a lot of people... I've never understood the whole month/day/year thing, to be honest. It just seems weird to go "middle/low/high" in terms of scale like that.)

Others cultures really are a problem. For example, that code in portugues returns someting like 01-01-01 instead of 01/01/01. I also don't undestand why...

To resolve that problem i do someting like this:

        IFormatProvider yyyymmddFormat = new System.Globalization.CultureInfo(String.Empty, false);
        return date.ToString("MM/dd/yy", yyyymmddFormat);

Converting between datetime, Timestamp and datetime64

Welcome to hell.

You can just pass a datetime64 object to pandas.Timestamp:

In [16]: Timestamp(numpy.datetime64('2012-05-01T01:00:00.000000'))
Out[16]: <Timestamp: 2012-05-01 01:00:00>

I noticed that this doesn't work right though in NumPy 1.6.1:

numpy.datetime64('2012-05-01T01:00:00.000000+0100')

Also, pandas.to_datetime can be used (this is off of the dev version, haven't checked v0.9.1):

In [24]: pandas.to_datetime('2012-05-01T01:00:00.000000+0100')
Out[24]: datetime.datetime(2012, 5, 1, 1, 0, tzinfo=tzoffset(None, 3600))

annotation to make a private method public only for test classes

As much as I know there is no annotation like this. The best way is to use reflection as some of the others suggested. Look at this post:
How do I test a class that has private methods, fields or inner classes?

You should only watch out on testing the exception outcome of the method. For example: if u expect an IllegalArgumentException, but instead you'll get "null" (Class:java.lang.reflect.InvocationTargetException).
A colegue of mine proposed using the powermock framework for these situations, but I haven't tested it yet, so no idea what exactly it can do. Although I have used the Mockito framework that it is based upon and thats a good framework too (but I think doesn't solve the private method exception issue).

It's a great idea though having the @PublicForTests annotation.

Cheers!

org.hibernate.QueryException: could not resolve property: filename

Hibernate queries are case sensitive with property names (because they end up relying on getter/setter methods on the @Entity).

Make sure you refer to the property as fileName in the Criteria query, not filename.

Specifically, Hibernate will call the getter method of the filename property when executing that Criteria query, so it will look for a method called getFilename(). But the property is called FileName and the getter getFileName().

So, change the projection like so:

criteria.setProjection(Projections.property("fileName"));

SSIS package creating Hresult: 0x80004005 Description: "Login timeout expired" error

The answer here is not clear, so I wanted to add more detail.

Using the link provided above, I performed the following step.

In my XML config manager I changed the "Provider" to SQLOLEDB.1 rather than SQLNCLI.1. This got me past this error.

This information is available at the link the OP posted in the Answer.

The link the got me there: http://social.msdn.microsoft.com/Forums/en-US/sqlintegrationservices/thread/fab0e3bf-4adf-4f17-b9f6-7b7f9db6523c/

Python object deleting itself

You don't need to use del to delete instances in the first place. Once the last reference to an object is gone, the object will be garbage collected. Maybe you should tell us more about the full problem.

SSH to AWS Instance without key pairs

AWS added a new feature to connect to instance without any open port, the AWS SSM Session Manager. https://aws.amazon.com/blogs/aws/new-session-manager/

I've created a neat SSH ProxyCommand script that temporary adds your public ssh key to target instance during connection to target instance. The nice thing about this is you will connect without the need to add the ssh(22) port to your security groups, because the ssh connection is tunneled through ssm session manager.

AWS SSM SSH ProxyComand -> https://gist.github.com/qoomon/fcf2c85194c55aee34b78ddcaa9e83a1

Right Align button in horizontal LinearLayout

Use layout width in the button like android:layout_width="75dp"

What is "stdafx.h" used for in Visual Studio?

"Stdafx.h" is a precompiled header.It include file for standard system include files and for project-specific include files that are used frequently but are changed infrequently.which reduces compile time and Unnecessary Processing.

Precompiled Header stdafx.h is basically used in Microsoft Visual Studio to let the compiler know the files that are once compiled and no need to compile it from scratch. You can read more about it

http://www.cplusplus.com/articles/1TUq5Di1/

https://docs.microsoft.com/en-us/cpp/ide/precompiled-header-files?view=vs-2017

How do I determine whether my calculation of pi is accurate?

Since I'm the current world record holder for the most digits of pi, I'll add my two cents:

Unless you're actually setting a new world record, the common practice is just to verify the computed digits against the known values. So that's simple enough.

In fact, I have a webpage that lists snippets of digits for the purpose of verifying computations against them: http://www.numberworld.org/digits/Pi/


But when you get into world-record territory, there's nothing to compare against.

Historically, the standard approach for verifying that computed digits are correct is to recompute the digits using a second algorithm. So if either computation goes bad, the digits at the end won't match.

This does typically more than double the amount of time needed (since the second algorithm is usually slower). But it's the only way to verify the computed digits once you've wandered into the uncharted territory of never-before-computed digits and a new world record.


Back in the days where supercomputers were setting the records, two different AGM algorithms were commonly used:

These are both O(N log(N)^2) algorithms that were fairly easy to implement.

However, nowadays, things are a bit different. In the last three world records, instead of performing two computations, we performed only one computation using the fastest known formula (Chudnovsky Formula):

Enter image description here

This algorithm is much harder to implement, but it is a lot faster than the AGM algorithms.

Then we verify the binary digits using the BBP formulas for digit extraction.

Enter image description here

This formula allows you to compute arbitrary binary digits without computing all the digits before it. So it is used to verify the last few computed binary digits. Therefore it is much faster than a full computation.

The advantage of this is:

  1. Only one expensive computation is needed.

The disadvantage is:

  1. An implementation of the Bailey–Borwein–Plouffe (BBP) formula is needed.
  2. An additional step is needed to verify the radix conversion from binary to decimal.

I've glossed over some details of why verifying the last few digits implies that all the digits are correct. But it is easy to see this since any computation error will propagate to the last digits.


Now this last step (verifying the conversion) is actually fairly important. One of the previous world record holders actually called us out on this because, initially, I didn't give a sufficient description of how it worked.

So I've pulled this snippet from my blog:

N = # of decimal digits desired
p = 64-bit prime number

Enter image description here

Compute A using base 10 arithmetic and B using binary arithmetic.

Enter image description here

If A = B, then with "extremely high probability", the conversion is correct.


For further reading, see my blog post Pi - 5 Trillion Digits.

What Language is Used To Develop Using Unity

i remember this from reading some articles about performance in unity from internet which awaring javascript users from using it in unity about really massive issues of using javascript in unity instead of C#, it says that C# is almost 4x faster than javascript!
i really appreciate that article b/c it saved my ass when i was about to start gaming, i dont mean that javascript it bad for unity developers , it is good but my advice could be that if you like using javascript, you should use it for simple small gamesNOT FOR BIG PROJECTS because it really can be a damn problem!

WPF User Control Parent

If you just want to get a specific parent, not only the window, a specific parent in the tree structure, and also not using recursion, or hard break loop counters, you can use the following:

public static T FindParent<T>(DependencyObject current)
    where T : class 
{
    var dependency = current;

    while((dependency = VisualTreeHelper.GetParent(dependency) ?? LogicalTreeHelper.GetParent(dependency)) != null
        && !(dependency is T)) { }

    return dependency as T;
}

Just don't put this call in a constructor (since the Parent property is not yet initialized). Add it in the loading event handler, or in other parts of your application.

Get type name without full namespace

Try this to get type parameters for generic types:

public static string CSharpName(this Type type)
{
    var sb = new StringBuilder();
    var name = type.Name;
    if (!type.IsGenericType) return name;
    sb.Append(name.Substring(0, name.IndexOf('`')));
    sb.Append("<");
    sb.Append(string.Join(", ", type.GetGenericArguments()
                                    .Select(t => t.CSharpName())));
    sb.Append(">");
    return sb.ToString();
}

Maybe not the best solution (due to the recursion), but it works. Outputs look like:

Dictionary<String, Object>

Best practice for REST token-based authentication with JAX-RS and Jersey

This answer is all about authorization and it is a complement of my previous answer about authentication

Why another answer? I attempted to expand my previous answer by adding details on how to support JSR-250 annotations. However the original answer became the way too long and exceeded the maximum length of 30,000 characters. So I moved the whole authorization details to this answer, keeping the other answer focused on performing authentication and issuing tokens.


Supporting role-based authorization with the @Secured annotation

Besides authentication flow shown in the other answer, role-based authorization can be supported in the REST endpoints.

Create an enumeration and define the roles according to your needs:

public enum Role {
    ROLE_1,
    ROLE_2,
    ROLE_3
}

Change the @Secured name binding annotation created before to support roles:

@NameBinding
@Retention(RUNTIME)
@Target({TYPE, METHOD})
public @interface Secured {
    Role[] value() default {};
}

And then annotate the resource classes and methods with @Secured to perform the authorization. The method annotations will override the class annotations:

@Path("/example")
@Secured({Role.ROLE_1})
public class ExampleResource {

    @GET
    @Path("{id}")
    @Produces(MediaType.APPLICATION_JSON)
    public Response myMethod(@PathParam("id") Long id) {
        // This method is not annotated with @Secured
        // But it's declared within a class annotated with @Secured({Role.ROLE_1})
        // So it only can be executed by the users who have the ROLE_1 role
        ...
    }

    @DELETE
    @Path("{id}")    
    @Produces(MediaType.APPLICATION_JSON)
    @Secured({Role.ROLE_1, Role.ROLE_2})
    public Response myOtherMethod(@PathParam("id") Long id) {
        // This method is annotated with @Secured({Role.ROLE_1, Role.ROLE_2})
        // The method annotation overrides the class annotation
        // So it only can be executed by the users who have the ROLE_1 or ROLE_2 roles
        ...
    }
}

Create a filter with the AUTHORIZATION priority, which is executed after the AUTHENTICATION priority filter defined previously.

The ResourceInfo can be used to get the resource Method and resource Class that will handle the request and then extract the @Secured annotations from them:

@Secured
@Provider
@Priority(Priorities.AUTHORIZATION)
public class AuthorizationFilter implements ContainerRequestFilter {

    @Context
    private ResourceInfo resourceInfo;

    @Override
    public void filter(ContainerRequestContext requestContext) throws IOException {

        // Get the resource class which matches with the requested URL
        // Extract the roles declared by it
        Class<?> resourceClass = resourceInfo.getResourceClass();
        List<Role> classRoles = extractRoles(resourceClass);

        // Get the resource method which matches with the requested URL
        // Extract the roles declared by it
        Method resourceMethod = resourceInfo.getResourceMethod();
        List<Role> methodRoles = extractRoles(resourceMethod);

        try {

            // Check if the user is allowed to execute the method
            // The method annotations override the class annotations
            if (methodRoles.isEmpty()) {
                checkPermissions(classRoles);
            } else {
                checkPermissions(methodRoles);
            }

        } catch (Exception e) {
            requestContext.abortWith(
                Response.status(Response.Status.FORBIDDEN).build());
        }
    }

    // Extract the roles from the annotated element
    private List<Role> extractRoles(AnnotatedElement annotatedElement) {
        if (annotatedElement == null) {
            return new ArrayList<Role>();
        } else {
            Secured secured = annotatedElement.getAnnotation(Secured.class);
            if (secured == null) {
                return new ArrayList<Role>();
            } else {
                Role[] allowedRoles = secured.value();
                return Arrays.asList(allowedRoles);
            }
        }
    }

    private void checkPermissions(List<Role> allowedRoles) throws Exception {
        // Check if the user contains one of the allowed roles
        // Throw an Exception if the user has not permission to execute the method
    }
}

If the user has no permission to execute the operation, the request is aborted with a 403 (Forbidden).

To know the user who is performing the request, see my previous answer. You can get it from the SecurityContext (which should be already set in the ContainerRequestContext) or inject it using CDI, depending on the approach you go for.

If a @Secured annotation has no roles declared, you can assume all authenticated users can access that endpoint, disregarding the roles the users have.

Supporting role-based authorization with JSR-250 annotations

Alternatively to defining the roles in the @Secured annotation as shown above, you could consider JSR-250 annotations such as @RolesAllowed, @PermitAll and @DenyAll.

JAX-RS doesn't support such annotations out-of-the-box, but it could be achieved with a filter. Here are a few considerations to keep in mind if you want to support all of them:

So an authorization filter that checks JSR-250 annotations could be like:

@Provider
@Priority(Priorities.AUTHORIZATION)
public class AuthorizationFilter implements ContainerRequestFilter {

    @Context
    private ResourceInfo resourceInfo;

    @Override
    public void filter(ContainerRequestContext requestContext) throws IOException {

        Method method = resourceInfo.getResourceMethod();

        // @DenyAll on the method takes precedence over @RolesAllowed and @PermitAll
        if (method.isAnnotationPresent(DenyAll.class)) {
            refuseRequest();
        }

        // @RolesAllowed on the method takes precedence over @PermitAll
        RolesAllowed rolesAllowed = method.getAnnotation(RolesAllowed.class);
        if (rolesAllowed != null) {
            performAuthorization(rolesAllowed.value(), requestContext);
            return;
        }

        // @PermitAll on the method takes precedence over @RolesAllowed on the class
        if (method.isAnnotationPresent(PermitAll.class)) {
            // Do nothing
            return;
        }

        // @DenyAll can't be attached to classes

        // @RolesAllowed on the class takes precedence over @PermitAll on the class
        rolesAllowed = 
            resourceInfo.getResourceClass().getAnnotation(RolesAllowed.class);
        if (rolesAllowed != null) {
            performAuthorization(rolesAllowed.value(), requestContext);
        }

        // @PermitAll on the class
        if (resourceInfo.getResourceClass().isAnnotationPresent(PermitAll.class)) {
            // Do nothing
            return;
        }

        // Authentication is required for non-annotated methods
        if (!isAuthenticated(requestContext)) {
            refuseRequest();
        }
    }

    /**
     * Perform authorization based on roles.
     *
     * @param rolesAllowed
     * @param requestContext
     */
    private void performAuthorization(String[] rolesAllowed, 
                                      ContainerRequestContext requestContext) {

        if (rolesAllowed.length > 0 && !isAuthenticated(requestContext)) {
            refuseRequest();
        }

        for (final String role : rolesAllowed) {
            if (requestContext.getSecurityContext().isUserInRole(role)) {
                return;
            }
        }

        refuseRequest();
    }

    /**
     * Check if the user is authenticated.
     *
     * @param requestContext
     * @return
     */
    private boolean isAuthenticated(final ContainerRequestContext requestContext) {
        // Return true if the user is authenticated or false otherwise
        // An implementation could be like:
        // return requestContext.getSecurityContext().getUserPrincipal() != null;
    }

    /**
     * Refuse the request.
     */
    private void refuseRequest() {
        throw new AccessDeniedException(
            "You don't have permissions to perform this action.");
    }
}

Note: The above implementation is based on the Jersey RolesAllowedDynamicFeature. If you use Jersey, you don't need to write your own filter, just use the existing implementation.

Adding horizontal spacing between divs in Bootstrap 3

From what I understand you want to make a navigation bar or something similar to it. What I recommend doing is making a list and editing the items from there. Just try this;

<ul>
    <li class='item col-md-12 panel' id='gameplay-title'>Title</li>
    <li class='item col-md-6 col-md-offset-3 panel' id='gameplay-scoreboard'>Scoreboard</li>
</ul>

And so on... To add more categories add another ul in there. Now, for the CSS you just need this;

ul {
    list-style: none;
}
.item {
    display: inline;
    padding-right: 20px;
}

json_encode sparse PHP array as JSON array, not JSON object

Array in JSON are indexed array only, so the structure you're trying to get is not valid Json/Javascript.

PHP Associatives array are objects in JSON, so unless you don't need the index, you can't do such conversions.

If you want to get such structure you can do:

$indexedOnly = array();

foreach ($associative as $row) {
    $indexedOnly[] = array_values($row);
}

json_encode($indexedOnly);

Will returns something like:

[
     [0, "name1", "n1"],
     [1, "name2", "n2"],
]

How to set up java logging using a properties file? (java.util.logging)

Logger log = Logger.getLogger("myApp");
log.setLevel(Level.ALL);
log.info("initializing - trying to load configuration file ...");

//Properties preferences = new Properties();
try {
    //FileInputStream configFile = new //FileInputStream("/path/to/app.properties");
    //preferences.load(configFile);
    InputStream configFile = myApp.class.getResourceAsStream("app.properties");
    LogManager.getLogManager().readConfiguration(configFile);
} catch (IOException ex)
{
    System.out.println("WARNING: Could not open configuration file");
    System.out.println("WARNING: Logging not configured (console output only)");
}
log.info("starting myApp");

this is working..:) you have to pass InputStream in readConfiguration().

Failed to open/create the internal network Vagrant on Windows10

I have Windows 8.1 and had this problem with VirtualBox 5.0.16.105871. I tried every suggestion I found here, virtual box site, and other forums. None worked for me. I had this error when tried to start a VM with host-only interface:

Failed to open a session for the virtual machine LinuxVMDev0.

Failed to open/create the internal network 'HostInterfaceNetworking-VirtualBox Host-Only Ethernet Adapter' (VERR_INTNET_FLT_IF_NOT_FOUND).

Failed to attach the network LUN (VERR_INTNET_FLT_IF_NOT_FOUND).

Result Code: E_FAIL (0x80004005)
Component: ConsoleWrap
Interface: IConsole {872da645-4a9b-1727-bee2-5585105b9eed}

Finally the only solution that worked for me was:

  1. Uninstall 5.0.16
  2. Install version 4.3.36 that did not have this problem (at least in my PC)
  3. Without uninstalling 4.3.36, install version 5.0.16 in the default way

(Always installing as Administrator, i.e. running the installer as administrator).

That worked for me after trying different solution during days.

ThreadStart with parameters

One of the 2 overloads of the Thread constructor takse a ParameterizedThreadStart delegate which allows you to pass a single parameter to the start method. Unfortunately though it only allows for a single parameter and it does so in an unsafe way because it passes it as object. I find it's much easier to use a lambda expression to capture the relevant parameters and pass them in a strongly typed fashion.

Try the following

public Thread StartTheThread(SomeType param1, SomeOtherType param2) {
  var t = new Thread(() => RealStart(param1, param2));
  t.Start();
  return t;
}

private static void RealStart(SomeType param1, SomeOtherType param2) {
  ...
}

What is a "bundle" in an Android application

Bundle is used to pass data between Activities. You can create a bundle, pass it to Intent that starts the activity which then can be used from the destination activity.

What does the "@" symbol do in Powershell?

The Splatting Operator

To create an array, we create a variable and assign the array. Arrays are noted by the "@" symbol. Let's take the discussion above and use an array to connect to multiple remote computers:

$strComputers = @("Server1", "Server2", "Server3")<enter>

They are used for arrays and hashes.

PowerShell Tutorial 7: Accumulate, Recall, and Modify Data

Array Literals In PowerShell

How to make PyCharm always show line numbers

v. community 5.0.4 (linux): File -> Settings -> Editor -> General -> Appearance -> now check 'Show line numbers', confirm w. OK an voila :)

How to pass parameter to function using in addEventListener?

No need to pass anything in. The function used for addEventListener will automatically have this bound to the current element. Simply use this in your function:

productLineSelect.addEventListener('change', getSelection, false);

function getSelection() {
    var value = this.options[this.selectedIndex].value;
    alert(value);
}

Here's the fiddle: http://jsfiddle.net/dJ4Wm/


If you want to pass arbitrary data to the function, wrap it in your own anonymous function call:

productLineSelect.addEventListener('change', function() {
    foo('bar');
}, false);

function foo(message) {
    alert(message);
}

Here's the fiddle: http://jsfiddle.net/t4Gun/


If you want to set the value of this manually, you can use the call method to call the function:

var self = this;
productLineSelect.addEventListener('change', function() {
    getSelection.call(self);
    // This'll set the `this` value inside of `getSelection` to `self`
}, false);

function getSelection() {
    var value = this.options[this.selectedIndex].value;
    alert(value);
}

How to select rows for a specific date, ignoring time in SQL Server

You can remove the time component when comparing:

SELECT * 
FROM sales 
WHERE CONVERT(DATETIME, FLOOR(CONVERT(FLOAT, salesDate))) = '11/11/2010'

Another approach is to change the select to cover all the time between the start and end of the date:

SELECT * 
FROM sales 
-- WHERE salesDate BETWEEN '11/11/2010 00:00:00.00' AND '11/11/2010 23:59:59.999'
WHERE salesDate BETWEEN '2020-05-18T00:00:00.00' AND '2020-05-18T23:59:59.999'

How can I convert a string to a number in Perl?

In comparisons it makes a difference if a scalar is a number of a string. And it is not always decidable. I can report a case where perl retrieved a float in "scientific" notation and used that same a few lines below in a comparison:

use strict;
....
next unless $line =~ /and your result is:\s*(.*)/;
my $val = $1;
if ($val < 0.001) {
   print "this is small\n";
}

And here $val was not interpreted as numeric for e.g. "2e-77" retrieved from $line. Adding 0 (or 0.0 for good ole C programmers) helped.

Reading a binary file with python

You could use numpy.fromfile, which can read data from both text and binary files. You would first construct a data type, which represents your file format, using numpy.dtype, and then read this type from file using numpy.fromfile.

How to suppress Update Links warning?

(I don't have enough rep points to add a comment, but I want to add some clarity on the answers here)

Application.AskToUpdateLinks = False is probably not what you want.

If set to False, then MS Excel will attempt to update the links automatically it just won't prompt the user beforehand, sorta counter-intuitive.

The correct solution, if you're looking to open a file without updating links should be:

Workbook.Open(UpdateLinks:=0)

Related link: Difference in AskToUpdateLinks=False and UpdateLinks:=0

How to group dataframe rows into list in pandas groupby

As you were saying the groupby method of a pd.DataFrame object can do the job.

Example

 L = ['A','A','B','B','B','C']
 N = [1,2,5,5,4,6]

 import pandas as pd
 df = pd.DataFrame(zip(L,N),columns = list('LN'))


 groups = df.groupby(df.L)

 groups.groups
      {'A': [0, 1], 'B': [2, 3, 4], 'C': [5]}

which gives and index-wise description of the groups.

To get elements of single groups, you can do, for instance

 groups.get_group('A')

     L  N
  0  A  1
  1  A  2

  groups.get_group('B')

     L  N
  2  B  5
  3  B  5
  4  B  4

Convert Enum to String

I create a "Description" extension method and attach it to the enum so that i can get truly user-friendly naming that includes spaces and casing. I have never liked using the enum value itself as displayable text because it is something we developers use to create more readable code. It is not intended for UI display purposes. I want to be able to change the UI without going through and changing enums all over.

Environment variables in Mac OS X

For 2020 Mac OS X Catalina users:

Forget about other useless answers, here only two steps needed:

  1. Create a file with the naming convention: priority-appname. Then copy-paste the path you want to add to PATH.

    E.g. 80-vscode with content /Applications/Visual Studio Code.app/Contents/Resources/app/bin/ in my case.

  2. Move that file to /etc/paths.d/. Don't forget to open a new tab(new session) in the Terminal and type echo $PATH to check that your path is added!

Notice: this method only appends your path to PATH.

How to install pip for Python 3.6 on Ubuntu 16.10?

This website contains a much cleaner solution, it leaves pip intact as-well and one can easily switch between 3.5 and 3.6 and then whenever 3.7 is released.

http://ubuntuhandbook.org/index.php/2017/07/install-python-3-6-1-in-ubuntu-16-04-lts/

A short summary:

sudo apt-get install python python-pip python3 python3-pip
sudo add-apt-repository ppa:jonathonf/python-3.6
sudo apt-get update
sudo apt-get install python3.6
sudo update-alternatives --install /usr/bin/python3 python3 /usr/bin/python3.5 1
sudo update-alternatives --install /usr/bin/python3 python3 /usr/bin/python3.6 2

Then

$ pip -V
pip 8.1.1 from /usr/lib/python2.7/dist-packages (python 2.7)
$ pip3 -V
pip 8.1.1 from /usr/local/lib/python3.5/dist-packages (python 3.5)

Then to select python 3.6 run

sudo update-alternatives --config python3

and select '2'. Then

$ pip3 -V
pip 8.1.1 from /usr/local/lib/python3.6/dist-packages (python 3.6)

To update pip select the desired version and

pip3 install --upgrade pip

$ pip3 -V
pip 9.0.1 from /usr/local/lib/python3.6/dist-packages (python 3.6)

Tested on Ubuntu 16.04.

How to concatenate properties from multiple JavaScript objects

You could use jquery's $.extend like this:

_x000D_
_x000D_
let a = { "one" : 1, "two" : 2 },_x000D_
    b = { "three" : 3 },_x000D_
    c = { "four" : 4, "five" : 5 };_x000D_
_x000D_
let d = $.extend({}, a, b, c)_x000D_
_x000D_
console.log(d)
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
_x000D_
_x000D_
_x000D_

Composer killed while updating

DigitalOcean fix that does not require extra memory - activating swap, here is an example for 1gb:

in terminal run below

/bin/dd if=/dev/zero of=/var/swap.1 bs=1M count=1024
/sbin/mkswap /var/swap.1
sudo /sbin/swapon /var/swap.1

The above solution will work until the next reboot, after that the swap would have to be reactivated. To persist it between the reboots add the swap file to fstab:

sudo nano /etc/fstab

open the above file add add below line to the file

/var/swap.1 swap swap sw 0 0

now restart the server. Composer require works fine.

CodeIgniter removing index.php from url

+ Copy .htaccess from Application to Root folder
+ edit .htaccess and put

<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteBase /ci_test/

    #Removes access to the system folder by users.
    #Additionally this will allow you to create a System.php controller,
    #previously this would not have been possible.
    #'system' can be replaced if you have renamed your system folder.
    RewriteCond %{REQUEST_URI} ^system.*
    RewriteRule ^(.*)$ /index.php?/$1 [L]

    #When your application folder isn't in the system folder
    #This snippet prevents user access to the application folder
    #Submitted by: Fabdrol
    #Rename 'application' to your applications folder name.
    RewriteCond %{REQUEST_URI} ^application.*
    RewriteRule ^(.*)$ /index.php?/$1 [L]

    #Checks to see if the user is attempting to access a valid file,
    #such as an image or css document, if this isn't true it sends the
    #request to index.php
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)$ index.php?/$1 [L]
</IfModule>

<IfModule !mod_rewrite.c>
    # If we don't have mod_rewrite installed, all 404's
    # can be sent to index.php, and everything works as normal.
    # Submitted by: ElliotHaughin

    ErrorDocument 404 /index.php
</IfModule>

Note: make sure your web server is enable for  "rewrite_module"

+ Remove index.php from $config['index_page'] = 'index.php';
- edit config.php in application/config
- search for index.php
change it from  $config['index_page'] = 'index.php'; to  $config['index_page'] = '';

Please watch this videos for reference https://www.youtube.com/watch?v=HFG2nMDn35Q

Python: List vs Dict for look up table

You want a dict.

For (unsorted) lists in Python, the "in" operation requires O(n) time---not good when you have a large amount of data. A dict, on the other hand, is a hash table, so you can expect O(1) lookup time.

As others have noted, you might choose a set (a special type of dict) instead, if you only have keys rather than key/value pairs.

Related:

  • Python wiki: information on the time complexity of Python container operations.
  • SO: Python container operation time and memory complexities

How to ignore SSL certificate errors in Apache HttpClient 4.0

Just for the record, there is a much simpler way to accomplish the same with HttpClient 4.1

    SSLSocketFactory sslsf = new SSLSocketFactory(new TrustStrategy() {

        public boolean isTrusted(
                final X509Certificate[] chain, String authType) throws CertificateException {
            // Oh, I am easy...
            return true;
        }

    });

Linux command to check if a shell script is running or not

Adding to the answers above -

To use in a script, use the following :-

result=`ps aux | grep -i "myscript.sh" | grep -v "grep" | wc -l`
if [ $result -ge 1 ]
   then
        echo "script is running"
   else
        echo "script is not running"
fi

iOS Detection of Screenshot?

I found the answer!! Taking a screenshot interrupts any touches that are on the screen. This is why snapchat requires holding to see the picture. Reference: http://tumblr.jeremyjohnstone.com/post/38503925370/how-to-detect-screenshots-on-ios-like-snapchat

splitting a number into the integer and decimal parts

intpart,decimalpart = int(value),value-int(value)

Works for positive numbers.

How to remove foreign key constraint in sql server?

Try following

ALTER TABLE <TABLE_NAME> DROP CONSTRAINT <FOREIGN_KEY_NAME>

Refer : http://www.w3schools.com/sql/sql_foreignkey.asp

error: expected declaration or statement at end of input in c

Normally that error occurs when a } was missed somewhere in the code, for example:

void mi_start_curr_serv(void){
    #if 0
    //stmt
    #endif

would fail with this error due to the missing } at the end of the function. The code you posted doesn't have this error, so it is likely coming from some other part of your source.

React prevent event bubbling in nested components on click

You can avoid event bubbling by checking target of event.
For example if you have input nested to the div element where you have handler for click event, and you don't want to handle it, when input is clicked, you can just pass event.target into your handler and check is handler should be executed based on properties of target.
For example you can check if (target.localName === "input") { return}.
So, it's a way to "avoid" handler execution

node.js, socket.io with SSL

On the same note, if your server supports both http and https you can connect using:

var socket = io.connect('//localhost');

to auto detect the browser scheme and connect using http/https accordingly. when in https, the transport will be secured by default, as connecting using

var socket = io.connect('https://localhost');

will use secure web sockets - wss:// (the {secure: true} is redundant).

for more information on how to serve both http and https easily using the same node server check out this answer.

How to hide element label by element id in CSS?

You probably have to add a class/id to and then make another CSS declaration that hides it as well.

Random "Element is no longer attached to the DOM" StaleElementReferenceException

Just happened to me when trying to send_keys to a search input box - that has autoupdate depending on what you type in. As mentioned by Eero, this can happen if your element does some Ajax updated while you are typing in your text inside the input element. The solution is to send one character at a time and search again for the input element. (Ex. in ruby shown below)

def send_keys_eachchar(webdriver, elem_locator, text_to_send)
  text_to_send.each_char do |char|
    input_elem = webdriver.find_element(elem_locator)
    input_elem.send_keys(char)
  end
end

Get startup type of Windows service using PowerShell

If you update to PowerShell 5 you can query all of the services on the machine and display Name and StartType and sort it by StartType for easy viewing:

Get-Service |Select-Object -Property Name,StartType |Sort-Object -Property StartType

split string in two on given index and return both parts

function splitText(value, index) {
  if (value.length < index) {return value;} 
  return [value.substring(0, index)].concat(splitText(value.substring(index), index));
}
console.log(splitText('this is a testing peace of text',10));
// ["this is a ", "testing pe", "ace of tex", "t"] 

For those who want to split a text into array using the index.

Convert a PHP script into a stand-alone windows executable

I tried most of solution given in the 1st answer, the only one that worked for me and is non-commercial is php-desktop.

I simply put my php files in the www/ folder, changed the name of .exe and was able to run my php as an exe !!

Also there is a complete documentation, up to date support, windows and linux (and soon mac) compatibility and options can easily be changed.

Reload parent window from child window

For Atlassian Connect Apps, use AP.navigator.reload();

See details here

How to set the background image of a html 5 canvas to .png image

You can use this plugin, but for printing purpose i have added some code like <button onclick="window.print();">Print</button> and for saving image <button onclick="savePhoto();">Save Picture</button>

     function savePhoto() {
     var canvas = document.getElementById("canvas");
     var img    = canvas.toDataURL("image/png");
     window.location = img;}

checkout this plugin http://www.williammalone.com/articles/create-html5-canvas-javascript-drawing-app

How do I keep jQuery UI Accordion collapsed by default?

Add the active: false option (documentation)..

$("#accordion").accordion({ header: "h3", collapsible: true, active: false });

How do you show animated GIFs on a Windows Form (c#)

Note that in Windows, you traditionally don't use animated Gifs, but little AVI animations: there is a Windows native control just to display them. There are even tools to convert animated Gifs to AVI (and vice-versa).

Can RDP clients launch remote applications and not desktops

This is called "seamless" mode. rdesktop, the RDP client for Unix, is capable of this. From the manpage:

   -A     Enable SeamlessRDP. In this mode, rdesktop creates a X11 window for each window on the server
          side.  This  mode  requires  the  SeamlessRDP  server side component, which is available from
          http://www.cendio.com/seamlessrdp/.  When using this option, you  should  specify  a  startup
          shell which launches the desired application through SeamlessRDP.

See mentioned Cendio website for more information.

Count number of rows per group and add result to original data frame

Using sqldf package:

library(sqldf)

sqldf("select a.*, b.cnt
       from df a,
           (select name, type, count(1) as cnt
            from df
            group by name, type) b
      where a.name = b.name and
            a.type = b.type")

#    name  type num cnt
# 1 black chair   4   2
# 2 black chair   5   2
# 3 black  sofa  12   1
# 4   red  sofa   4   1
# 5   red plate   3   1

Excel cell value as string won't store as string

Use Range("A1").Text instead of .Value

post comment edit:
Why?
Because the .Text property of Range object returns what is literally visible in the spreadsheet, so if you cell displays for example i100l:25he*_92 then <- Text will return exactly what it in the cell including any formatting.
The .Value and .Value2 properties return what's stored in the cell under the hood excluding formatting. Specially .Value2 for date types, it will return the decimal representation.

If you want to dig deeper into the meaning and performance, I just found this article which seems like a good guide

another edit
Here you go @Santosh
type in (MANUALLY) the values from the DEFAULT (col A) to other columns
Do not format column A at all
Format column B as Text
Format column C as Date[dd/mm/yyyy]
Format column D as Percentage
Dont Format column A, Format B as TEXT, C as Date, D as Percentage
now,
paste this code in a module

Sub main()

    Dim ws As Worksheet, i&, j&
    Set ws = Sheets(1)
    For i = 3 To 7
        For j = 1 To 4
            Debug.Print _
                    "row " & i & vbTab & vbTab & _
                    Cells(i, j).Text & vbTab & _
                    Cells(i, j).Value & vbTab & _
                    Cells(i, j).Value2
        Next j
    Next i
End Sub

and Analyse the output! Its really easy and there isn't much more i can do to help :)

            .TEXT              .VALUE             .VALUE2
row 3       hello             hello               hello
row 3       hello             hello               hello
row 3       hello             hello               hello
row 3       hello             hello               hello
row 4       1                 1                   1
row 4       1                 1                   1
row 4       01/01/1900        31/12/1899          1
row 4       1.00%             0.01                0.01
row 5       helo1$$           helo1$$             helo1$$
row 5       helo1$$           helo1$$             helo1$$
row 5       helo1$$           helo1$$             helo1$$
row 5       helo1$$           helo1$$             helo1$$
row 6       63                63                  63
row 6       =7*9              =7*9                =7*9
row 6       03/03/1900        03/03/1900          63
row 6       6300.00%          63                  63
row 7       29/05/2013        29/05/2013          41423
row 7       29/05/2013        29/05/2013          29/05/2013
row 7       29/05/2013        29/05/2013          41423
row 7       29/05/2013%       29/05/2013%         29/05/2013%

How do I use StringUtils in Java?

StringUtils is an Apache Commons project. You need to download and add the library to your classpath.

To use:

import org.apache.commons.lang3.StringUtils;

How can I call controller/view helper methods from the console in Ruby on Rails?

The earlier answers are calling helpers, but the following will help for calling controller methods. I have used this on Ruby on Rails 2.3.2.

First add the following code to your .irbrc file (which can be in your home directory)

class Object
   def request(options = {})
     url=app.url_for(options)
     app.get(url)
     puts app.html_document.root.to_s
  end
end

Then in the Ruby on Rails console you can type something like...

request(:controller => :show, :action => :show_frontpage)

...and the HTML will be dumped to the console.

Restart android machine

adb reboot should not reboot your linux box.

But in any case, you can redirect the command to a specific adb device using adb -s <device_id> command , where

Device ID can be obtained from the command adb devices
command in this case is reboot

Is there a command line utility for rendering GitHub flavored Markdown?

I created a tool similar to Atom's Preview functionality, but as a standalone application. Not sure if this is what you're looking for, but it might be helpful. -- https://github.com/yoshuawuyts/vmd

vmd

Using request.setAttribute in a JSP page

Try

request.getSession().setAttribute("SUBFAMILY", subFam);
request.getSession().getAttribute("SUBFAMILY");

How to set default value for column of new created table from select statement in 11g

The reason is that CTAS (Create table as select) does not copy any metadata from the source to the target table, namely

  • no primary key
  • no foreign keys
  • no grants
  • no indexes
  • ...

To achieve what you want, I'd either

  • use dbms_metadata.get_ddl to get the complete table structure, replace the table name with the new name, execute this statement, and do an INSERT afterward to copy the data
  • or keep using CTAS, extract the not null constraints for the source table from user_constraints and add them to the target table afterwards

Loop through JSON in EJS

JSON.stringify returns a String. So, for example:

var data = [
    { id: 1, name: "bob" },
    { id: 2, name: "john" },
    { id: 3, name: "jake" },
];

JSON.stringify(data)

will return the equivalent of:

"[{\"id\":1,\"name\":\"bob\"},{\"id\":2,\"name\":\"john\"},{\"id\":3,\"name\":\"jake\"}]"

as a String value.

So when you have

<% for(var i=0; i<JSON.stringify(data).length; i++) {%>

what that ends up looking like is:

<% for(var i=0; i<"[{\"id\":1,\"name\":\"bob\"},{\"id\":2,\"name\":\"john\"},{\"id\":3,\"name\":\"jake\"}]".length; i++) {%>

which is probably not what you want. What you probably do want is something like this:

<table>
<% for(var i=0; i < data.length; i++) { %>
   <tr>
     <td><%= data[i].id %></td>
     <td><%= data[i].name %></td>
   </tr>
<% } %>
</table>

This will output the following table (using the example data from above):

<table>
  <tr>
    <td>1</td>
    <td>bob</td>
  </tr>
  <tr>
    <td>2</td>
    <td>john</td>
  </tr>
  <tr>
    <td>3</td>
    <td>jake</td>
  </tr>
</table>

How to npm install to a specified directory?

You can use the --prefix option:

mkdir -p ./install/here/node_modules
npm install --prefix ./install/here <package>

The package(s) will then be installed in ./install/here/node_modules. The mkdir is needed since npm might otherwise choose an already existing node_modules directory higher up in the hierarchy. (See npm documentation on folders.)

Creating an iframe with given HTML dynamically

There is an alternative for creating an iframe whose contents are a string of HTML: the srcdoc attribute. This is not supported in older browsers (chief among them: Internet Explorer, and possibly Safari?), but there is a polyfill for this behavior, which you could put in conditional comments for IE, or use something like has.js to conditionally lazy load it.

psql: FATAL: role "postgres" does not exist

NOTE: If you installed postgres using homebrew, see the comment from @user3402754 below.

Note that the error message does NOT talk about a missing database, it talks about a missing role. Later in the login process it might also stumble over the missing database.

But the first step is to check the missing role: What is the output within psql of the command \du ? On my Ubuntu system the relevant line looks like this:

                              List of roles
 Role name |            Attributes             | Member of 
-----------+-----------------------------------+-----------
 postgres  | Superuser, Create role, Create DB | {}        

If there is not at least one role with superuser, then you have a problem :-)

If there is one, you can use that to login. And looking at the output of your \l command: The permissions for user on the template0 and template1 databases are the same as on my Ubuntu system for the superuser postgres. So I think your setup simple uses user as the superuser. So you could try this command to login:

sudo -u user psql user

If user is really the DB superuser you can create another DB superuser and a private, empty database for him:

CREATE USER postgres SUPERUSER;
CREATE DATABASE postgres WITH OWNER postgres;

But since your postgres.app setup does not seem to do this, you also should not. Simple adapt the tutorial.

Docker-compose: node_modules not present in a volume after npm install succeeds

You can try something like this in your Dockerfile:

FROM node:0.12
WORKDIR /worker
CMD bash ./start.sh

Then you should use the Volume like this:

volumes:
  - worker/:/worker:rw

The startscript should be a part of your worker repository and looks like this:

#!/bin/sh
npm install
npm start

So the node_modules are a part of your worker volume and gets synchronized and the npm scripts are executed when everything is up.

VBA Print to PDF and Save with Automatic File Name

Hopefully this is self explanatory enough. Use the comments in the code to help understand what is happening. Pass a single cell to this function. The value of that cell will be the base file name. If the cell contains "AwesomeData" then we will try and create a file in the current users desktop called AwesomeData.pdf. If that already exists then try AwesomeData2.pdf and so on. In your code you could just replace the lines filename = Application..... with filename = GetFileName(Range("A1"))

Function GetFileName(rngNamedCell As Range) As String
    Dim strSaveDirectory As String: strSaveDirectory = ""
    Dim strFileName As String: strFileName = ""
    Dim strTestPath As String: strTestPath = ""
    Dim strFileBaseName As String: strFileBaseName = ""
    Dim strFilePath As String: strFilePath = ""
    Dim intFileCounterIndex As Integer: intFileCounterIndex = 1

    ' Get the users desktop directory.
    strSaveDirectory = Environ("USERPROFILE") & "\Desktop\"
    Debug.Print "Saving to: " & strSaveDirectory

    ' Base file name
    strFileBaseName = Trim(rngNamedCell.Value)
    Debug.Print "File Name will contain: " & strFileBaseName

    ' Loop until we find a free file number
    Do
        If intFileCounterIndex > 1 Then
            ' Build test path base on current counter exists.
            strTestPath = strSaveDirectory & strFileBaseName & Trim(Str(intFileCounterIndex)) & ".pdf"
        Else
            ' Build test path base just on base name to see if it exists.
            strTestPath = strSaveDirectory & strFileBaseName & ".pdf"
        End If

        If (Dir(strTestPath) = "") Then
            ' This file path does not currently exist. Use that.
            strFileName = strTestPath
        Else
            ' Increase the counter as we have not found a free file yet.
            intFileCounterIndex = intFileCounterIndex + 1
        End If

    Loop Until strFileName <> ""

    ' Found useable filename
    Debug.Print "Free file name: " & strFileName
    GetFileName = strFileName

End Function

The debug lines will help you figure out what is happening if you need to step through the code. Remove them as you see fit. I went a little crazy with the variables but it was to make this as clear as possible.

In Action

My cell O1 contained the string "FileName" without the quotes. Used this sub to call my function and it saved a file.

Sub Testing()
    Dim filename As String: filename = GetFileName(Range("o1"))

    ActiveWorkbook.Worksheets("Sheet1").Range("A1:N24").ExportAsFixedFormat Type:=xlTypePDF, _
                                              filename:=filename, _
                                              Quality:=xlQualityStandard, _
                                              IncludeDocProperties:=True, _
                                              IgnorePrintAreas:=False, _
                                              OpenAfterPublish:=False
End Sub

Where is your code located in reference to everything else? Perhaps you need to make a module if you have not already and move your existing code into there.

Mailbox unavailable. The server response was: 5.7.1 Unable to relay Error

WE had this issue. everything was setup fine in terms of permissions and security.

after MUCH needling around in the haystack. the issue was some sort of heuristics. in the email body , anytime a certain email address was listed, we would get the above error message from our exchange server.

it took 2 days of crazy testing and hair pulling to find this.

so if you have checked everything out, try changing the email body to only the word 'test'. If after that, your email goes out fine, you are having some sort of spam/heuristic filter issue like we were

How to import or copy images to the "res" folder in Android Studio?

If you want to do this easily from within Android Studio then on the left side, right above your file directory you will see a dropdown with options on how to view your files like:

Project, Android, and Packages, plus a list of Scopes.

If you are on Android it makes it hard to see when you add new folders or assets to your project - BUT if you change the dropdown to PROJECT then the file directory will match the file system on your computer, then go to:

app > src > main > res

From here you can find the conventional Eclipse type files like drawable/drawable-hdpi/drawable-mdpi and so on where you can easily drag and drop files into or import into and instantly see them. As soon as you see your files here they will be available when going to assign image src's and so on.

Good luck Android Warriors in a strange new world!

Fill background color left to right CSS

A single css code on hover can do the trick: box-shadow: inset 100px 0 0 0 #e0e0e0;

A complete demo can be found in my fiddle:

https://jsfiddle.net/shuvamallick/3o0h5oka/

Display MessageBox in ASP

Here is one way of doing it:

    <%
       Dim message    
       message = "This is my message"
       Response.Write("<script language=VBScript>MsgBox """ + message + """</script>") 
    %>

How to show a running progress bar while page is loading

It’s a chicken-and-egg problem. You won’t be able to do it because you need to load the assets to display the progress bar widget, by which time your page will be either fully or partially downloaded. Also, you need to know the total size of the page prior to the user requesting in order to calculate a percentage.

It’s more hassle than it’s worth.

slideToggle JQuery right to left

include Jquery and Jquery UI plugins and try this

 $("#LeftSidePane").toggle('slide','left',400);

PHP cURL HTTP PUT

Using Postman for Chrome, selecting CODE you get this... And works

_x000D_
_x000D_
<?php_x000D_
_x000D_
$curl = curl_init();_x000D_
_x000D_
curl_setopt_array($curl, array(_x000D_
  CURLOPT_URL => "https://blablabla.com/comorl",_x000D_
  CURLOPT_RETURNTRANSFER => true,_x000D_
  CURLOPT_ENCODING => "",_x000D_
  CURLOPT_MAXREDIRS => 10,_x000D_
  CURLOPT_TIMEOUT => 30,_x000D_
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,_x000D_
  CURLOPT_CUSTOMREQUEST => "PUT",_x000D_
  CURLOPT_POSTFIELDS => "{\n  \"customer\" : \"con\",\n  \"customerID\" : \"5108\",\n  \"customerEmail\" : \"[email protected]\",\n  \"Phone\" : \"34600000000\",\n  \"Active\" : false,\n  \"AudioWelcome\" : \"https://audio.com/welcome-defecto-es.mp3\"\n\n}",_x000D_
  CURLOPT_HTTPHEADER => array(_x000D_
    "cache-control: no-cache",_x000D_
    "content-type: application/json",_x000D_
    "x-api-key: whateveriyouneedinyourheader"_x000D_
  ),_x000D_
));_x000D_
_x000D_
$response = curl_exec($curl);_x000D_
$err = curl_error($curl);_x000D_
_x000D_
curl_close($curl);_x000D_
_x000D_
if ($err) {_x000D_
  echo "cURL Error #:" . $err;_x000D_
} else {_x000D_
  echo $response;_x000D_
}_x000D_
_x000D_
?>
_x000D_
_x000D_
_x000D_

Git update submodules recursively

In recent Git (I'm using v2.15.1), the following will merge upstream submodule changes into the submodules recursively:

git submodule update --recursive --remote --merge

You may add --init to initialize any uninitialized submodules and use --rebase if you want to rebase instead of merge.

You need to commit the changes afterwards:

git add . && git commit -m 'Update submodules to latest revisions'

How to draw a line in android

  final SurfaceView surf = (SurfaceView)findViewById(R.id.surface_home);
                surf.setOnTouchListener( new SurfaceView.OnTouchListener(){
                    private boolean moving = false;//stupid state
                    public boolean onTouch(View v, MotionEvent event) {
                        switch( event.getAction() ){
                        case MotionEvent.ACTION_DOWN:
                            final int x = (int)event.getX();
                            final int y = (int)event.getY();
                            final Rect bounds = mTiles.getBounds();
                            moving = bounds.intersects(x, y, x+1, y+1);
                            return true;
                        case MotionEvent.ACTION_MOVE:
                            if( moving ){
                                final int x_new = (int)event.getX();
                                final int y_new = (int)event.getY();
                                mDrawTiles.draw( new DrawLogic(){
                                    public void draw(Rect _surface) {
                                        mTiles.setBounds(
                                            x_new - mDrawWidth/2,
                                            y_new - mDrawHeight/2,
                                            x_new + mDrawWidth/2,
                                            y_new + mDrawHeight/2);
                                        }
                                    });

Does bootstrap 4 have a built in horizontal divider?

I am using this example in my project:

html:

 <hr class="my-3 dividerClass"/>

css:

.dividerClass{
  border-top-color: #999
 }

Jump to function definition in vim

1- install exuberant ctags. If you're using osx, this article shows a little trick: http://www.runtime-era.com/2012/05/exuberant-ctags-in-osx-107.html

2- If you only wish to include the ctags for the files in your directory only, run this command in your directory:

ctags -R

This will create a "tags" file for you.

3- If you're using Ruby and wish to include the ctags for your gems (this has been really helpful for me with RubyMotion and local gems that I have developed), do the following:

ctags --exclude=.git --exclude='*.log' -R * `bundle show --paths`

credit: https://coderwall.com/p/lv1qww (Note that I omitted the -e option which generates tags for emacs instead of vim)

4- Add the following line to your ~/.vimrc

set autochdir 
set tags+=./tags;

(Why the semi colon: http://vim.wikia.com/wiki/Single_tags_file_for_a_source_tree )

5- Go to the word you'd like to follow and hit ctrl + ] ; if you'd like to go back, use ctrl+o (source: https://stackoverflow.com/a/53929/226255)

Enums in Javascript with ES6

Maybe this solution ? :)

function createEnum (array) {
  return Object.freeze(array
    .reduce((obj, item) => {
      if (typeof item === 'string') {
        obj[item.toUpperCase()] = Symbol(item)
      }
      return obj
    }, {}))
}

Example:

createEnum(['red', 'green', 'blue']);

> {RED: Symbol(red), GREEN: Symbol(green), BLUE: Symbol(blue)}

TypeError: window.initMap is not a function

Create initMap method between "" tag or load javascript file before call google api.

_x000D_
_x000D_
<script src="Scripts/main.js"></script>_x000D_
_x000D_
<script src="https://maps.googleapis.com/maps/api/js?key=abcde&libraries=places&callback=initMap" async defer></script>
_x000D_
_x000D_
_x000D_

Get the content of a sharepoint folder with Excel VBA

IMHO the coolest way is to go via WebDAV (without Network Folder, as this is often not permitted). This can be accomplished via ActiveX Data Objects as layed out in this excellent article excellent article (code can be used directly in Excel, used the concept recently).

Hope this helps!

http://blog.itwarlocks.com/2009/04/28/accessing-webdav-in-microsoft-word-visual-basic/

the original link is dead, but at least the textual content is still available on archive.org: http://web.archive.org/web/20091008034423/http://blog.itwarlocks.com/2009/04/28/accessing-webdav-in-microsoft-word-visual-basic

Differences between fork and exec

I think some concepts from "Advanced Unix Programming" by Marc Rochkind were helpful in understanding the different roles of fork()/exec(), especially for someone used to the Windows CreateProcess() model:

A program is a collection of instructions and data that is kept in a regular file on disk. (from 1.1.2 Programs, Processes, and Threads)

.

In order to run a program, the kernel is first asked to create a new process, which is an environment in which a program executes. (also from 1.1.2 Programs, Processes, and Threads)

.

It’s impossible to understand the exec or fork system calls without fully understanding the distinction between a process and a program. If these terms are new to you, you may want to go back and review Section 1.1.2. If you’re ready to proceed now, we’ll summarize the distinction in one sentence: A process is an execution environment that consists of instruction, user-data, and system-data segments, as well as lots of other resources acquired at runtime, whereas a program is a file containing instructions and data that are used to initialize the instruction and user-data segments of a process. (from 5.3 exec System Calls)

Once you understand the distinction between a program and a process, the behavior of fork() and exec() function can be summarized as:

  • fork() creates a duplicate of the current process
  • exec() replaces the program in the current process with another program

(this is essentially a simplified 'for dummies' version of paxdiablo's much more detailed answer)

When use getOne and findOne methods Spring Data JPA

The getOne methods returns only the reference from DB (lazy loading). So basically you are outside the transaction (the Transactional you have been declare in service class is not considered), and the error occur.

fastest way to export blobs from table into individual files

I came here looking for exporting blob into file with least effort. CLR functions is not something what I'd call least effort. Here described lazier one, using OLE Automation:

declare @init int
declare @file varbinary(max) = CONVERT(varbinary(max), N'your blob here')
declare @filepath nvarchar(4000) = N'c:\temp\you file name here.txt'

EXEC sp_OACreate 'ADODB.Stream', @init OUTPUT; -- An instace created
EXEC sp_OASetProperty @init, 'Type', 1; 
EXEC sp_OAMethod @init, 'Open'; -- Calling a method
EXEC sp_OAMethod @init, 'Write', NULL, @file; -- Calling a method
EXEC sp_OAMethod @init, 'SaveToFile', NULL, @filepath, 2; -- Calling a method
EXEC sp_OAMethod @init, 'Close'; -- Calling a method
EXEC sp_OADestroy @init; -- Closed the resources

You'll potentially need to allow to run OA stored procedures on server (and then turn it off, when you're done):

sp_configure 'show advanced options', 1;  
GO  
RECONFIGURE;  
GO  
sp_configure 'Ole Automation Procedures', 1;  
GO  
RECONFIGURE;  
GO

The simplest possible JavaScript countdown timer?

I have two demos, one with jQuery and one without. Neither use date functions and are about as simple as it gets.

Demo with vanilla JavaScript

_x000D_
_x000D_
function startTimer(duration, display) {_x000D_
    var timer = duration, minutes, seconds;_x000D_
    setInterval(function () {_x000D_
        minutes = parseInt(timer / 60, 10);_x000D_
        seconds = parseInt(timer % 60, 10);_x000D_
_x000D_
        minutes = minutes < 10 ? "0" + minutes : minutes;_x000D_
        seconds = seconds < 10 ? "0" + seconds : seconds;_x000D_
_x000D_
        display.textContent = minutes + ":" + seconds;_x000D_
_x000D_
        if (--timer < 0) {_x000D_
            timer = duration;_x000D_
        }_x000D_
    }, 1000);_x000D_
}_x000D_
_x000D_
window.onload = function () {_x000D_
    var fiveMinutes = 60 * 5,_x000D_
        display = document.querySelector('#time');_x000D_
    startTimer(fiveMinutes, display);_x000D_
};
_x000D_
<body>_x000D_
    <div>Registration closes in <span id="time">05:00</span> minutes!</div>_x000D_
</body>
_x000D_
_x000D_
_x000D_

Demo with jQuery

function startTimer(duration, display) {
    var timer = duration, minutes, seconds;
    setInterval(function () {
        minutes = parseInt(timer / 60, 10);
        seconds = parseInt(timer % 60, 10);

        minutes = minutes < 10 ? "0" + minutes : minutes;
        seconds = seconds < 10 ? "0" + seconds : seconds;

        display.text(minutes + ":" + seconds);

        if (--timer < 0) {
            timer = duration;
        }
    }, 1000);
}

jQuery(function ($) {
    var fiveMinutes = 60 * 5,
        display = $('#time');
    startTimer(fiveMinutes, display);
});

However if you want a more accurate timer that is only slightly more complicated:

_x000D_
_x000D_
function startTimer(duration, display) {_x000D_
    var start = Date.now(),_x000D_
        diff,_x000D_
        minutes,_x000D_
        seconds;_x000D_
    function timer() {_x000D_
        // get the number of seconds that have elapsed since _x000D_
        // startTimer() was called_x000D_
        diff = duration - (((Date.now() - start) / 1000) | 0);_x000D_
_x000D_
        // does the same job as parseInt truncates the float_x000D_
        minutes = (diff / 60) | 0;_x000D_
        seconds = (diff % 60) | 0;_x000D_
_x000D_
        minutes = minutes < 10 ? "0" + minutes : minutes;_x000D_
        seconds = seconds < 10 ? "0" + seconds : seconds;_x000D_
_x000D_
        display.textContent = minutes + ":" + seconds; _x000D_
_x000D_
        if (diff <= 0) {_x000D_
            // add one second so that the count down starts at the full duration_x000D_
            // example 05:00 not 04:59_x000D_
            start = Date.now() + 1000;_x000D_
        }_x000D_
    };_x000D_
    // we don't want to wait a full second before the timer starts_x000D_
    timer();_x000D_
    setInterval(timer, 1000);_x000D_
}_x000D_
_x000D_
window.onload = function () {_x000D_
    var fiveMinutes = 60 * 5,_x000D_
        display = document.querySelector('#time');_x000D_
    startTimer(fiveMinutes, display);_x000D_
};
_x000D_
<body>_x000D_
    <div>Registration closes in <span id="time"></span> minutes!</div>_x000D_
</body>
_x000D_
_x000D_
_x000D_

Now that we have made a few pretty simple timers we can start to think about re-usability and separating concerns. We can do this by asking "what should a count down timer do?"

  • Should a count down timer count down? Yes
  • Should a count down timer know how to display itself on the DOM? No
  • Should a count down timer know to restart itself when it reaches 0? No
  • Should a count down timer provide a way for a client to access how much time is left? Yes

So with these things in mind lets write a better (but still very simple) CountDownTimer

function CountDownTimer(duration, granularity) {
  this.duration = duration;
  this.granularity = granularity || 1000;
  this.tickFtns = [];
  this.running = false;
}

CountDownTimer.prototype.start = function() {
  if (this.running) {
    return;
  }
  this.running = true;
  var start = Date.now(),
      that = this,
      diff, obj;

  (function timer() {
    diff = that.duration - (((Date.now() - start) / 1000) | 0);

    if (diff > 0) {
      setTimeout(timer, that.granularity);
    } else {
      diff = 0;
      that.running = false;
    }

    obj = CountDownTimer.parse(diff);
    that.tickFtns.forEach(function(ftn) {
      ftn.call(this, obj.minutes, obj.seconds);
    }, that);
  }());
};

CountDownTimer.prototype.onTick = function(ftn) {
  if (typeof ftn === 'function') {
    this.tickFtns.push(ftn);
  }
  return this;
};

CountDownTimer.prototype.expired = function() {
  return !this.running;
};

CountDownTimer.parse = function(seconds) {
  return {
    'minutes': (seconds / 60) | 0,
    'seconds': (seconds % 60) | 0
  };
};

So why is this implementation better than the others? Here are some examples of what you can do with it. Note that all but the first example can't be achieved by the startTimer functions.

An example that displays the time in XX:XX format and restarts after reaching 00:00

An example that displays the time in two different formats

An example that has two different timers and only one restarts

An example that starts the count down timer when a button is pressed

Subset and ggplot2

Here 2 options for subsetting:

Using subset from base R:

library(ggplot2)
ggplot(subset(dat,ID %in% c("P1" , "P3"))) + 
         geom_line(aes(Value1, Value2, group=ID, colour=ID))

Using subset the argument of geom_line(Note I am using plyr package to use the special . function).

library(plyr)
ggplot(data=dat)+ 
  geom_line(aes(Value1, Value2, group=ID, colour=ID),
                ,subset = .(ID %in% c("P1" , "P3")))

You can also use the complementary subsetting:

subset(dat,ID != "P2")

How do you change library location in R?

I've used this successfully inside R script:

library("reshape2",lib.loc="/path/to/R-packages/")

useful if for whatever reason libraries are in more than one place.

In Python, how do I create a string of n characters in one line of code?

To simply repeat the same letter 10 times:

string_val = "x" * 10  # gives you "xxxxxxxxxx"

And if you want something more complex, like n random lowercase letters, it's still only one line of code (not counting the import statements and defining n):

from random import choice
from string import ascii_lowercase
n = 10

string_val = "".join(choice(ascii_lowercase) for i in range(n))

How to install wkhtmltopdf on a linux based (shared hosting) web server

Chances are that without full access to this server (due to being a hosted account) you are going to have problems. I would go so far as to say that I think it is a fruitless endeavor--they have to lock servers down in hosted environments for good reason.

Call your hosting company and make the request to them to install it, but don't expect a good response--they typically won't install very custom items for single users unless there is a really good reason (bug fixes for example).

Lastly, depending on how familiar you are with server administration and what you are paying for server hosting now consider something like http://www.slicehost.com. $20 a month will get you a low grade web server (256 ram) and you can install anything you want. However, if you are running multiple sites or have heavy load the cost will go up as you need larger servers.

GL!

node.js require() cache - possible to invalidate?

I made a small module to delete module from the cache after loading. This forces reevaluation of the module next time it is required. See https://github.com/bahmutov/require-and-forget

// random.js
module.exports = Math.random()
const forget = require('require-and-forget')
const r1 = forget('./random')
const r2 = forget('./random')
// r1 and r2 will be different
// "random.js" will not be stored in the require.cache

PS: you can also put "self-destruct" into the module itself. See https://github.com/bahmutov/unload-me

PSS: more tricks with Node require in my https://glebbahmutov.com/blog/hacking-node-require/

Set up an HTTP proxy to insert a header

Rather than using a proxy, I'm using the Firefox plugin "Modify Headers" to insert headers (in my case, to fake a login using the Single Sign On so I can test as different people).

Running Java Program from Command Line Linux

If your Main class is in a package called FileManagement, then try:

java -cp . FileManagement.Main

in the parent folder of the FileManagement folder.

If your Main class is not in a package (the default package) then cd to the FileManagement folder and try:

java -cp . Main

More info about the CLASSPATH and how the JRE find classes:

Get current cursor position in a textbox

Here's one possible method.

function isMouseInBox(e) {
  var textbox = document.getElementById('textbox');

  // Box position & sizes
  var boxX = textbox.offsetLeft;
  var boxY = textbox.offsetTop;
  var boxWidth = textbox.offsetWidth;
  var boxHeight = textbox.offsetHeight;

  // Mouse position comes from the 'mousemove' event
  var mouseX = e.pageX;
  var mouseY = e.pageY;
  if(mouseX>=boxX && mouseX<=boxX+boxWidth) {
    if(mouseY>=boxY && mouseY<=boxY+boxHeight){
       // Mouse is in the box
       return true;
    }
  }
}

document.addEventListener('mousemove', function(e){
    isMouseInBox(e);
})

Is there an equivalent of lsusb for OS X

Homebrew users: you can get lsusb by installing usbutils formula from my tap:

brew install mikhailai/misc/usbutils

It installs the REAL lsusb based on Linux sources (version 007).

SignalR - Sending a message to a specific user using (IUserIdProvider) *NEW 2.0.0*

For anyone trying to do this in asp.net core. You can use claims.

public class CustomEmailProvider : IUserIdProvider
{
    public virtual string GetUserId(HubConnectionContext connection)
    {
        return connection.User?.FindFirst(ClaimTypes.Email)?.Value;
    }
}

Any identifier can be used, but it must be unique. If you use a name identifier for example, it means if there are multiple users with the same name as the recipient, the message would be delivered to them as well. I have chosen email because it is unique to every user.

Then register the service in the startup class.

services.AddSingleton<IUserIdProvider, CustomEmailProvider>();

Next. Add the claims during user registration.

var result = await _userManager.CreateAsync(user, Model.Password);
if (result.Succeeded)
{
    await _userManager.AddClaimAsync(user, new Claim(ClaimTypes.Email, Model.Email));
}

To send message to the specific user.

public class ChatHub : Hub
{
    public async Task SendMessage(string receiver, string message)
    {
        await Clients.User(receiver).SendAsync("ReceiveMessage", message);
    }
}

Note: The message sender won't be notified the message is sent. If you want a notification on the sender's end. Change the SendMessage method to this.

public async Task SendMessage(string sender, string receiver, string message)
{
    await Clients.Users(sender, receiver).SendAsync("ReceiveMessage", message);
}

These steps are only necessary if you need to change the default identifier. Otherwise, skip to the last step where you can simply send messages by passing userIds or connectionIds to SendMessage. For more

ACCESS_FINE_LOCATION AndroidManifest Permissions Not Being Granted

just remove s from the permission you are using sss you have to use ss

How can one grab a stack trace in C?

For Windows check the StackWalk64() API (also on 32bit Windows). For UNIX you should use the OS' native way to do it, or fallback to glibc's backtrace(), if availabe.

Note however that taking a Stacktrace in native code is rarely a good idea - not because it is not possible, but because you're usally trying to achieve the wrong thing.

Most of the time people try to get a stacktrace in, say, an exceptional circumstance, like when an exception is caught, an assert fails or - worst and most wrong of them all - when you get a fatal "exception" or signal like a segmentation violation.

Considering the last issue, most of the APIs will require you to explicitly allocate memory or may do it internally. Doing so in the fragile state in which your program may be currently in, may acutally make things even worse. For example, the crash report (or coredump) will not reflect the actual cause of the problem, but your failed attempt to handle it).

I assume you're trying to achive that fatal-error-handling thing, as most people seem to try that when it comes to getting a stacktrace. If so, I would rely on the debugger (during development) and letting the process coredump in production (or mini-dump on windows). Together with proper symbol-management, you should have no trouble figuring the causing instruction post-mortem.

Git Cherry-pick vs Merge Workflow

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

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

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

HTH.

Preventing SQL injection in Node.js

The library has a section in the readme about escaping. It's Javascript-native, so I do not suggest switching to node-mysql-native. The documentation states these guidelines for escaping:

Edit: node-mysql-native is also a pure-Javascript solution.

  • Numbers are left untouched
  • Booleans are converted to true / false strings
  • Date objects are converted to YYYY-mm-dd HH:ii:ss strings
  • Buffers are converted to hex strings, e.g. X'0fa5'
  • Strings are safely escaped
  • Arrays are turned into list, e.g. ['a', 'b'] turns into 'a', 'b'
  • Nested arrays are turned into grouped lists (for bulk inserts), e.g. [['a', 'b'], ['c', 'd']] turns into ('a', 'b'), ('c', 'd')
  • Objects are turned into key = 'val' pairs. Nested objects are cast to strings.
  • undefined / null are converted to NULL
  • NaN / Infinity are left as-is. MySQL does not support these, and trying to insert them as values will trigger MySQL errors until they implement support.

This allows for you to do things like so:

var userId = 5;
var query = connection.query('SELECT * FROM users WHERE id = ?', [userId], function(err, results) {
  //query.sql returns SELECT * FROM users WHERE id = '5'
});

As well as this:

var post  = {id: 1, title: 'Hello MySQL'};
var query = connection.query('INSERT INTO posts SET ?', post, function(err, result) {
  //query.sql returns INSERT INTO posts SET `id` = 1, `title` = 'Hello MySQL'
});

Aside from those functions, you can also use the escape functions:

connection.escape(query);
mysql.escape(query);

To escape query identifiers:

mysql.escapeId(identifier);

And as a response to your comment on prepared statements:

From a usability perspective, the module is great, but it has not yet implemented something akin to PHP's Prepared Statements.

The prepared statements are on the todo list for this connector, but this module at least allows you to specify custom formats that can be very similar to prepared statements. Here's an example from the readme:

connection.config.queryFormat = function (query, values) {
  if (!values) return query;
  return query.replace(/\:(\w+)/g, function (txt, key) {
    if (values.hasOwnProperty(key)) {
      return this.escape(values[key]);
    }
    return txt;
  }.bind(this));
};

This changes the query format of the connection so you can use queries like this:

connection.query("UPDATE posts SET title = :title", { title: "Hello MySQL" });
//equivalent to
connection.query("UPDATE posts SET title = " + mysql.escape("Hello MySQL");

How to check if a String is numeric in Java

Parallel checking for very long strings using IntStream

In Java 8, the following tests if all characters of the given string are within '0' to '9'. Mind that the empty string is accepted:

string.chars().unordered().parallel().allMatch( i -> '0' <= i && '9' >= i )

TypeScript: casting HTMLElement

Do not type cast. Never. Use type guards:

const e = document.getElementsByName("script")[0];
if (!(e instanceof HTMLScriptElement)) 
  throw new Error(`Expected e to be an HTMLScriptElement, was ${e && e.constructor && e.constructor.name || e}`);
// locally TypeScript now types e as an HTMLScriptElement, same as if you casted it.

Let the compiler do the work for you and get errors when your assumptions turn out wrong.

It may look overkill in this case, but it will help you a lot if you come back later and change the selector, like adding a class that is missing in the dom, for example.

how to fetch array keys with jQuery?

Don't Reinvent the Wheel, Use Underscore

I know the OP specifically mentioned jQuery but I wanted to put an answer here to introduce people to the helpful Underscore library if they are not aware of it already.

By leveraging the keys method in the Underscore library, you can simply do the following:

_.keys(foo)  #=> ["alfa", "beta"]

Plus, there's a plethora of other useful functions that are worth perusing.

How to open Visual Studio Code from the command line on OSX?

I ran: open -a "Visual Studio Code" [folder-name] to open a folder with my Visual Studio Code application. Folder name is optional if you just want to open the application. Not sure if this is exactly your use-case, but hope this helps!

"CAUTION: provisional headers are shown" in Chrome debugger

In my case it was just a false set path in to a resource (svg / img)

Google Maps V3 - How to calculate the zoom level for a given bounds

Valerio is almost right with his solution, but there is some logical mistake.

you must firstly check wether angle2 is bigger than angle, before adding 360 at a negative.

otherwise you always have a bigger value than angle

So the correct solution is:

var west = calculateMin(data.longitudes);
var east = calculateMax(data.longitudes);
var angle = east - west;
var north = calculateMax(data.latitudes);
var south = calculateMin(data.latitudes);
var angle2 = north - south;
var zoomfactor;
var delta = 0;
var horizontal = false;

if(angle2 > angle) {
    angle = angle2;
    delta = 3;
}

if (angle < 0) {
    angle += 360;
}

zoomfactor = Math.floor(Math.log(960 * 360 / angle / GLOBE_WIDTH) / Math.LN2) - 2 - delta;

Delta is there, because i have a bigger width than height.

Looping from 1 to infinity in Python

Using itertools.count:

import itertools
for i in itertools.count(start=1):
    if there_is_a_reason_to_break(i):
        break

In Python 2, range() and xrange() were limited to sys.maxsize. In Python 3 range() can go much higher, though not to infinity:

import sys
for i in range(sys.maxsize**10):  # you could go even higher if you really want
    if there_is_a_reason_to_break(i):
        break

So it's probably best to use count().

Sending emails in Node.js?

Check out emailjs

After wasting lots of time on trying to make nodemailer work with large attachments, found emailjs and happy ever since.

It supports sending files by using normal File objects, and not huge Buffers as nodemailer requires. Means that you can link it to, f.e., formidable to pass the attachments from an html form to the mailer. It also supports queueing..

All in all, no idea why nodejitsu ppl chose nodemailer to base their version on, emailjs is just much more advanced.

How to keep environment variables when using sudo

For individual variables you want to make available on a one off basis you can make it part of the command.

sudo http_proxy=$http_proxy wget "http://stackoverflow.com"

How do I get a reference to the app delegate in Swift?

Swift 4.2

In Swift, easy to access in your VC's

extension UIViewController {
    var appDelegate: AppDelegate {
    return UIApplication.shared.delegate as! AppDelegate
   }
}

How to select option in drop down using Capybara

In Capybara you can use only find with xpath

find(:xpath, "//*[@id='organizationSelect']/option[2]").click

and method click

Take screenshots in the iOS simulator

First method:

Select simulator and press "command + s" button. Screenshot saved on desktop.

Second method:

Select simulator and go to "File > New Screenshot". Screenshot saved on desktop.

Focus Input Box On Load

very simple one line solution:

<body onLoad="document.getElementById('myinputbox').focus();">

Populating spinner directly in the layout xml

I'm not sure about this, but give it a shot.

In your strings.xml define:

<string-array name="array_name">
<item>Array Item One</item>
<item>Array Item Two</item>
<item>Array Item Three</item>
</string-array>

In your layout:

<Spinner 
        android:id="@+id/spinner"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:drawSelectorOnTop="true"
        android:entries="@array/array_name"
    />

I've heard this doesn't always work on the designer, but it compiles fine.

Python/BeautifulSoup - how to remove all tags from an element?

it looks like this is the way to do! as simple as that

with this line you are joining together the all text parts within the current element

''.join(htmlelement.find(text=True))

In Python script, how do I set PYTHONPATH?

You don't set PYTHONPATH, you add entries to sys.path. It's a list of directories that should be searched for Python packages, so you can just append your directories to that list.

sys.path.append('/path/to/whatever')

In fact, sys.path is initialized by splitting the value of PYTHONPATH on the path separator character (: on Linux-like systems, ; on Windows).

You can also add directories using site.addsitedir, and that method will also take into account .pth files existing within the directories you pass. (That would not be the case with directories you specify in PYTHONPATH.)

Switch on Enum in Java

You might be using the enums incorrectly in the switch cases. In comparison with the above example by CoolBeans.. you might be doing the following:

switch(day) {
    case Day.MONDAY:
        // Something..
        break;
    case Day.FRIDAY:
        // Something friday
        break;
}

Make sure that you use the actual enum values instead of EnumType.EnumValue

Eclipse points out this mistake though..

MySQL trigger if condition exists

Try to do...

 DELIMITER $$
        CREATE TRIGGER aumentarsalario 
        BEFORE INSERT 
        ON empregados
        FOR EACH ROW
        BEGIN
          if (NEW.SALARIO < 900) THEN 
             set NEW.SALARIO = NEW.SALARIO + (NEW.SALARIO * 0.1);
          END IF;
        END $$
  DELIMITER ;

Copy file from source directory to binary directory using CMake

The first of option you tried doesn't work for two reasons.

First, you forgot to close the parenthesis.

Second, the DESTINATION should be a directory, not a file name. Assuming that you closed the parenthesis, the file would end up in a folder called input.txt.

To make it work, just change it to

file(COPY ${CMAKE_CURRENT_SOURCE_DIR}/input.txt
     DESTINATION ${CMAKE_CURRENT_BINARY_DIR})

Matplotlib different size subplots

Probably the simplest way is using subplot2grid, described in Customizing Location of Subplot Using GridSpec.

ax = plt.subplot2grid((2, 2), (0, 0))

is equal to

import matplotlib.gridspec as gridspec
gs = gridspec.GridSpec(2, 2)
ax = plt.subplot(gs[0, 0])

so bmu's example becomes:

import numpy as np
import matplotlib.pyplot as plt

# generate some data
x = np.arange(0, 10, 0.2)
y = np.sin(x)

# plot it
fig = plt.figure(figsize=(8, 6))
ax0 = plt.subplot2grid((1, 3), (0, 0), colspan=2)
ax0.plot(x, y)
ax1 = plt.subplot2grid((1, 3), (0, 2))
ax1.plot(y, x)

plt.tight_layout()
plt.savefig('grid_figure.pdf')

what is Array.any? for javascript

The JavaScript native .some() method does exactly what you're looking for:

function isBiggerThan10(element, index, array) {
  return element > 10;
}

[2, 5, 8, 1, 4].some(isBiggerThan10);  // false
[12, 5, 8, 1, 4].some(isBiggerThan10); // true

Alternative for frames in html5 using iframes

While I agree with everyone else, if you are dead set on using frames anyway, you can just do index.html in XHTML and then do the contents of the frames in HTML5.

VBA Check if variable is empty

How you test depends on the Property's DataType:

| Type                                 | Test                            | Test2
| Numeric (Long, Integer, Double etc.) | If obj.Property = 0 Then        | 
| Boolen (True/False)                  | If Not obj.Property Then        | If obj.Property = False Then
| Object                               | If obj.Property Is Nothing Then |
| String                               | If obj.Property = "" Then       | If LenB(obj.Property) = 0 Then
| Variant                              | If obj.Property = Empty Then    |

You can tell the DataType by pressing F2 to launch the Object Browser and looking up the Object. Another way would be to just use the TypeName function:MsgBox TypeName(obj.Property)

Using NotNull Annotation in method argument

To test your method validation in a test, you have to wrap it a proxy in the @Before method.

@Before
public void setUp() {
    this.classAutowiredWithFindStuffMethod = MethodValidationProxyFactory.createProxy(this.classAutowiredWithFindStuffMethod);
}

With MethodValidationProxyFactory as :

import org.springframework.context.support.StaticApplicationContext;
import org.springframework.validation.beanvalidation.MethodValidationPostProcessor;

public class MethodValidationProxyFactory {

private static final StaticApplicationContext ctx = new StaticApplicationContext();

static {
    MethodValidationPostProcessor processor = new MethodValidationPostProcessor();
    processor.afterPropertiesSet(); // init advisor
    ctx.getBeanFactory()
            .addBeanPostProcessor(processor);
}

@SuppressWarnings("unchecked")
public static <T> T createProxy(T instance) {

    return (T) ctx.getAutowireCapableBeanFactory()
            .applyBeanPostProcessorsAfterInitialization(instance, instance.getClass()
                    .getName());
}

}

And then, add your test :

@Test
public void findingNullStuff() {
 assertThatExceptionOfType(ConstraintViolationException.class).isThrownBy(() -> this.classAutowiredWithFindStuffMethod.findStuff(null));

}

JavaScript - XMLHttpRequest, Access-Control-Allow-Origin errors

I think you've missed the point of access control.

A quick recap on why CORS exists: Since JS code from a website can execute XHR, that site could potentially send requests to other sites, masquerading as you and exploiting the trust those sites have in you(e.g. if you have logged in, a malicious site could attempt to extract information or execute actions you never wanted) - this is called a CSRF attack. To prevent that, web browsers have very stringent limitations on what XHR you can send - you are generally limited to just your domain, and so on.

Now, sometimes it's useful for a site to allow other sites to contact it - sites that provide APIs or services, like the one you're trying to access, would be prime candidates. CORS was developed to allow site A(e.g. paste.ee) to say "I trust site B, so you can send XHR from it to me". This is specified by site A sending "Access-Control-Allow-Origin" headers in its responses.

In your specific case, it seems that paste.ee doesn't bother to use CORS. Your best bet is to contact the site owner and find out why, if you want to use paste.ee with a browser script. Alternatively, you could try using an extension(those should have higher XHR privileges).

Storing images in SQL Server?

In my experience, storing to the url to the images stored in another location is the best way for a simple project.

How do I get a human-readable file size in bytes abbreviation using .NET?

I assume you're looking for "1.4 MB" instead of "1468006 bytes"?

I don't think there is a built-in way to do that in .NET. You'll need to just figure out which unit is appropriate, and format it.

Edit: Here's some sample code to do just that:

http://www.codeproject.com/KB/cpp/formatsize.aspx

HTML button to NOT submit form

For accessibility reason, I could not pull it off with multiple type=submit buttons. The only way to work natively with a form with multiple buttons but ONLY one can submit the form when hitting the Enter key is to ensure that only one of them is of type=submit while others are in other type such as type=button. By this way, you can benefit from the better user experience in dealing with a form on a browser in terms of keyboard support.

Best way in asp.net to force https for an entire site?

-> Simply ADD [RequireHttps] on top of the public class HomeController : Controller.

-> And add GlobalFilters.Filters.Add(new RequireHttpsAttribute()); in 'protected void Application_Start()' method in Global.asax.cs file.

Which forces your entire application to HTTPS.

Virtual network interface in Mac OS X

ifconfig interfacename create will create a virtual interface,

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

class MyMessageBox;

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

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


On a side note, this function:

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

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

Rather, use a reference (possibly const):

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

How to read a text file from server using JavaScript?

It looks like XMLHttpRequest has been replaced by the Fetch API. Google published a good introduction that includes this example doing what you want:

fetch('./api/some.json')
  .then(
    function(response) {
      if (response.status !== 200) {
        console.log('Looks like there was a problem. Status Code: ' +
          response.status);
        return;
      }

      // Examine the text in the response
      response.json().then(function(data) {
        console.log(data);
      });
    }
  )
  .catch(function(err) {
    console.log('Fetch Error :-S', err);
  });

However, you probably want to call response.text() instead of response.json().

Declaring array of objects

Using forEach we can store data in case we have already data we want to do some business login on data.

var sample = new Array();
var x = 10;
var sample = [1,2,3,4,5,6,7,8,9];
var data = [];

sample.forEach(function(item){
    data.push(item);
})

document.write(data);

Example by using simple for loop

var data = [];
for(var i = 0 ; i < 10 ; i++){
   data.push(i);
}
document.write(data);

Unit testing void methods?

Depends on what it's doing. If it has parameters, pass in mocks that you could ask later on if they have been called with the right set of parameters.

How do I set 'semi-bold' font via CSS? Font-weight of 600 doesn't make it look like the semi-bold I see in my Photoshop file

By mid-2016 the Chromium engine (v53) supports just 3 emphasis styles:

Plain text, bold, and super-bold...

 <div style="font:normal 400 14px Arial;">Testing</div>

 <div style="font:normal 700 14px Arial;">Testing</div>

 <div style="font:normal 800 14px Arial;">Testing</div>

Struct Constructor in C++?

Yes. A structure is just like a class, but defaults to public:, in the class definition and when inheriting:

struct Foo
{
    int bar;

    Foo(void) :
    bar(0)
    {
    }
}

Considering your other question, I would suggest you read through some tutorials. They will answer your questions faster and more complete than we will.

Image vs Bitmap class

Image provides an abstract access to an arbitrary image , it defines a set of methods that can loggically be applied upon any implementation of Image. Its not bounded to any particular image format or implementation . Bitmap is a specific implementation to the image abstract class which encapsulate windows GDI bitmap object. Bitmap is just a specific implementation to the Image abstract class which relay on the GDI bitmap Object.

You could for example , Create your own implementation to the Image abstract , by inheriting from the Image class and implementing the abstract methods.

Anyway , this is just a simple basic use of OOP , it shouldn't be hard to catch.

What are some reasons for jquery .focus() not working?

Don't forget that an input field must be visible first, thereafter you're able to focus it.

$("#elementid").show();
$("#elementid input[type=text]").focus();

How to drop a table if it exists?

Is it correct to do the following?

IF EXISTS(SELECT *
          FROM   dbo.Scores)
  DROP TABLE dbo.Scores

No. That will drop the table only if it contains any rows (and will raise an error if the table does not exist).

Instead, for a permanent table you can use

IF OBJECT_ID('dbo.Scores', 'U') IS NOT NULL 
  DROP TABLE dbo.Scores; 

Or, for a temporary table you can use

IF OBJECT_ID('tempdb.dbo.#TempTableName', 'U') IS NOT NULL
  DROP TABLE #TempTableName; 

SQL Server 2016+ has a better way, using DROP TABLE IF EXISTS …. See the answer by @Jovan.

How to get a product's image in Magento?

<img src='.$this->helper('catalog/image')->init($product, 'small_image')->resize(225, 225).' width=\'225\' height=\'225\'/>

How to cherry-pick multiple commits

To cherry pick from a commit id up to the tip of the branch, you can use:

git cherry-pick commit_id^..branch_name

LINQ: Distinct values

// First Get DataTable as dt
// DataRowComparer Compare columns numbers in each row & data in each row

IEnumerable<DataRow> Distinct = dt.AsEnumerable().Distinct(DataRowComparer.Default);

foreach (DataRow row in Distinct)
{
    Console.WriteLine("{0,-15} {1,-15}",
        row.Field<int>(0),
        row.Field<string>(1)); 
}

How can I fix WebStorm warning "Unresolved function or method" for "require" (Firefox Add-on SDK)

For WebStorm 2019.3 File > Preferences or Settings > Languages & Frameworks > Node.js and NPM -> Enable Coding assitance for NodeJs

Note that the additional packages that you want to use are included.

jQuery or JavaScript auto click

You haven't provided your javascript code, but the usual cause of this type of issue is not waiting till the page is loaded. Remember that most javascript is executed before the DOM is loaded, so code trying to manipulate it won't work.

To run code after the page has finished loading, use the $(document).ready callback:

$(document).ready(function(){
  $('#some-id').trigger('click');
});

Android Image View Pinch Zooming

I made my own custom imageview with pinch to zoom. There is no limits/borders on Chirag Ravals code, so user can drag the image off the screen. This will fix it.

Here is the CustomImageView class:

    public class CustomImageVIew extends ImageView implements OnTouchListener {


    private Matrix matrix = new Matrix();
    private Matrix savedMatrix = new Matrix();

    static final int NONE = 0;
    static final int DRAG = 1;
    static final int ZOOM = 2;

    private int mode = NONE;

    private PointF mStartPoint = new PointF();
    private PointF mMiddlePoint = new PointF();
    private Point mBitmapMiddlePoint = new Point();

    private float oldDist = 1f;
    private float matrixValues[] = {0f, 0f, 0f, 0f, 0f, 0f, 0f, 0f, 0f};
    private float scale;
    private float oldEventX = 0;
    private float oldEventY = 0;
    private float oldStartPointX = 0;
    private float oldStartPointY = 0;
    private int mViewWidth = -1;
    private int mViewHeight = -1;
    private int mBitmapWidth = -1;
    private int mBitmapHeight = -1;
    private boolean mDraggable = false;


    public CustomImageVIew(Context context) {
        this(context, null, 0);
    }

    public CustomImageVIew(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public CustomImageVIew(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        this.setOnTouchListener(this);
    }

    @Override
    public void onSizeChanged (int w, int h, int oldw, int oldh){
        super.onSizeChanged(w, h, oldw, oldh);
        mViewWidth = w;
        mViewHeight = h;
    }

    public void setBitmap(Bitmap bitmap){
        if(bitmap != null){
            setImageBitmap(bitmap);

            mBitmapWidth = bitmap.getWidth();
            mBitmapHeight = bitmap.getHeight();
            mBitmapMiddlePoint.x = (mViewWidth / 2) - (mBitmapWidth /  2);
            mBitmapMiddlePoint.y = (mViewHeight / 2) - (mBitmapHeight / 2);

            matrix.postTranslate(mBitmapMiddlePoint.x, mBitmapMiddlePoint.y);
            this.setImageMatrix(matrix);
        }
    }

    @Override
    public boolean onTouch(View v, MotionEvent event){
        switch (event.getAction() & MotionEvent.ACTION_MASK) {
        case MotionEvent.ACTION_DOWN:
            savedMatrix.set(matrix);
            mStartPoint.set(event.getX(), event.getY());
            mode = DRAG;
            break;
        case MotionEvent.ACTION_POINTER_DOWN:
            oldDist = spacing(event);
            if(oldDist > 10f){
                savedMatrix.set(matrix);
                midPoint(mMiddlePoint, event);
                mode = ZOOM;
            }
            break;
        case MotionEvent.ACTION_UP:
        case MotionEvent.ACTION_POINTER_UP:
            mode = NONE;
            break;
        case MotionEvent.ACTION_MOVE:
            if(mode == DRAG){
                drag(event);
            } else if(mode == ZOOM){
                zoom(event);
            } 
            break;
        }

        return true;
    }



   public void drag(MotionEvent event){
       matrix.getValues(matrixValues);

       float left = matrixValues[2];
       float top = matrixValues[5];
       float bottom = (top + (matrixValues[0] * mBitmapHeight)) - mViewHeight;
       float right = (left + (matrixValues[0] * mBitmapWidth)) -mViewWidth;

       float eventX = event.getX();
       float eventY = event.getY();
       float spacingX = eventX - mStartPoint.x;
       float spacingY = eventY - mStartPoint.y;
       float newPositionLeft = (left  < 0 ? spacingX : spacingX * -1) + left;
       float newPositionRight = (spacingX) + right;
       float newPositionTop = (top  < 0 ? spacingY : spacingY * -1) + top;
       float newPositionBottom = (spacingY) + bottom;
       boolean x = true;
       boolean y = true;

       if(newPositionRight < 0.0f || newPositionLeft > 0.0f){
           if(newPositionRight < 0.0f && newPositionLeft > 0.0f){
               x = false;
           } else{
               eventX = oldEventX;
               mStartPoint.x = oldStartPointX;
           }
       }
       if(newPositionBottom < 0.0f || newPositionTop > 0.0f){
           if(newPositionBottom < 0.0f && newPositionTop > 0.0f){
               y = false;
           } else{
               eventY = oldEventY;
               mStartPoint.y = oldStartPointY;
           }
       }

       if(mDraggable){
           matrix.set(savedMatrix);
           matrix.postTranslate(x? eventX - mStartPoint.x : 0, y? eventY - mStartPoint.y : 0);
           this.setImageMatrix(matrix);
           if(x)oldEventX = eventX;
           if(y)oldEventY = eventY;
           if(x)oldStartPointX = mStartPoint.x;
           if(y)oldStartPointY = mStartPoint.y;
       }

   }

   public void zoom(MotionEvent event){
       matrix.getValues(matrixValues);

       float newDist = spacing(event);
       float bitmapWidth = matrixValues[0] * mBitmapWidth;
       float bimtapHeight = matrixValues[0] * mBitmapHeight;
       boolean in = newDist > oldDist;

       if(!in && matrixValues[0] < 1){
           return;
       }
       if(bitmapWidth > mViewWidth || bimtapHeight > mViewHeight){
           mDraggable = true;
       } else{
           mDraggable = false;
       }

       float midX = (mViewWidth / 2);
       float midY = (mViewHeight / 2);

       matrix.set(savedMatrix);
       scale = newDist / oldDist;
       matrix.postScale(scale, scale, bitmapWidth > mViewWidth ? mMiddlePoint.x : midX, bimtapHeight > mViewHeight ? mMiddlePoint.y : midY); 

       this.setImageMatrix(matrix);


   }





    /** Determine the space between the first two fingers */
    private float spacing(MotionEvent event) {
        float x = event.getX(0) - event.getX(1);
        float y = event.getY(0) - event.getY(1);

        return (float)Math.sqrt(x * x + y * y);
    }

    /** Calculate the mid point of the first two fingers */
    private void midPoint(PointF point, MotionEvent event) {
        float x = event.getX(0) + event.getX(1);
        float y = event.getY(0) + event.getY(1);
        point.set(x / 2, y / 2);
    }


}

This is how you can use it in your activity:

CustomImageVIew mImageView = (CustomImageVIew)findViewById(R.id.customImageVIew1);
mImage.setBitmap(your bitmap);

And layout:

<your.package.name.CustomImageVIew
        android:id="@+id/customImageVIew1"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_marginBottom="15dp"
        android:layout_marginLeft="15dp"
        android:layout_marginRight="15dp"
        android:layout_marginTop="15dp"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true" 
        android:scaleType="matrix"/> // important

Print "hello world" every X seconds

This is the simple way to use thread in java:

for(int i = 0; i< 10; i++) {
    try {
        //sending the actual Thread of execution to sleep X milliseconds
        Thread.sleep(3000);
    } catch(Exception e) {
        System.out.println("Exception : "+e.getMessage());
    }
    System.out.println("Hello world!");
}

Postgresql query between date ranges

Just in case somebody land here... since 8.1 you can simply use:

SELECT user_id 
FROM user_logs 
WHERE login_date BETWEEN SYMMETRIC '2014-02-01' AND '2014-02-28'

From the docs:

BETWEEN SYMMETRIC is the same as BETWEEN except there is no requirement that the argument to the left of AND be less than or equal to the argument on the right. If it is not, those two arguments are automatically swapped, so that a nonempty range is always implied.

How to remove a branch locally?

Force Delete a Local Branch:

$ git branch -D <branch-name>

[NOTE]:

-D is a shortcut for --delete --force.


C# : assign data to properties via constructor vs. instantiating

Both approaches call a constructor, they just call different ones. This code:

var albumData = new Album 
                {
                     Name = "Albumius",
                     Artist = "Artistus",
                     Year = 2013
                };

is syntactic shorthand for this equivalent code:

var albumData = new Album();
albumData.Name = "Albumius";
albumData.Artist = "Artistus";
albumData.Year = 2013;

The two are almost identical after compilation (close enough for nearly all intents and purposes). So if the parameterless constructor wasn't public:

public Album() { }

then you wouldn't be able to use the object initializer at all anyway. So the main question isn't which to use when initializing the object, but which constructor(s) the object exposes in the first place. If the object exposes two constructors (like the one in your example), then one can assume that both ways are equally valid for constructing an object.

Sometimes objects don't expose parameterless constructors because they require certain values for construction. Though in cases like that you can still use the initializer syntax for other values. For example, suppose you have these constructors on your object:

private Album() { }
public Album(string name)
{
    this.Name = name;
}

Since the parameterless constructor is private, you can't use that. But you can use the other one and still make use of the initializer syntax:

var albumData = new Album("Albumius")
                {
                     Artist = "Artistus",
                     Year = 2013
                };

The post-compilation result would then be identical to:

var albumData = new Album("Albumius");
albumData.Artist = "Artistus";
albumData.Year = 2013;

System.Security.SecurityException when writing to Event Log

Had a similar issue with all of our 2008 servers. The security log stopped working altogether because of a GPO that took the group Authenticated Users and read permission away from the key HKLM\System\CurrentControlSet\Services\EventLog\security

Putting this back per Microsoft's recommendation corrected the issue. I suspect giving all authenticated users read at a higher level will also correct your problem.

Why is this rsync connection unexpectedly closed on Windows?

The trick for me was I had ssh conflict.

I have Git installed on my Windows path, which includes ssh. cwrsync also installs ssh.

The trick is to have make a batch file to set the correct paths:

rsync.bat

@echo off
SETLOCAL
SET CWRSYNCHOME=c:\commands\cwrsync
SET HOME=c:\Users\Petah\
SET CWOLDPATH=%PATH%
SET PATH=%CWRSYNCHOME%\bin;%PATH%
%~dp0\cwrsync\bin\rsync.exe %*

On Windows you can type where ssh to check if this is an issue. You will get something like this:

where ssh
C:\Program Files (x86)\Git\bin\ssh.exe
C:\Program Files\cwRsync\ssh.exe

How to enable curl in Wamp server

The steps are as follows :

  1. Close WAMP (if running)
  2. Navigate to WAMP\bin\php\(your version of php)\
  3. Edit php.ini
  4. Search for curl, uncomment extension=php_curl.dll
  5. Navigate to WAMP\bin\Apache\(your version of apache)\bin\
  6. Edit php.ini
  7. Search for curl, uncomment extension=php_curl.dll
  8. Save both
  9. Restart WAMP

The service cannot accept control messages at this time

I kept having this problem whenever I tried to start an app pool more than once. Rather than rebooting, I simply run the Application Information Service. (Note: This service is set to run manually on my system, which may be the reason for the problem.) From its description, it seems obvious that it is somehow involved:

Facilitates the running of interactive applications with additional administrative privileges. If this service is stopped, users will be unable to launch applications with the additional administrative privileges they may require to perform desired user tasks.

Presumably, IIS manager (as well as most other processes running as an administrator) does not maintain admin privileges throughout the life of the process, but instead request admin rights from the Application Information service on a case-by-case basis.

Source: social.technech.microsoft.com

Pseudo-terminal will not be allocated because stdin is not a terminal

I was having the same error under Windows using emacs 24.5.1 to connect to some company servers through /ssh:user@host. What solved my problem was setting the "tramp-default-method" variable to "plink" and whenever I connect to a server I ommit the ssh protocol. You need to have PuTTY's plink.exe installed for this to work.

Solution

  1. M-x customize-variable (and then hit Enter)
  2. tramp-default-method (and then hit Enter again)
  3. On the text field put plink and then Apply and Save the buffer
  4. Whenever I try to access a remote server I now use C-x-f /user@host: and then input the password. The connection is now correctly made under Emacs on Windows to my remote server.