Programs & Examples On #Eventlog source

Component is part of the declaration of 2 modules

IN Angular 4. This error is considered as ng serve run time cache issue.

case:1 this error will occur, once you import the component in one module and again import in sub modules will occur.

case:2 Import one Component in wrong place and removed and replaced in Correct module, That time it consider as ng serve cache issue. Need to Stop the project and start -do again ng serve, It will work as expected.

rejected master -> master (non-fast-forward)

git push -f origin master

use brute force ;-) Most likely you are trying to add a local folder that you created before creating the repo on git.

How exactly does binary code get converted into letters?

Here's a way to convert binary numbers to ASCII characters that is often simple enough to do in your head.

1 - Convert every 4 binary digits into one hex digit.

Here's a binary to hex conversion chart:

0001 = 1 
0010 = 2 
0011 = 3 
0100 = 4 
0101 = 5
0110 = 6
0111 = 7
1000 = 8

1001 = 9
1010 = a (the hex number a, not the letter a)
1011 = b
1100 = c
1101 = d
1110 = e
1111 = f

(The hexadecimal numbers a through f are the decimal numbers 10 through 15. That's what hexadecimal, or "base 16" is - instead of each digit being capable of representing 10 different numbers [0 - 9], like decimal or "base 10" does, each digit is instead capable of representing 16 different numbers [0 - f].)

Once you know that chart, converting any string of binary digits into a string of hex digits is simple.

For example,

01000100 = 0100 0100 = 44 hex
1010001001110011 = 1010 0010 0111 0011 = a273 hex

Simple enough, right? It is a simple matter to convert a binary number of any length into its hexadecimal equivalent.

(This works because hexadecimal is base 16 and binary is base 2 and 16 is the 4th power of 2, so it takes 4 binary digits to make 1 hex digit. 10, on the other hand, is not a power of 2, so we can't convert binary to decimal nearly as easily.)

2 - Split the string of hex digits into pairs.

When converting a number into ASCII, every 2 hex digits is a character. So break the hex string into sets of 2 digits.

You would split a hex number like 7340298b392 this into 6 pairs, like this:

7340298b392 = 07 34 02 98 b3 92

(Notice I prepended a 0, since I had an odd number of hex digits.)

That's 6 pairs of hex digits, so its going to be 6 letters. (Except I know right away that 98, b3 and 92 aren't letters. I'll explain why in a minute.)

3 - Convert each pair of hex digits into a decimal number.

Do this by multiplying the (decimal equivalent of the) left digit by 16, and adding the 2nd.

For example, b3 hex = 11*16 + 3, which is 110 + 66 + 3, which is 179. (b hex is 11 decimal.)

4 - Convert the decimal numbers into ASCII characters.

Now, to get the ASCII letters for the decimal numbers, simply keep in mind that in ASCII, 65 is an uppercase 'A', and 97 is a lowercase 'a'.

So what letter is 68?

68 is the 4th letter of the alphabet in uppercase, right?
65 = A, 66 = B, 67 = C, 68 = D.

So 68 is 'D'.

You take the decimal number, subtract 64 for uppercase letters if the number is less than 97, or 96 for lowercase letters if the number is 97 or larger, and that's the number of the letter of the alphabet associated with that set of 2 hex digits.


Alternatively, if you're not afraid of a little bit of easy hex arithmetic, you can skip step 3, and just go straight from hex to ASCII, by remembering, for example, that

hex 41 = 'A' 
hex 61 = 'a'

So subtract 40 hex for uppercase letters or 60 hex for lowercase letters, and convert what's left to decimal to get the alphabet letter number.

For example

01101100 = 6c, 6c - 60 = c = 12 decimal = 'l'
01010010 = 52, 52 - 40 = 12 hex = 18 decimal = 'R'

(When doing this, it's helpful to remember that 'm' (or 'M') is the 13 letter of the alphabet. So you can count up or down from 13 to find a letter that's nearer to the middle than to either end.)

I saw this on a shirt once, and was able to read it in my head:

01000100
01000001
01000100

I did it like this:

01000100 = 0100 0100 = 44 hex, - 40 hex = ucase letter 4 = D
01000001 = 0100 0001 = 41 hex, - 40 hex = ucase letter 1 = A
01000100 = 0100 0100 = 44 hex, - 40 hex = ucase letter 4 = D

The shirt said "DAD", which I thought was kinda cool, since it was being purchased by a pregnant woman. Her husband must be a geek like me.


How did I know right away that 92, b3, and 98 were not letters?

Because the ASCII code for a lowercase 'z' is 96 + 26 = 122, which in hex is 7a. 7a is the largest hex number for a letter. Anything larger than 7a is not a letter.


So that's how you can do it as a human.

How do computer programs do it?

For each set of 8 binary digits, convert it to a number, and look it up in an ASCII table.

(That's one pretty obvious and straight forward way. A typical programmer could probably think of 10 or 15 other ways in the space of a few minutes. The details depend on the computer language environment.)

How to compare arrays in JavaScript?

With an option to compare the order or not:

function arraysEqual(a1, a2, compareOrder) {
    if (a1.length !== a2.length) {
        return false;
    }

    return a1.every(function(value, index) {
        if (compareOrder) {
            return value === a2[index];
        } else {
            return a2.indexOf(value) > -1;
        }
    });
}

How to clear the logs properly for a Docker container?

On my Ubuntu servers even as sudo I would get Cannot open ‘/var/lib/docker/containers/*/*-json.log’ for writing: No such file or directory

But combing the docker inspect and truncate answers worked :

sudo truncate -s 0 `docker inspect --format='{{.LogPath}}' <container>`

Skip first entry in for loop in python?

Here's my preferred choice. It doesn't require adding on much to the loop, and uses nothing but built in tools.

Go from:

for item in my_items:
  do_something(item)

to:

for i, item in enumerate(my_items):
  if i == 0:
    continue
  do_something(item)

How to delete columns in numpy.array

Example from the numpy documentation:

>>> a = numpy.array([[ 0,  1,  2,  3],
               [ 4,  5,  6,  7],
               [ 8,  9, 10, 11],
               [12, 13, 14, 15]])

>>> numpy.delete(a, numpy.s_[1:3], axis=0)                       # remove rows 1 and 2

array([[ 0,  1,  2,  3],
       [12, 13, 14, 15]])

>>> numpy.delete(a, numpy.s_[1:3], axis=1)                       # remove columns 1 and 2

array([[ 0,  3],
       [ 4,  7],
       [ 8, 11],
       [12, 15]])

Make flex items take content width, not width of parent container

In addtion to align-self you can also consider auto margin which will do almost the same thing

_x000D_
_x000D_
.container {_x000D_
  background: red;_x000D_
  height: 200px;_x000D_
  flex-direction: column;_x000D_
  padding: 10px;_x000D_
  display: flex;_x000D_
}_x000D_
a {_x000D_
  margin-right:auto;_x000D_
  padding: 10px 40px;_x000D_
  background: pink;_x000D_
}
_x000D_
<div class="container">_x000D_
  <a href="#">Test</a>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How do you make an array of structs in C?

move

struct body bodies[n];

to after

struct body
{
    double p[3];//position
    double v[3];//velocity
    double a[3];//acceleration
    double radius;
    double mass;
};

Rest all looks fine.

Facebook share link without JavaScript

It is possible to include JavaScript in your code and still support non-JavaScript users.

If a user clicks any of the following links without JavaScript enabled, it will simply open a new tab:

<!-- Remember to change URL_HERE, TITLE_HERE and TWITTER_HANDLE_HERE -->
<a href="http://www.facebook.com/sharer/sharer.php?u=URL_HERE&t=TITLE_HERE" target="_blank" class="share-popup">Share on Facebook</a>
<a href="http://www.twitter.com/intent/tweet?url=URL_HERE&via=TWITTER_HANDLE_HERE&text=TITLE_HERE" target="_blank" class="share-popup">Share on Twitter</a>
<a href="http://plus.google.com/share?url=URL_HERE" target="_blank" class="share-popup">Share on Googleplus</a>

Because they contain the share-popup class, we can easily reference these in jQuery, and change the window size to suit the domain we are sharing from:

$(".share-popup").click(function(){
    var window_size = "width=585,height=511";
    var url = this.href;
    var domain = url.split("/")[2];
    switch(domain) {
        case "www.facebook.com":
            window_size = "width=585,height=368";
            break;
        case "www.twitter.com":
            window_size = "width=585,height=261";
            break;
        case "plus.google.com":
            window_size = "width=517,height=511";
            break;
    }
    window.open(url, '', 'menubar=no,toolbar=no,resizable=yes,scrollbars=yes,' + window_size);
    return false;
});

No more ugly inline JavaScript, or countless window sizing alterations. And it still supports non-JavaScript users.

CentOS: Copy directory to another directory

To copy all files, including hidden files use:

cp -r /home/server/folder/test/. /home/server/

How to create an object property from a variable value in JavaScript?

You could just use this:

function createObject(propName, propValue){
    this[propName] = propValue;
}
var myObj1 = new createObject('string1','string2');

Anything you pass as the first parameter will be the property name, and the second parameter is the property value.

CakePHP find method with JOIN

        $services = $this->Service->find('all', array(
            'limit' =>4,
            'fields' => array('Service.*','ServiceImage.*'),
            'joins' => array(
                array(
                        'table' => 'services_images',
                        'alias' => 'ServiceImage',
                        'type' => 'INNER',
                        'conditions' => array(
                        'ServiceImage.service_id' =>'Service.id'
                        )
                    ),
                ),
            )
        );

It goges to array is null.

How to quietly remove a directory with content in PowerShell

in short, We can use rm -r -fo {folderName} to remove the folder recursively (remove all the files and folders inside) and force

Create Directory When Writing To File In Node.js

If you don't want to use any additional package, you can call the following function before creating your file:

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

function ensureDirectoryExistence(filePath) {
  var dirname = path.dirname(filePath);
  if (fs.existsSync(dirname)) {
    return true;
  }
  ensureDirectoryExistence(dirname);
  fs.mkdirSync(dirname);
}

AngularJS custom filter function

You can use it like this: http://plnkr.co/edit/vtNjEgmpItqxX5fdwtPi?p=preview

Like you found, filter accepts predicate function which accepts item by item from the array. So, you just have to create an predicate function based on the given criteria.

In this example, criteriaMatch is a function which returns a predicate function which matches the given criteria.

template:

<div ng-repeat="item in items | filter:criteriaMatch(criteria)">
  {{ item }}
</div>

scope:

$scope.criteriaMatch = function( criteria ) {
  return function( item ) {
    return item.name === criteria.name;
  };
};

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

Make sure you clean your project in android studio (or eclipse),

It should solve your issues

ReactJS: setTimeout() not working?

Do

setTimeout(
    function() {
        this.setState({ position: 1 });
    }
    .bind(this),
    3000
);

Otherwise, you are passing the result of setState to setTimeout.

You can also use ES6 arrow functions to avoid the use of this keyword:

setTimeout(
  () => this.setState({ position: 1 }), 
  3000
);

XSS prevention in JSP/Servlet web application

My personal opinion is that you should avoid using JSP/ASP/PHP/etc pages. Instead output to an API similar to SAX (only designed for calling rather than handling). That way there is a single layer that has to create well formed output.

Oracle SQL - DATE greater than statement

you have to use the To_Date() function to convert the string to date ! http://www.techonthenet.com/oracle/functions/to_date.php

How to preview a part of a large pandas DataFrame, in iPython notebook?

In this case, where the DataFrame is long but not too wide, you can simply slice it:

>>> df = pd.DataFrame({"A": range(1000), "B": range(1000)})
>>> df
<class 'pandas.core.frame.DataFrame'>
Int64Index: 1000 entries, 0 to 999
Data columns:
A    1000  non-null values
B    1000  non-null values
dtypes: int64(2)
>>> df[:5]
   A  B
0  0  0
1  1  1
2  2  2
3  3  3
4  4  4

ix is deprecated.

If it's both wide and long, I tend to use .ix:

>>> df = pd.DataFrame({i: range(1000) for i in range(100)})
>>> df.ix[:5, :10]
   0   1   2   3   4   5   6   7   8   9   10
0   0   0   0   0   0   0   0   0   0   0   0
1   1   1   1   1   1   1   1   1   1   1   1
2   2   2   2   2   2   2   2   2   2   2   2
3   3   3   3   3   3   3   3   3   3   3   3
4   4   4   4   4   4   4   4   4   4   4   4
5   5   5   5   5   5   5   5   5   5   5   5

jquery/javascript convert date string to date

I used the javascript date funtion toLocaleDateString to get

var Today = new Date();
var r = Today.toLocaleDateString();

The result of r will be

11/29/2016

More info at: http://www.w3schools.com/jsref/jsref_tolocaledatestring.asp

Can an XSLT insert the current date?

Do you have control over running the transformation? If so, you could pass in the current date to the XSL and use $current-date from inside your XSL. Below is how you declare the incoming parameter, but with knowing how you are running the transformation, I can't tell you how to pass in the value.

<xsl:param name="current-date" />

For example, from the bash script, use:

xsltproc --stringparam current-date `date +%Y-%m-%d` -o output.html path-to.xsl path-to.xml

Then, in the xsl you can use:

<xsl:value-of select="$current-date"/>

How to bring view in front of everything?

bringToFront() is the right way, but, NOTE that you must call bringToFront() and invalidate() method on highest-level view (under your root view), for e.g.:

Your view's hierarchy is:

-RelativeLayout
|--LinearLayout1
|------Button1
|------Button2
|------Button3
|--ImageView
|--LinearLayout2
|------Button4
|------Button5
|------Button6

So, when you animate back your buttons (1->6), your buttons will under (below) the ImageView. To bring it over (above) the ImageView you must call bringToFront() and invalidate() method on your LinearLayouts. Then it will work :) **NOTE: Remember to set android:clipChildren="false" for your root layout or animate-view's gradparent_layout. Let's take a look at my real code:

.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:hw="http://schemas.android.com/apk/res-auto"
    android:id="@+id/layout_parent"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/common_theme_color"
    android:orientation="vertical" >

    <com.binh.helloworld.customviews.HWActionBar
        android:id="@+id/action_bar"
        android:layout_width="match_parent"
        android:layout_height="@dimen/dimen_actionbar_height"
        android:layout_alignParentTop="true"
        hw:titleText="@string/app_name" >
    </com.binh.helloworld.customviews.HWActionBar>

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@id/action_bar"
        android:clipChildren="false" >

        <LinearLayout
            android:id="@+id/layout_top"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_alignParentTop="true"
            android:gravity="center_horizontal"
            android:orientation="horizontal" >
        </LinearLayout>

        <ImageView
            android:id="@+id/imgv_main"
            android:layout_width="@dimen/common_imgv_height"
            android:layout_height="@dimen/common_imgv_height"
            android:layout_centerInParent="true"
            android:contentDescription="@string/app_name"
            android:src="@drawable/ic_launcher" />

        <LinearLayout
            android:id="@+id/layout_bottom"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_alignParentBottom="true"
            android:gravity="center_horizontal"
            android:orientation="horizontal" >
        </LinearLayout>
    </RelativeLayout>

</RelativeLayout>

Some code in .java

private LinearLayout layoutTop, layoutBottom;
...
layoutTop = (LinearLayout) rootView.findViewById(R.id.layout_top);
layoutBottom = (LinearLayout) rootView.findViewById(R.id.layout_bottom);
...
//when animate back
//dragedView is my layoutTop's child view (i added programmatically) (like buttons in above example) 
dragedView.setVisibility(View.GONE);
layoutTop.bringToFront();
layoutTop.invalidate();
dragedView.startAnimation(animation); // TranslateAnimation
dragedView.setVisibility(View.VISIBLE);

GLuck!

How can I dynamically set the position of view in Android?

Yes, you can dynamically set the position of the view in Android. Likewise, you have an ImageView in LinearLayout of your XML file. So you can set its position through LayoutParams.But make sure to take LayoutParams according to the layout taken in your XML file. There are different LayoutParams according to the layout taken.

Here is the code to set:

    LayoutParams layoutParams=new LayoutParams(int width, int height);
    layoutParams.setMargins(int left, int top, int right, int bottom);
    imageView.setLayoutParams(layoutParams);

Table and Index size in SQL Server

The exec sp_spaceused without parameter shows the summary for the whole database. The foreachtable solution generates one result set per table - which SSMS might not be able to handle if you have too many tables.

I created a script which collects the table infos via sp_spaceused and displays a summary in a single record set, sorted by size.

create table #t
(
  name nvarchar(128),
  rows varchar(50),
  reserved varchar(50),
  data varchar(50),
  index_size varchar(50),
  unused varchar(50)
)

declare @id nvarchar(128)
declare c cursor for
select '[' + sc.name + '].[' + s.name + ']' FROM sysobjects s INNER JOIN sys.schemas sc ON s.uid = sc.schema_id where s.xtype='U'

open c
fetch c into @id

while @@fetch_status = 0 begin

  insert into #t
  exec sp_spaceused @id

  fetch c into @id
end

close c
deallocate c

select * from #t
order by convert(int, substring(data, 1, len(data)-3)) desc

drop table #t

UIView bottom border?

The most complete answer. https://github.com/oney/UIView-Border

let rectangle = UIView(frame: CGRect(x: 100, y: 100, width: 100, height: 60))
rectangle.backgroundColor = UIColor.grayColor()
view.addSubview(rectangle)
rectangle.borderTop = Border(size: 3, color: UIColor.orangeColor(), offset: UIEdgeInsets(top: 0, left: -10, bottom: 0, right: -5))
rectangle.borderBottom = Border(size: 6, color: UIColor.redColor(), offset: UIEdgeInsets(top: 0, left: 10, bottom: 10, right: 0))
rectangle.borderLeft = Border(size: 2, color: UIColor.blueColor(), offset: UIEdgeInsets(top: 10, left: -10, bottom: 0, right: 0))
rectangle.borderRight = Border(size: 2, color: UIColor.greenColor(), offset: UIEdgeInsets(top: 10, left: 10, bottom: 0, right: 0))

enter image description here

Custom domain for GitHub project pages

I'd like to share my steps which is a bit different to what offered by rynop and superluminary.

  • for A Record is exactly the same but
  • instead of creating CNAME for www I would prefer to redirect it to my blank domain (non-www)

This configuration is referring to guidance of preferred domain. The domain setting of www to non www or vise versa can be different on each of the domain providers. Since my domain is under GoDaddy, so under the Domain Setting I set it using the Subdomain Forwarding (301).

As the result of pointing the domain to Github repository, it will then give all the URLs for both of master and gh-pages branch similar like the ones I listed below goes to the preferred domain:

master

By creating CNAME file on master branch (check it on my user repository).

http://hyipworld.github.io/
http://www.hyip.world/
http://hyip.world/

gh-pages

By creating the same CNAME file on gh-pages branch (check it on my project repository).

http://hyipworld.github.io/maps/
http://www.hyip.world/maps/
http://hyip.world/maps/

As addition to the CNAME file above, you may need to completely bypass Jekyll processing on GitHub Pages by creating a file named .nojekyll in the root of your pages repo.

Spring Boot REST service exception handling

For REST controllers, I would recommend to use Zalando Problem Spring Web.

https://github.com/zalando/problem-spring-web

If Spring Boot aims to embed some auto-configuration, this library does more for exception handling. You just need to add the dependency:

<dependency>
    <groupId>org.zalando</groupId>
    <artifactId>problem-spring-web</artifactId>
    <version>LATEST</version>
</dependency>

And then define one or more advice traits for your exceptions (or use those provided by default)

public interface NotAcceptableAdviceTrait extends AdviceTrait {

    @ExceptionHandler
    default ResponseEntity<Problem> handleMediaTypeNotAcceptable(
            final HttpMediaTypeNotAcceptableException exception,
            final NativeWebRequest request) {
        return Responses.create(Status.NOT_ACCEPTABLE, exception, request);
    }

}

Then you can defined the controller advice for exception handling as:

@ControllerAdvice
class ExceptionHandling implements MethodNotAllowedAdviceTrait, NotAcceptableAdviceTrait {

}

Spring default behavior for lazy-init

The lazy-init="default" setting on a bean only refers to what is set by the default-lazy-init attribute of the enclosing beans element. The implicit default value of default-lazy-init is false.

If there is no lazy-init attribute specified on a bean, it's always eagerly instantiated.

How do you disable browser Autocomplete on web form field / input tag?

If you want to prevent the common browser plug-in LastPass from auto-filling a field as well, you can add the attribute data-lpignore="true" added to the other suggestions on this thread. Note that this doesn't only apply to password fields.

<input type="text" autocomplete="false" data-lpignore="true" />

I was trying to do this same thing a while back, and was stumped because none of the suggestions I found worked for me. Turned out it was LastPass.

alternative to "!is.null()" in R

Ian put this in the comment, but I think it's a good answer:

if (exists("aVariable"))
{
  do whatever
}

note that the variable name is quoted.

How to set border on jPanel?

Swing has no idea what the preferred, minimum and maximum sizes of the GoBoard should be as you have no components inside of it for it to calculate based on, so it picks a (probably wrong) default. Since you are doing custom drawing here, you should implement these methods

Dimension getPreferredSize()
Dimension getMinumumSize()
Dimension getMaximumSize()

or conversely, call the setters for these methods.

ASP.NET MVC 4 Custom Authorize Attribute with Permission Codes (without roles)

Here is a modification for the prev. answer. The main difference is when the user is not authenticated, it uses the original "HandleUnauthorizedRequest" method to redirect to login page:

   protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
    {

        if (filterContext.HttpContext.User.Identity.IsAuthenticated) {

            filterContext.Result = new RedirectToRouteResult(
                        new RouteValueDictionary(
                            new
                            {
                                controller = "Account",
                                action = "Unauthorised"
                            })
                        );
        }
        else
        {
             base.HandleUnauthorizedRequest(filterContext);
        }
    }

Printing integer variable and string on same line in SQL

Numbers have higher precedence than strings so of course the + operators want to convert your strings into numbers before adding.

You could do:

print 'There are ' + CONVERT(varchar(10),@Number) +
      ' alias combinations did not match a record'

or use the (rather limited) formatting facilities of RAISERROR:

RAISERROR('There are %i alias combinations did not match a record',10,1,@Number)
WITH NOWAIT

Which is the fastest algorithm to find prime numbers?

Rabin-Miller is a standard probabilistic primality test. (you run it K times and the input number is either definitely composite, or it is probably prime with probability of error 4-K. (a few hundred iterations and it's almost certainly telling you the truth)

There is a non-probabilistic (deterministic) variant of Rabin Miller.

The Great Internet Mersenne Prime Search (GIMPS) which has found the world's record for largest proven prime (274,207,281 - 1 as of June 2017), uses several algorithms, but these are primes in special forms. However the GIMPS page above does include some general deterministic primality tests. They appear to indicate that which algorithm is "fastest" depends upon the size of the number to be tested. If your number fits in 64 bits then you probably shouldn't use a method intended to work on primes of several million digits.

Converting dd/mm/yyyy formatted string to Datetime

You need to use DateTime.ParseExact with format "dd/MM/yyyy"

DateTime dt=DateTime.ParseExact("24/01/2013", "dd/MM/yyyy", CultureInfo.InvariantCulture);

Its safer if you use d/M/yyyy for the format, since that will handle both single digit and double digits day/month. But that really depends if you are expecting single/double digit values.


Your date format day/Month/Year might be an acceptable date format for some cultures. For example for Canadian Culture en-CA DateTime.Parse would work like:

DateTime dt = DateTime.Parse("24/01/2013", new CultureInfo("en-CA"));

Or

System.Threading.Thread.CurrentThread.CurrentCulture = new CultureInfo("en-CA");
DateTime dt = DateTime.Parse("24/01/2013"); //uses the current Thread's culture

Both the above lines would work because the the string's format is acceptable for en-CA culture. Since you are not supplying any culture to your DateTime.Parse call, your current culture is used for parsing which doesn't support the date format. Read more about it at DateTime.Parse.


Another method for parsing is using DateTime.TryParseExact

DateTime dt;
if (DateTime.TryParseExact("24/01/2013", 
                            "d/M/yyyy", 
                            CultureInfo.InvariantCulture, 
                            DateTimeStyles.None,
    out dt))
{
    //valid date
}
else
{
    //invalid date
}

The TryParse group of methods in .Net framework doesn't throw exception on invalid values, instead they return a bool value indicating success or failure in parsing.

Notice that I have used single d and M for day and month respectively. Single d and M works for both single/double digits day and month. So for the format d/M/yyyy valid values could be:

  • "24/01/2013"
  • "24/1/2013"
  • "4/12/2013" //4 December 2013
  • "04/12/2013"

For further reading you should see: Custom Date and Time Format Strings

php return 500 error but no error log

Be sure your file permissions are correct. If apache doesn't have permission to read the file then it can't write to the log.

.NET String.Format() to add commas in thousands place for a number

int number = 1000000000;
string whatYouWant = number.ToString("#,##0");
//You get: 1,000,000,000

Import Error: No module named numpy

For installing NumPy via Anaconda(use below commands):

  • conda install -c conda-forge numpy
  • conda install -c conda-forge/label/broken numpy

Histogram Matplotlib

I know this does not answer your question, but I always end up on this page, when I search for the matplotlib solution to histograms, because the simple histogram_demo was removed from the matplotlib example gallery page.

Here is a solution, which doesn't require numpy to be imported. I only import numpy to generate the data x to be plotted. It relies on the function hist instead of the function bar as in the answer by @unutbu.

import numpy as np
mu, sigma = 100, 15
x = mu + sigma * np.random.randn(10000)

import matplotlib.pyplot as plt
plt.hist(x, bins=50)
plt.savefig('hist.png')

enter image description here

Also check out the matplotlib gallery and the matplotlib examples.

Saving a Excel File into .txt format without quotes

I just spent the better part of an afternoon on this

There are two common ways of writing to a file, the first being a direct file access "write" statement. This adds the quotes.

The second is the "ActiveWorkbook.SaveAs" or "ActiveWorksheet.SaveAs" which both have the really bad side effect of changing the filename of the active workbook.

The solution here is a hybrid of a few solutions I found online. It basically does this: 1) Copy selected cells to a new worksheet 2) Iterate through each cell one at a time and "print" it to the open file 3) Delete the temporary worksheet.

The function works on the selected cells and takes in a string for a filename or prompts for a filename.

Function SaveFile(myFolder As String) As String
tempSheetName = "fileWrite_temp"
SaveFile = "False"

Dim FilePath As String
Dim CellData As String
Dim LastCol As Long
Dim LastRow As Long

Set myRange = Selection
'myRange.Select
Selection.Copy

'Ask user for folder to save text file to.
If myFolder = "prompt" Then
    myFolder = Application.GetSaveAsFilename(fileFilter:="XML Files (*.xml), *.xml, All Files (*), *")
End If
If myFolder = "False" Then
    End
End If

Open myFolder For Output As #2

'This temporarily adds a sheet named "Test."
Sheets.Add.Name = tempSheetName
Sheets(tempSheetName).Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
    :=False, Transpose:=False

LastCol = ActiveSheet.UsedRange.SpecialCells(xlCellTypeLastCell).Column
LastRow = ActiveSheet.UsedRange.SpecialCells(xlCellTypeLastCell).Row

For i = 1 To LastRow
    For j = 1 To LastCol
        CellData = CellData + Trim(ActiveCell(i, j).Value) + "   "
    Next j

    Print #2, CellData; " "
    CellData = ""

Next i

Close #2

'Remove temporary sheet.
Application.ScreenUpdating = False
Application.DisplayAlerts = False
ActiveWindow.SelectedSheets.Delete
Application.DisplayAlerts = True
Application.ScreenUpdating = True
'Indicate save action.
MsgBox "Text File Saved to: " & vbNewLine & myFolder
SaveFile = myFolder

End Function

C# Get/Set Syntax Usage

You are not able to access those properties as they are marked as protected meaning:

The type or member can be accessed only by code in the same class or struct, or in a class that is derived from that class.

Converting file into Base64String and back again

For Java, consider using Apache Commons FileUtils:

/**
 * Convert a file to base64 string representation
 */
public String fileToBase64(File file) throws IOException {
    final byte[] bytes = FileUtils.readFileToByteArray(file);
    return Base64.getEncoder().encodeToString(bytes);
}

/**
 * Convert base64 string representation to a file
 */
public void base64ToFile(String base64String, String filePath) throws IOException {
    byte[] bytes = Base64.getDecoder().decode(base64String);
    FileUtils.writeByteArrayToFile(new File(filePath), bytes);
}

Why use prefixes on member variables in C++ classes

Those conventions are just that. Most shops use code conventions to ease code readability so anyone can easily look at a piece of code and quickly decipher between things such as public and private members.

WCF Exception: Could not find a base address that matches scheme http for the endpoint

In my case this fixed the issue

  1. Go to Project Properties by clicking F4 on the project name
  2. Set SSLEnabled = true

Project Properties Image

What causes HttpHostConnectException?

You must set proxy server for gradle at some time, you can try to change the proxy server ip address in gradle.properties which is under .gradle document

NSAttributedString add text alignment

I was searching for the same issue and was able to center align the text in a NSAttributedString this way:

NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc]init] ;
[paragraphStyle setAlignment:NSTextAlignmentCenter];

NSMutableAttributedString *attribString = [[NSMutableAttributedString alloc]initWithString:string];
[attribString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, [string length])];

What is the advantage of using REST instead of non-REST HTTP?

Query-strings can be ignored by search engines.

Getting Image from URL (Java)

Try:

public class ImageComponent extends JComponent {
  private final BufferedImage img;

  public ImageComponent(URL url) throws IOException {
    img = ImageIO.read(url);
    setPreferredSize(new Dimension(img.getWidth(), img.getHeight()));

  }

  @Override
  protected void paintComponent(Graphics g) {
    super.paintComponent(g);
    g.drawImage(img, 0, 0, img.getWidth(), img.getHeight(), this);
  }

  public static void main(String[] args) throws Exception {
    final URL kitten = new URL("https://placekitten.com/g/200/300");

    final ImageComponent image = new ImageComponent(kitten);

    JFrame frame = new JFrame("Test");
    frame.add(new JScrollPane(image));

    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(400, 300);
    frame.setVisible(true);
  }
}

How to get the response of XMLHttpRequest?

In XMLHttpRequest, using XMLHttpRequest.responseText may raise the exception like below

 Failed to read the \'responseText\' property from \'XMLHttpRequest\': 
 The value is only accessible if the object\'s \'responseType\' is \'\' 
 or \'text\' (was \'arraybuffer\')

Best way to access the response from XHR as follows

function readBody(xhr) {
    var data;
    if (!xhr.responseType || xhr.responseType === "text") {
        data = xhr.responseText;
    } else if (xhr.responseType === "document") {
        data = xhr.responseXML;
    } else {
        data = xhr.response;
    }
    return data;
}

var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
    if (xhr.readyState == 4) {
        console.log(readBody(xhr));
    }
}
xhr.open('GET', 'http://www.google.com', true);
xhr.send(null);

m2e lifecycle-mapping not found

The org.eclipse.m2e:lifecycle-mapping plugin doesn't exist actually. It should be used from the <build><pluginManagement> section of your pom.xml. That way, it's not resolved by Maven but can be read by m2e.

But a more practical solution to your problem would be to install the m2e build-helper connector in eclipse. You can install it from the Window > Preferences > Maven > Discovery > Open Catalog. That way build-helper-maven-plugin:add-sources would be called in eclipse without having you to change your pom.xml.

Tensorflow import error: No module named 'tensorflow'

In Windows 64, if you did this sequence correctly:

Anaconda prompt:

conda create -n tensorflow python=3.5
activate tensorflow
pip install --ignore-installed --upgrade tensorflow

Be sure you still are in tensorflow environment. The best way to make Spyder recognize your tensorflow environment is to do this:

conda install spyder

This will install a new instance of Spyder inside Tensorflow environment. Then you must install scipy, matplotlib, pandas, sklearn and other libraries. Also works for OpenCV.

Always prefer to install these libraries with "conda install" instead of "pip".

Batch Renaming of Files in a Directory

I have this to simply rename all files in subfolders of folder

import os

def replace(fpath, old_str, new_str):
    for path, subdirs, files in os.walk(fpath):
        for name in files:
            if(old_str.lower() in name.lower()):
                os.rename(os.path.join(path,name), os.path.join(path,
                                            name.lower().replace(old_str,new_str)))

I am replacing all occurences of old_str with any case by new_str.

What do these operators mean (** , ^ , %, //)?

You can find all of those operators in the Python language reference, though you'll have to scroll around a bit to find them all. As other answers have said:

  • The ** operator does exponentiation. a ** b is a raised to the b power. The same ** symbol is also used in function argument and calling notations, with a different meaning (passing and receiving arbitrary keyword arguments).
  • The ^ operator does a binary xor. a ^ b will return a value with only the bits set in a or in b but not both. This one is simple!
  • The % operator is mostly to find the modulus of two integers. a % b returns the remainder after dividing a by b. Unlike the modulus operators in some other programming languages (such as C), in Python a modulus it will have the same sign as b, rather than the same sign as a. The same operator is also used for the "old" style of string formatting, so a % b can return a string if a is a format string and b is a value (or tuple of values) which can be inserted into a.
  • The // operator does Python's version of integer division. Python's integer division is not exactly the same as the integer division offered by some other languages (like C), since it rounds towards negative infinity, rather than towards zero. Together with the modulus operator, you can say that a == (a // b)*b + (a % b). In Python 2, floor division is the default behavior when you divide two integers (using the normal division operator /). Since this can be unexpected (especially when you're not picky about what types of numbers you get as arguments to a function), Python 3 has changed to make "true" (floating point) division the norm for division that would be rounded off otherwise, and it will do "floor" division only when explicitly requested. (You can also get the new behavior in Python 2 by putting from __future__ import division at the top of your files. I strongly recommend it!)

How to tell PowerShell to wait for each command to end before starting the next?

If you use Start-Process <path to exe> -NoNewWindow -Wait

You can also use the -PassThru option to echo output.

jQuery .load() call doesn't execute JavaScript in loaded HTML file

If you want to load both the HTML and scripts, here's a more automated way to do so utilizing both $(selector).load() and jQuery.getScript(). This specific example loads the HTML content of the element with ID "toLoad" from content.html, inserts the HTML into the element with ID "content", and then loads and runs all scripts within the element with the "toLoad" ID.

$("#content").load("content.html #toLoad", function(data) {
    var scripts = $(data).find("script");

    if (scripts.length) {
        $(scripts).each(function() {
            if ($(this).attr("src")) {
                $.getScript($(this).attr("src"));
            }
            else {
                eval($(this).html());
            }
        });
    }

});

This code finds all of the script elements in the content that is being loaded, and loops through each of these elements. If the element has a src attribute, meaning it is a script from an external file, we use the jQuery.getScript method of fetching and running the script. If the element does not have a src attribute, meaning it is an inline script, we simply use eval to run the code. If it finds no script elements, it solely inserts the HTML into the target element and does not attempt to load any scripts.

I've tested this method in Chrome and it works. Remember to be cautious when using eval, as it can run potentially unsafe scripts and is generally considered harmful. You might want to avoid using inline scripts when using this method in order to avoid having to use eval.

Java - How to access an ArrayList of another class?

Two ways

1)instantiate the first class and getter for arrayList

or

2)Make arraylist as static

And finally

Java Basics By Oracle

What is Android keystore file, and what is it used for?

The whole idea of a keytool is to sign your apk with a unique identifier indicating the source of that apk. A keystore file (from what I understand) is used for debuging so your apk has the functionality of a keytool without signing your apk for production. So yes, for debugging purposes you should be able to sign multiple apk's with a single keystore. But understand that, upon pushing to production you'll need unique keytools as identifiers for each apk you create.

Find OpenCV Version Installed on Ubuntu

The other methods here didn't work for me, so here's what does work in Ubuntu 12.04 'precise'.

On Ubuntu and other Debian-derived platforms, dpkg is the typical way to get software package versions. For more recent versions than the one that @Tio refers to, use

 dpkg -l | grep libopencv

If you have the development packages installed, like libopencv-core-dev, you'll probably have .pc files and can use pkg-config:

 pkg-config --modversion opencv

How to clear out session on log out

I would prefer Session.Abandon()

Session.Clear() will not cause End to fire and further requests from the client will not raise the Session Start event.

x86 Assembly on a Mac

Forget about finding a IDE to write/run/compile assembler on Mac. But, remember mac is UNIX. See http://asm.sourceforge.net/articles/linasm.html. A decent guide (though short) to running assembler via GCC on Linux. You can mimic this. Macs use Intel chips so you want to look at Intel syntax.

What should I do when 'svn cleanup' fails?

It might not apply in all situations, but when I recently encountered this problem my "fix" was to upgrade the Subversion package on my system. I had been running 1.4.something, and when I upgraded to the latest (1.6.6 in my case) the checkout worked.

(I did try re-downloading it, but a checkout to a clean directory always hung at the same spot.)

How do we update URL or query strings using javascript/jQuery without reloading the page?

You'll need to be more specific. What do you mean by 'update the URL'? It could mean automatically navigating to a different page, which is certainly possible.

If you want to just update the contents of the address bar without reloading the page, see Modify the URL without reloading the page

JVM property -Dfile.encoding=UTF8 or UTF-8?

Both UTF8 and UTF-8 work for me.

mongodb count num of distinct values per field/key

I wanted a more concise answer and I came up with the following using the documentation at aggregates and group

db.countries.aggregate([{"$group": {"_id": "$country", "count":{"$sum": 1}}])

Get lengths of a list in a jinja2 template

Alex' comment looks good but I was still confused with using range. The following worked for me while working on a for condition using length within range.

{% for i in range(0,(nums['list_users_response']['list_users_result']['users'])| length) %}
<li>    {{ nums['list_users_response']['list_users_result']['users'][i]['user_name'] }} </li>
{% endfor %}

PHP php_network_getaddresses: getaddrinfo failed: No such host is known

Your "localhost" cannot resolve the name www.google.com, which means your machine doesn't/can't reach a valid dns server.

Try ping google.com on the console of that machine to verify this.

Sort a Map<Key, Value> by values

This method will just serve the purpose. (the 'setback' is that the Values must implement the java.util.Comparable interface)

  /**

 * Sort a map according to values.

 * @param <K> the key of the map.
 * @param <V> the value to sort according to.
 * @param mapToSort the map to sort.

 * @return a map sorted on the values.

 */ 
public static <K, V extends Comparable< ? super V>> Map<K, V>
sortMapByValues(final Map <K, V> mapToSort)
{
    List<Map.Entry<K, V>> entries =
        new ArrayList<Map.Entry<K, V>>(mapToSort.size());  

    entries.addAll(mapToSort.entrySet());

    Collections.sort(entries,
                     new Comparator<Map.Entry<K, V>>()
    {
        @Override
        public int compare(
               final Map.Entry<K, V> entry1,
               final Map.Entry<K, V> entry2)
        {
            return entry1.getValue().compareTo(entry2.getValue());
        }
    });      

    Map<K, V> sortedMap = new LinkedHashMap<K, V>();      

    for (Map.Entry<K, V> entry : entries)
    {
        sortedMap.put(entry.getKey(), entry.getValue());

    }      

    return sortedMap;

}

http://javawithswaranga.blogspot.com/2011/06/generic-method-to-sort-hashmap.html

Is there any way to configure multiple registries in a single npmrc file

My approach was to make a slight command line variant that adds the registry switch.

I created these files in the nodejs folder where the npm executable is found:

npm-.cmd:

@ECHO OFF
npm --registry https://registry.npmjs.org %*

npm-:

#!/bin/sh
"npm" --registry https://registry.npmjs.org "$@"

Now, if I want to do an operation against the normal npm registry (while I am not connected to the VPN), I just type npm- where I would usually type npm.

To test this command and see the registry for a package, use this example:

npm- view lodash

PS. I am in windows and have tested this in Bash, CMD, and Powershell. I also

Change selected value of kendo ui dropdownlist

You have to use Kendo UI DropDownList select method (documentation in here).

Basically you should:

// get a reference to the dropdown list
var dropdownlist = $("#Instrument").data("kendoDropDownList");

If you know the index you can use:

// selects by index
dropdownlist.select(1);

If not, use:

// selects item if its text is equal to "test" using predicate function
dropdownlist.select(function(dataItem) {
    return dataItem.symbol === "test";
});

JSFiddle example here

XAMPP installation on Win 8.1 with UAC Warning

There's nothing to be worried upon for this. Like other servers, install xampp somewhere outside of the default Program Files folder of Windows. It shall work fine.

I previously had wamp server installed on my machine and i never understood why wamp server installs itself outside of the default directory. Xampp cleared this, now i have both the servers lying outside the Program Files folder and are running fine.

MySQL Query to select data from last week?

i Use this for the week start from SUNDAY:

SELECT id FROM tbl
WHERE
date >= curdate() - INTERVAL DAYOFWEEK(curdate())+5 DAY  
AND date < curdate() - INTERVAL DAYOFWEEK(curdate())-2 DAY

Difference between request.getSession() and request.getSession(true)

request.getSession() will return a current session. if current session does not exist, then it will create a new one.

request.getSession(true) will return current session. If current session does not exist, then it will create a new session.

So basically there is not difference between both method.

request.getSession(false) will return current session if current session exists. If not, it will not create a new session.

How can I get the current user directory?

Environment.GetEnvironmentVariable("userprofile")

Trying to navigate up from a named SpecialFolder is prone for problems. There are plenty of reasons that the folders won't be where you expect them - users can move them on their own, GPO can move them, folder redirection to UNC paths, etc.

Using the environment variable for the userprofile should reflect any of those possible issues.

Rails: How does the respond_to block work?

What type of variable is format?

From a java POV, format is an implemtation of an anonymous interface. This interface has one method named for each mime type. When you invoke one of those methods (passing it a block), then if rails feels that the user wants that content type, then it will invoke your block.

The twist, of course, is that this anonymous glue object doesn't actually implement an interface - it catches the method calls dynamically and works out if its the name of a mime type that it knows about.

Personally, I think it looks weird: the block that you pass in is executed. It would make more sense to me to pass in a hash of format labels and blocks. But - that's how its done in RoR, it seems.

How to change ViewPager's page?

for switch to another page, try with this code:

viewPager.postDelayed(new Runnable()
{
    @Override
    public void run()
    {
        viewPager.setCurrentItem(num, true);
    }
}, 100);

Execute Python script via crontab

As you have mentioned it doesn't change anything.

First, you should redirect both standard input and standard error from the crontab execution like below:

*/2 * * * * /usr/bin/python /home/souza/Documets/Listener/listener.py > /tmp/listener.log 2>&1

Then you can view the file /tmp/listener.log to see if the script executed as you expected.

Second, I guess what you mean by change anything is by watching the files created by your program:

f = file('counter', 'r+w')
json_file = file('json_file_create_server.json', 'r+w')

The crontab job above won't create these file in directory /home/souza/Documets/Listener, as the cron job is not executed in this directory, and you use relative path in the program. So to create this file in directory /home/souza/Documets/Listener, the following cron job will do the trick:

*/2 * * * * cd /home/souza/Documets/Listener && /usr/bin/python listener.py > /tmp/listener.log 2>&1

Change to the working directory and execute the script from there, and then you can view the files created in place.

How to find all the dependencies of a table in sql server

The following SQL lists all object dependencies across all databases and servers:

IF(OBJECT_ID('tempdb..#Obj_Dep_Details') IS NOT NULL)
BEGIN
    DROP TABLE #Obj_Dep_Details
END
CREATE TABLE #Obj_Dep_Details
(
   [Database]               nvarchar(128)
  ,[Schema]                 nvarchar(128)
  ,dependent_object         nvarchar(128)
  ,dependent_object_type    nvarchar(60)
  ,referenced_server_name   nvarchar(128)
  ,referenced_database_name nvarchar(128)
  ,referenced_schema_name   nvarchar(128)
  ,referenced_entity_name   nvarchar(128)
  ,referenced_id            int
  ,referenced_object_db     nvarchar(128)
  ,referenced_object_type   nvarchar(60)
  ,referencing_id           int
  ,SchemaDep                nvarchar(128)
)
EXEC sp_MSForEachDB @command1='USE [?];
INSERT INTO #Obj_Dep_Details
SELECT DISTINCT
       DB_NAME()                          AS [Database]
      ,SCHEMA_NAME(od.[schema_id])        AS [Schema]
      ,OBJECT_NAME(d1.referencing_id)     AS dependent_object
      ,od.[type_desc]                     AS dependent_object_type
      ,COALESCE(d1.referenced_server_name, @@SERVERNAME)                AS referenced_server_name
      ,COALESCE(d1.referenced_database_name, DB_NAME())                 AS referenced_database_name
      ,COALESCE(d1.referenced_schema_name, SCHEMA_NAME(ro.[schema_id])) AS referenced_schema_name
      ,d1.referenced_entity_name
      ,d1.referenced_id
      ,DB_NAME(ro.parent_object_id)        AS referenced_object_db
      ,ro.[type_desc]                      AS referenced_object_type
      ,d1.referencing_id
      ,SCHEMA_NAME(od.[schema_id])         AS SchemaDep
  FROM sys.sql_expression_dependencies d1
  LEFT OUTER JOIN sys.all_objects od
    ON d1.referencing_id = od.[object_id]
  LEFT OUTER JOIN sys.objects ro
    ON d1.referenced_id = ro.[object_id]'

SELECT [Database]                                       AS [Dep_Object_DB]
      ,[Schema]                                         AS [Dep_Object_Schema]
      ,dependent_object                                 AS [Dep_Object_Name]
      ,LOWER(REPLACE(dependent_object_type, '_', ' '))  AS [Dep_Object_Type]
      ,referenced_server_name                           AS [Ref_Object_Server_Name]
      ,referenced_database_name                         AS [Ref_Object_DB]
      ,referenced_schema_name                           AS [Ref_Object_Schema]
      ,referenced_entity_name                           AS [Ref_Object_Name]
      ,referenced_id                                    AS [Ref_Object_ID]
      ,LOWER(REPLACE(referenced_object_type, '_', ' ')) AS [Ref_Object_Type]
      ,referencing_id                                   AS [Dep_Object_ID]
  FROM #Obj_Dep_Details WITH(NOLOCK)
 WHERE referenced_entity_name = 'TableName'
ORDER BY [Dep_Object_DB]
        ,[Dep_Object_Name]
        ,[Ref_Object_Name]
        ,[Ref_Object_DB]

TableName Dependencies

Is there a way to specify which pytest tests to run from a file?

If you have the same method name in two different classes and you just want to run one of them, this works:

pytest tests.py -k 'TestClassName and test_method_name'

Difference between objectForKey and valueForKey?

When you do valueForKey: you need to give it an NSString, whereas objectForKey: can take any NSObject subclass as a key. This is because for Key-Value Coding, the keys are always strings.

In fact, the documentation states that even when you give valueForKey: an NSString, it will invoke objectForKey: anyway unless the string starts with an @, in which case it invokes [super valueForKey:], which may call valueForUndefinedKey: which may raise an exception.

Getting error: Peer authentication failed for user "postgres", when trying to get pgsql working with rails

You need just set METHOD to trust.

#TYPE  DATABASE        USER            ADDRESS                 METHOD
local    all             all                                     trust

And reload postgres server.

# service postgresql-9.5 reload

Changes in pg_hba.conf dont require RESTART postgres server. just RELOAD.

If isset $_POST

You can try,

 <?php

     if (isset($_POST["mail"])) {
            echo "Yes, mail is set";    
        }else{  
            echo "N0, mail is not set";
        }
  ?>

How to declare empty list and then add string in scala?

In your case I use: val dm = ListBuffer[String]() and val dk = ListBuffer[Map[String,anyRef]]()

Authentication versus Authorization

Imagine that you have registered for a tech conference. You arrive and walk up to the registration table outside to get your conference badge. You have to first show some form of identification, such as a driver's license. Your driver's license identifies you (with your picture, for example) and is distributed by a trusted entity (the DMV). This is authentication.

The person hands you your badge, which is red, blue, or green. Walking around inside the conference, some of the exhibits are color-coded. With a green badge, you can enter the green exhibits, but not the blue or red exhibits. The badge is not distributed by the DMV -- rather, it is distributed by the conference itself, to access conference resources inside the conference hall.

There is not necessarily anything about the badge that identifies you (it may have your name printed on it, but you can easily borrow your friend's blue badge to visit a blue exhibit -- nobody is going to check your name, just the color blue). The color of your badge grants you access to exhibits. This is authorization.

Find non-ASCII characters in varchar columns using SQL Server

There is a user defined function available on the web 'Parse Alphanumeric'. Google UDF parse alphanumeric and you should find the code for it. This user defined function removes all characters that doesn't fit between 0-9, a-z, and A-Z.

Select * from Staging.APARMRE1 ar
where udf_parsealpha(ar.last_name) <> ar.last_name

That should bring back any records that have a last_name with invalid chars for you...though your bonus points question is a bit more of a challenge, but I think a case statement could handle it. This is a bit psuedo code, I'm not entirely sure if it'd work.

Select id, case when udf_parsealpha(ar.last_name) <> ar.last_name then 'last name'
when udf_parsealpha(ar.first_name) <> ar.first_name then 'first name'
when udf_parsealpha(ar.Address1) <> ar.last_name then 'Address1'
end, 
case when udf_parsealpha(ar.last_name) <> ar.last_name then ar.last_name
when udf_parsealpha(ar.first_name) <> ar.first_name then ar.first_name
when udf_parsealpha(ar.Address1) <> ar.last_name then ar.Address1
end
from Staging.APARMRE1 ar
where udf_parsealpha(ar.last_name) <> ar.last_name or
udf_parsealpha(ar.first_name) <> ar.first_name or
udf_parsealpha(ar.Address1) <> ar.last_name 

I wrote this in the forum post box...so I'm not quite sure if that'll function as is, but it should be close. I'm not quite sure how it will behave if a single record has two fields with invalid chars either.

As an alternative, you should be able to change the from clause away from a single table and into a subquery that looks something like:

select id,fieldname,value from (
Select id,'last_name' as 'fieldname', last_name as 'value'
from Staging.APARMRE1 ar
Union
Select id,'first_name' as 'fieldname', first_name as 'value'
from Staging.APARMRE1 ar
---(and repeat unions for each field)
)
where udf_parsealpha(value) <> value

Benefit here is for every column you'll only need to extend the union statement here, while you need to put that comparisson three times for every column in the case statement version of this script

How can I combine multiple nested Substitute functions in Excel?

To simply combine them you can place them all together like this:

=SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(A2,"_AB","_"),"_CD","_"),"_EF","_"),"_40K",""),"_60K",""),"_S_","_"),"_","-")

(note that this may pass the older Excel limit of 7 nested statements. I'm testing in Excel 2010


Another way to do it is by utilizing Left and Right functions.

This assumes that the changing data on the end is always present and is 8 characters long

=SUBSTITUTE(LEFT(A2,LEN(A2)-8),"_","-")

This will achieve the same resulting string


If the string doesn't always end with 8 characters that you want to strip off you can search for the "_S" and get the current location. Try this:

=SUBSTITUTE(LEFT(A2,FIND("_S",A2,1)),"_","-")

Gradient borders

Try this, it worked for me.

_x000D_
_x000D_
div{_x000D_
  border-radius: 20px;_x000D_
  height: 70vh;_x000D_
  overflow: hidden;_x000D_
}_x000D_
_x000D_
div::before{_x000D_
  content: '';_x000D_
  display: block;_x000D_
  box-sizing: border-box;_x000D_
  height: 100%;_x000D_
_x000D_
  border: 1em solid transparent;_x000D_
  border-image: linear-gradient(to top, red 0%, blue 100%);_x000D_
  border-image-slice: 1;_x000D_
}
_x000D_
<div></div>
_x000D_
_x000D_
_x000D_

The link is to the fiddle https://jsfiddle.net/yash009/kayjqve3/1/ hope this helps

Nested Git repositories?

Place your third party libraries in a separate repository and use submodules to associate them with the main project. Here is a walk-through:

http://git-scm.com/book/en/Git-Tools-Submodules

In deciding how to segment a repo I would usually decide based on how often I would modify them. If it is a third-party library and only changes you are making to it is upgrading to a newer version then you should definitely separate it from the main project.

How to add multiple jar files in classpath in linux

Say you have multiple jar files a.jar,b.jar and c.jar. To add them to classpath while compiling you need to do

$javac -cp .:a.jar:b.jar:c.jar HelloWorld.java

To run do

$java -cp .:a.jar:b.jar:c.jar HelloWorld

How to enumerate an enum with String type?

enum Rank: Int {
    case Ace = 1
    case Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten
    case Jack, Queen, King

    func simpleDescription() -> String {
        switch self {
        case .Ace: return "ace"
        case .Jack: return "jack"
        case .Queen: return "queen"
        case .King: return "king"
        default: return String(self.toRaw())
        }
    }
}

enum Suit: Int {
    case Spades = 1
    case Hearts, Diamonds, Clubs

    func simpleDescription() -> String {
        switch self {
        case .Spades: return "spades"
        case .Hearts: return "hearts"
        case .Diamonds: return "diamonds"
        case .Clubs: return "clubs"
        }
    }

    func color() -> String {
        switch self {
        case .Spades, .Clubs: return "black"
        case .Hearts, .Diamonds: return "red"
        }
    }
}

struct Card {
    var rank: Rank
    var suit: Suit
    func simpleDescription() -> String {
        return "The \(rank.simpleDescription()) of \(suit.simpleDescription())"
    }

    static func createPokers() -> Card[] {
        let ranks = Array(Rank.Ace.toRaw()...Rank.King.toRaw())
        let suits = Array(Suit.Spades.toRaw()...Suit.Clubs.toRaw())
        let cards = suits.reduce(Card[]()) { (tempCards, suit) in
            tempCards + ranks.map { rank in
                Card(rank: Rank.fromRaw(rank)!, suit: Suit.fromRaw(suit)!)
            }
        }
        return cards
    }
}

How to get pandas.DataFrame columns containing specific dtype

Someone will give you a better answe than this possibly, but one thing I tend to do is if all my numeric data are int64 or float64 objects, then you can create a dict of the column data types and then use the values to create your list of columns.

So for example, in a dataframe where I have columns of type float64, int64 and object firstly you can look at the data types as so:

DF.dtypes

and if they conform to the standard whereby the non-numeric columns of data are all object types (as they are in my dataframes), then you can do the following to get a list of the numeric columns:

[key for key in dict(DF.dtypes) if dict(DF.dtypes)[key] in ['float64', 'int64']]

Its just a simple list comprehension. Nothing fancy. Again, though whether this works for you will depend upon how you set up you dataframe...

A reference to the dll could not be added

I had this issue after my PC has been restarted during building the solution. My two references gone, so I had to rebuild my two projects manually and then I could add references without error.

Autoplay an audio with HTML5 embed tag while the player is invisible

You can use this simple code:

<embed src="audio.mp3" AutoPlay loop hidden>

for the result seen here: https://hataken.000webhostapp.com/list-anime.html

Visual Studio replace tab with 4 spaces?

If you don't see the formatting option, you can do Tools->Import and Export settings to import the missing one.

How to style the <option> with only CSS?

There is no cross-browser way of styling option elements, certainly not to the extent of your second screenshot. You might be able to make them bold, and set the font-size, but that will be about it...

select count(*) from table of mysql in php

$db  = new PDO('mysql:host=localhost;dbname=java_db', 'root', 'pass');
$Sql = "SELECT count(*) as `total` FROM users";
$stmt = $db->query($Sql);
$stmt->execute();
$total = $stmt->fetch(PDO::FETCH_ASSOC);
print '<pre>';
print_r($total);
print '</pre>';

Result:

enter image description here

How do I get the backtrace for all the threads in GDB?

Is there a command that does?

thread apply all where

What does %~dp0 mean, and how does it work?

Great example from Strawberry Perl's portable shell launcher:

set drive=%~dp0
set drivep=%drive%
if #%drive:~-1%# == #\# set drivep=%drive:~0,-1%

set PATH=%drivep%\perl\site\bin;%drivep%\perl\bin;%drivep%\c\bin;%PATH%

not sure what the negative 1's doing there myself, but it works a treat!

Start an Activity with a parameter

The existing answers (pass the data in the Intent passed to startActivity()) show the normal way to solve this problem. There is another solution that can be used in the odd case where you're creating an Activity that will be started by another app (for example, one of the edit activities in a Tasker plugin) and therefore do not control the Intent which launches the Activity.

You can create a base-class Activity that has a constructor with a parameter, then a derived class that has a default constructor which calls the base-class constructor with a value, as so:

class BaseActivity extends Activity
{
    public BaseActivity(String param)
    {
        // Do something with param
    }
}

class DerivedActivity extends BaseActivity
{
    public DerivedActivity()
    {
        super("parameter");
    }
}

If you need to generate the parameter to pass to the base-class constructor, simply replace the hard-coded value with a function call that returns the correct value to pass.

How can I get the sha1 hash of a string in node.js?

Tips to prevent issue (bad hash) :

I experienced that NodeJS is hashing the UTF-8 representation of the string. Other languages (like Python, PHP or PERL...) are hashing the byte string.

We can add binary argument to use the byte string.

const crypto = require("crypto");

function sha1(data) {
    return crypto.createHash("sha1").update(data, "binary").digest("hex");
}

sha1("Your text ;)");

You can try with : "\xac", "\xd1", "\xb9", "\xe2", "\xbb", "\x93", etc...

Other languages (Python, PHP, ...):

sha1("\xac") //39527c59247a39d18ad48b9947ea738396a3bc47

Nodejs:

sha1 = crypto.createHash("sha1").update("\xac", "binary").digest("hex") //39527c59247a39d18ad48b9947ea738396a3bc47
//without:
sha1 = crypto.createHash("sha1").update("\xac").digest("hex") //f50eb35d94f1d75480496e54f4b4a472a9148752

PreparedStatement setNull(..)

You could also consider using preparedStatement.setObject(index,value,type);

HTML5 Canvas background image

Canvas does not using .png file as background image. changing to other file extensions like gif or jpg works fine.

Read all contacts' phone numbers in android

Following code shows an easy way to read all phone numbers and names:

Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,null,null, null);
while (phones.moveToNext())
{
  String name=phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
  String phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));

}
phones.close();

NOTE: getContentResolver is a method from the Activity context.

how to get docker-compose to use the latest image from repository

To close this question, what seemed to have worked is indeed running

docker-compose stop
docker-compose rm -f
docker-compose -f docker-compose.yml up -d

I.e. remove the containers before running up again.

What one needs to keep in mind when doing it like this is that data volume containers are removed as well if you just run rm -f. In order to prevent that I specify explicitly each container to remove:

docker-compose rm -f application nginx php

As I said in my question, I don't know if this is the correct process. But this seems to work for our use case, so until we find a better solution we'll roll with this one.

How to get the clicked link's href with jquery?

$(".testClick").click(function () {
         var value = $(this).attr("href");
         alert(value );     
}); 

When you use $(".className") you are getting the set of all elements that have that class. Then when you call attr it simply returns the value of the first item in the collection.

printing out a 2-D array in Matrix format

In java8 fashion:

import java.util.Arrays;

public class MatrixPrinter {

    public static void main(String[] args) {
        final int[][] matrix = new int[4][4];
        printMatrix(matrix);
    }

    public static void printMatrix(int[][] matrix) {
        Arrays.stream(matrix)
        .forEach(
            (row) -> {
                System.out.print("[");
                Arrays.stream(row)
                .forEach((el) -> System.out.print(" " + el + " "));
                System.out.println("]");
            }
        );
    }

}

this produces

[ 0  0  0  0 ]
[ 0  0  0  0 ]
[ 0  0  0  0 ]
[ 0  0  0  0 ]

but since we are here why not make the row layout customisable?

All we need is to pass a lamba to the matrixPrinter method:

import java.util.Arrays;
import java.util.function.Consumer;

public class MatrixPrinter {

    public static void main(String[] args) {
        final int[][] matrix = new int[3][3];

        Consumer<int[]> noDelimiter = (row) -> {
            Arrays.stream(row).forEach((el) -> System.out.print(" " + el + " "));
            System.out.println();
        };

        Consumer<int[]> pipeDelimiter = (row) -> {
            Arrays.stream(row).forEach((el) -> System.out.print("| " + el + " "));
            System.out.println("|");
        };

        Consumer<int[]> likeAList = (row) -> {
            System.out.print("[");
            Arrays.stream(row)
            .forEach((el) -> System.out.print(" " + el + " "));
            System.out.println("]");
        };

        printMatrix(matrix, noDelimiter);
        System.out.println();
        printMatrix(matrix, pipeDelimiter);
        System.out.println();
        printMatrix(matrix, likeAList);

    }

    public static void printMatrix(int[][] matrix, Consumer<int[]> rowPrinter) {
        Arrays.stream(matrix)
        .forEach((row) -> rowPrinter.accept(row));
    }

}

this is the result :

 0  0  0 
 0  0  0 
 0  0  0 

| 0 | 0 | 0 |
| 0 | 0 | 0 |
| 0 | 0 | 0 |

[ 0  0  0 ]
[ 0  0  0 ]
[ 0  0  0 ]

Uncaught ReferenceError: function is not defined with onclick

Make sure you are using Javascript module or not?! if using js6 modules your html events attributes won't work. in that case you must bring your function from global scope to module scope. Just add this to your javascript file: window.functionName= functionName;

example:

<h1 onClick="functionName">some thing</h1>

urllib2 and json

You certainly want to hack the header to have a proper Ajax Request :

headers = {'X_REQUESTED_WITH' :'XMLHttpRequest',
           'ACCEPT': 'application/json, text/javascript, */*; q=0.01',}
request = urllib2.Request(path, data, headers)
response = urllib2.urlopen(request).read()

And to json.loads the POST on the server-side.

Edit : By the way, you have to urllib.urlencode(mydata_dict) before sending them. If you don't, the POST won't be what the server expect

What are the differences and similarities between ffmpeg, libav, and avconv?

Confusing messages

These messages are rather misleading and understandably a source of confusion. Older Ubuntu versions used Libav which is a fork of the FFmpeg project. FFmpeg returned in Ubuntu 15.04 "Vivid Vervet".

The fork was basically a non-amicable result of conflicting personalities and development styles within the FFmpeg community. It is worth noting that the maintainer for Debian/Ubuntu switched from FFmpeg to Libav on his own accord due to being involved with the Libav fork.

The real ffmpeg vs the fake one

For a while both Libav and FFmpeg separately developed their own version of ffmpeg.

Libav then renamed their bizarro ffmpeg to avconv to distance themselves from the FFmpeg project. During the transition period the "not developed anymore" message was displayed to tell users to start using avconv instead of their counterfeit version of ffmpeg. This confused users into thinking that FFmpeg (the project) is dead, which is not true. A bad choice of words, but I can't imagine Libav not expecting such a response by general users.

This message was removed upstream when the fake "ffmpeg" was finally removed from the Libav source, but, depending on your version, it can still show up in Ubuntu because the Libav source Ubuntu uses is from the ffmpeg-to-avconv transition period.

In June 2012, the message was re-worded for the package libav - 4:0.8.3-0ubuntu0.12.04.1. Unfortunately the new "deprecated" message has caused additional user confusion.

Starting with Ubuntu 15.04 "Vivid Vervet", FFmpeg's ffmpeg is back in the repositories again.

libav vs Libav

To further complicate matters, Libav chose a name that was historically used by FFmpeg to refer to its libraries (libavcodec, libavformat, etc). For example the libav-user mailing list, for questions and discussions about using the FFmpeg libraries, is unrelated to the Libav project.

How to tell the difference

If you are using avconv then you are using Libav. If you are using ffmpeg you could be using FFmpeg or Libav. Refer to the first line in the console output to tell the difference: the copyright notice will either mention FFmpeg or Libav.

Secondly, the version numbering schemes differ. Each of the FFmpeg or Libav libraries contains a version.h header which shows a version number. FFmpeg will end in three digits, such as 57.67.100, and Libav will end in one digit such as 57.67.0. You can also view the library version numbers by running ffmpeg or avconv and viewing the console output.

If you want to use the real ffmpeg

Ubuntu 15.04 "Vivid Vervet" or newer

The real ffmpeg is in the repository, so you can install it with:

apt-get install ffmpeg

For older Ubuntu versions

Your options are:

These methods are non-intrusive, reversible, and will not interfere with the system or any repository packages.

Another possible option is to upgrade to Ubuntu 15.04 "Vivid Vervet" or newer and just use ffmpeg from the repository.

Also see

For an interesting blog article on the situation, as well as a discussion about the main technical differences between the projects, see The FFmpeg/Libav situation.

VBA changing active workbook

Use ThisWorkbook which will refer to the original workbook which holds the code.

Alternatively at code start

Dim Wb As Workbook
Set Wb = ActiveWorkbook

sample code that activates all open books before returning to ThisWorkbook

Sub Test()
Dim Wb As Workbook
Dim Wb2 As Workbook
Set Wb = ThisWorkbook
For Each Wb2 In Application.Workbooks
    Wb2.Activate
Next
Wb.Activate
End Sub

How to put php inside JavaScript?

You're missing quotes around your string:

...
var htmlString="<?php echo $htmlString; ?>";
...

In Java how does one turn a String into a char or a char into a String?

In order to convert string to char

 String str = "abcd";
char arr [] = new char[len]; // len is the length of the array
arr = str.toCharArray();

Prevent HTML5 video from being downloaded (right-click saved)?

Here's what I did:

_x000D_
_x000D_
function noRightClick() {_x000D_
      alert("You cannot save this video for copyright reasons. Sorry about that.");_x000D_
}
_x000D_
    <body oncontextmenu="noRightClick();">_x000D_
    <video>_x000D_
    <source src="http://calumchilds.com/videos/big_buck_bunny.mp4" type="video/mp4">_x000D_
    </video>_x000D_
    </body>
_x000D_
_x000D_
_x000D_ This also works for images, text and pretty much anything. However, you can still access the "Inspect" and the "View source" tool through keyboard shortcuts. (As the answer at the top says, you can't stop it entirely.) But you can try to put barriers up to stop them.

Logging framework incompatibility

You are mixing the 1.5.6 version of the jcl bridge with the 1.6.0 version of the slf4j-api; this won't work because of a few changes in 1.6.0. Use the same versions for both, i.e. 1.6.1 (the latest). I use the jcl-over-slf4j bridge all the time and it works fine.

How to get the fragment instance from the FragmentActivity?

To get the fragment instance in a class that extends FragmentActivity:

MyclassFragment instanceFragment=
    (MyclassFragment)getSupportFragmentManager().findFragmentById(R.id.idFragment);

To get the fragment instance in a class that extends Fragment:

MyclassFragment instanceFragment =  
    (MyclassFragment)getFragmentManager().findFragmentById(R.id.idFragment);

Add item to Listview control

Simple one, just do like this..

ListViewItem lvi = new ListViewItem(pet.Name);
    lvi.SubItems.Add(pet.Type);
    lvi.SubItems.Add(pet.Age);
    listView.Items.Add(lvi);

Defining a percentage width for a LinearLayout?

Use new percentage support library

compile 'com.android.support:percent:24.0.0'

See below example

<android.support.percent.PercentRelativeLayout
     xmlns:android="http://schemas.android.com/apk/res/android"
     xmlns:app="http://schemas.android.com/apk/res-auto"
     android:layout_width="match_parent"
     android:layout_height="match_parent">
     <ImageView
         app:layout_widthPercent="50%"
         app:layout_heightPercent="50%"
         app:layout_marginTopPercent="25%"
         app:layout_marginLeftPercent="25%"/>
 </android.support.percent.PercentRelativeLayout>

For More Info Tutorial1 Tutorial2 Tutorial3

How to terminate script execution when debugging in Google Chrome?

2020 April update

As of Chrome 80, none of the current answers work. There is no visible "Pause" button - you need to long-click the "Play" button to access the Stop icon:

Stop script execution in Chrome DevTools

Undefined reference to pthread_create in Linux

Since none of the answers exactly covered my need (using MSVS Code), I add here my experience with this IDE and CMAKE build tools too.

Step 1: Make sure in your .cpp, (or .hpp if needed) you have included:

#include <functional>

Step 2 For MSVSCode IDE users: Add this line to your c_cpp_properties.json file:

"compilerArgs": ["-pthread"],

Add this line to your c_cpp_properties.json file

Step 2 For CMAKE build tools users: Add this line to your CMakeLists.txt

set(CMAKE_CXX_FLAGS "-pthread")

Note: Adding flag -lpthread (instead of -pthread) results in failed linking.

React won't load local images

Sometimes you may enter instead of in your image location/src: try

./assets/images/picture.jpg

instead of

../assets/images/picture.jpg

How do I get the first n characters of a string without checking the size or going out of bounds?

Don't reinvent the wheel...:

org.apache.commons.lang.StringUtils.substring(String s, int start, int len)

Javadoc says:

StringUtils.substring(null, *, *)    = null
StringUtils.substring("", * ,  *)    = "";
StringUtils.substring("abc", 0, 2)   = "ab"
StringUtils.substring("abc", 2, 0)   = ""
StringUtils.substring("abc", 2, 4)   = "c"
StringUtils.substring("abc", 4, 6)   = ""
StringUtils.substring("abc", 2, 2)   = ""
StringUtils.substring("abc", -2, -1) = "b"
StringUtils.substring("abc", -4, 2)  = "ab"

Thus:

StringUtils.substring("abc", 0, 4) = "abc"

Finding the last index of an array

The following will return NULL if the array is empty, else the last element.

var item = (arr.Length == 0) ? null : arr[arr.Length - 1]

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

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

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

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

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

Below is a benchmark that Edouard published on his site

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

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

SQL TRUNCATE DATABASE ? How to TRUNCATE ALL TABLES

No nonsense script this:

EXEC sp_MSForEachTable 'ALTER TABLE ? NOCHECK CONSTRAINT ALL'
EXEC sp_MSForEachTable 'DELETE FROM ?'
EXEC sp_MSForEachTable 'ALTER TABLE ? CHECK CONSTRAINT ALL'
EXEC sp_MSforeachtable 'DBCC CHECKIDENT ( ''?'', RESEED, 0)'
GO

Truncate will still not work if you have foreign keys in tables. This script will reset all identity columns as well.

What is the correct XPath for choosing attributes that contain "foo"?

John C is the closest, but XPath is case sensitive, so the correct XPath would be:

/bla/a[contains(@prop, 'Foo')]

JCheckbox - ActionListener and ItemListener?

The difference is that ActionEvent is fired when the action is performed on the JCheckBox that is its state is changed either by clicking on it with the mouse or with a space bar or a mnemonic. It does not really listen to change events whether the JCheckBox is selected or deselected.

For instance, if JCheckBox c1 (say) is added to a ButtonGroup. Changing the state of other JCheckBoxes in the ButtonGroup will not fire an ActionEvent on other JCheckBox, instead an ItemEvent is fired.

Final words: An ItemEvent is fired even when the user deselects a check box by selecting another JCheckBox (when in a ButtonGroup), however ActionEvent is not generated like that instead ActionEvent only listens whether an action is performed on the JCheckBox (to which the ActionListener is registered only) or not. It does not know about ButtonGroup and all other selection/deselection stuff.

How to make JQuery-AJAX request synchronous

I added dataType as json and made the response as json:

PHP

echo json_encode(array('success'=>$res)); //send the response as json **use this instead of echo $res in your php file**

JavaScript

  var ajaxSubmit = function(formE1) {

        var password = $.trim($('#employee_password').val());    
        $.ajax({
            type: "POST",
            async: "false",
            url: "checkpass.php",
            data: "password="+password,
            dataType:'json',  //added this so the response is in json
            success: function(result) {
                var arr=result.success;
                if(arr == "Successful")
                {    return true;
                }
                else
                {    return false;
                }
            }
        });

  return false
}

How do you change the size of figures drawn with matplotlib?

If you've already got the figure created you can quickly do this:

fig = matplotlib.pyplot.gcf()
fig.set_size_inches(18.5, 10.5)
fig.savefig('test2png.png', dpi=100)

To propagate the size change to an existing gui window add forward=True

fig.set_size_inches(18.5, 10.5, forward=True)

How to remove trailing whitespace in code, using another script?

If you're looking to tidy up for PEP8, this will trim trailing whitespace for your whole project:

import os

PATH = '/path/to/your/project'

for path, dirs, files in os.walk(PATH):
    for f in files:
        file_name, file_extension = os.path.splitext(f)
        if file_extension == '.py':
            path_name = os.path.join(path, f)
            with open(path_name, 'r') as fh:
                new = [line.rstrip() for line in fh]
            with open(path_name, 'w') as fh:
                [fh.write('%s\n' % line) for line in new]

How to set a cron job to run every 3 hours

The unix setup should be like the following:

 0 */3 * * * sh cron/update_old_citations.sh

good reference for how to set various settings in cron at: http://www.thegeekstuff.com/2011/07/cron-every-5-minutes/

How to add System.Windows.Interactivity to project?

With Blend for Visual Studio, which is included in Visual Studio starting with version 2013, you can find the DLL in the following folder:

C:\Program Files (x86)\Microsoft SDKs\Expression\Blend\.NETFramework\v4.5\Libraries

You will have to add the reference to the System.Windows.Interactivity.dll yourself though, unless you use Blend for Visual Studio with an existing project to add functionality that makes use of the Interactivity namespace. In that case, Blend will add the reference automatically.

PDO with INSERT INTO through prepared statements

Thanks to Novocaine88's answer to use a try catch loop I have successfully received an error message when I caused one.

    <?php
    $dbhost = "localhost";
    $dbname = "pdo";
    $dbusername = "root";
    $dbpassword = "845625";

    $link = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbusername, $dbpassword);
    $link->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    try {
        $statement = $link->prepare("INERT INTO testtable(name, lastname, age)
            VALUES(?,?,?)");

        $statement->execute(array("Bob","Desaunois",18));
    } catch(PDOException $e) {
        echo $e->getMessage();
    }
    ?>

In the following code instead of INSERT INTO it says INERT.

this is the error I got.

SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'INERT INTO testtable(name, lastname, age) VALUES('Bob','Desaunoi' at line 1

When I "fix" the issue, it works as it should. Thanks alot everyone!

Apache 13 permission denied in user's home directory

Apache's errorlog will explain why you get a permission denied. Also, serverfault.com is a better forum for a question like this.

If the error log simply says "permission denied", su to the user that the webserver is running as and try to read from the file in question. So for example:

sudo -s
su - nobody
cd /
cd /home
cd user
cd xxx
cat index.html

See if one of those gives you the "permission denied" error.

Running javascript in Selenium using Python

If you move from iframes, you may get lost in your page, best way to execute some jquery without issue (with selenimum/python/gecko):

# 1) Get back to the main body page
driver.switch_to.default_content()

# 2) Download jquery lib file to your current folder manually & set path here
with open('./_lib/jquery-3.3.1.min.js', 'r') as jquery_js: 
    # 3) Read the jquery from a file
    jquery = jquery_js.read() 
    # 4) Load jquery lib
    driver.execute_script(jquery)
    # 5) Execute your command 
    driver.execute_script('$("#myId").click()')

htons() function in socket programing

htons is host-to-network short

This means it works on 16-bit short integers. i.e. 2 bytes.

This function swaps the endianness of a short.

Your number starts out at:

0001 0011 1000 1001 = 5001

When the endianness is changed, it swaps the two bytes:

1000 1001 0001 0011 = 35091

How can I format a number into a string with leading zeros?

Here I want my no to limit in 4 digit like if it is 1 it should show as 0001,if it 11 it should show as 0011..Below are the code.

        reciptno=1;//Pass only integer.

        string formatted = string.Format("{0:0000}", reciptno);

        TxtRecNo.Text = formatted;//Output=0001..

I implemented this code to generate Money receipt no.

Add UIPickerView & a Button in Action sheet - How?

I think this is best way to do it.

ActionSheetPicker-3.0

Its pretty much what everyone suggest, but uses blocks, which is a nice touch!

Selenium Finding elements by class name in python

You can try to get the list of all elements with class = "content" by using find_elements_by_class_name:

a = driver.find_elements_by_class_name("content")

Then you can click on the link that you are looking for.

How to change font size in a textbox in html

For a <input type='text'> element:

input { font-size: 18px; }

or for a <textarea>:

textarea { font-size: 18px; }

or for a <select>:

select { font-size: 18px; }

you get the drift.

Maximum size of an Array in Javascript

You could try something like this to test and trim the length:

http://jsfiddle.net/orolo/wJDXL/

_x000D_
_x000D_
var longArray = [1, 2, 3, 4, 5, 6, 7, 8];_x000D_
_x000D_
if (longArray.length >= 6) {_x000D_
  longArray.length = 3;_x000D_
}_x000D_
_x000D_
alert(longArray); //1, 2, 3
_x000D_
_x000D_
_x000D_

How to create a template function within a class? (C++)

Your guess is the correct one. The only thing you have to remember is that the member function template definition (in addition to the declaration) should be in the header file, not the cpp, though it does not have to be in the body of the class declaration itself.

Android open camera from button

the below code does exactly what you want

//use this intent on click event

Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); startActivityForResult(cameraIntent,CAMERA_REQUEST);

// the above code is used in 'on activity Result'

protected void onActivityResult(int requestCode, int resultCode, Intent data) {

    super.onActivityResult(requestCode, resultCode, data);
    callbackManager.onActivityResult(requestCode, resultCode, data);

    if (requestCode == CAMERA_REQUEST) {
        Bitmap photo = (Bitmap) data.getExtras().get("data");
        image.setImageBitmap(photo);
    }
}

How to set the color of "placeholder" text?

::-webkit-input-placeholder { /* WebKit browsers */
    color:    #999;
}
:-moz-placeholder { /* Mozilla Firefox 4 to 18 */
    color:    #999;
}
::-moz-placeholder { /* Mozilla Firefox 19+ */
    color:    #999;
}
:-ms-input-placeholder { /* Internet Explorer 10+ */
    color:    #999;
}

python replace single backslash with double backslash

You could use

os.path.abspath(path_with_backlash)

it returns the path with \

What does double question mark (??) operator mean in PHP

$x = $y ?? 'dev'

is short hand for x = y if y is set, otherwise x = 'dev'

There is also

$x = $y =="SOMETHING" ? 10 : 20

meaning if y equals 'SOMETHING' then x = 10, otherwise x = 20

Using FileUtils in eclipse

Open the project's properties---> Java Build Path ---> Libraries tab ---> Add External Jars

will allow you to add jars.

You need to download commonsIO from here.

The application may be doing too much work on its main thread

I too had the same problem.
Mine was a case where i was using a background image which was in drawables.That particular image was of approx 130kB and was used during splash screen and home page in my android app.

Solution - I just shifted that particular image to drawables-xxx folder from drawables and was able free a lot of memory occupied in background and the skipping frames were no longer skipping.

Update Use 'nodp' drawable resource folder for storing background drawables files.
Will a density qualified drawable folder or drawable-nodpi take precedence?

PHP Multidimensional Array Searching (Find key by specific value)

Another poossible solution is based on the array_search() function. You need to use PHP 5.5.0 or higher.

Example

$userdb=Array
(
(0) => Array
    (
        (uid) => '100',
        (name) => 'Sandra Shush',
        (url) => 'urlof100'
    ),

(1) => Array
    (
        (uid) => '5465',
        (name) => 'Stefanie Mcmohn',
        (pic_square) => 'urlof100'
    ),

(2) => Array
    (
        (uid) => '40489',
        (name) => 'Michael',
        (pic_square) => 'urlof40489'
    )
);

$key = array_search(40489, array_column($userdb, 'uid'));

echo ("The key is: ".$key);
//This will output- The key is: 2

Explanation

The function array_search() has two arguments. The first one is the value that you want to search. The second is where the function should search. The function array_column() gets the values of the elements which key is 'uid'.

Summary

So you could use it as:

array_search('breville-one-touch-tea-maker-BTM800XL', array_column($products, 'slug'));

or, if you prefer:

// define function
function array_search_multidim($array, $column, $key){
    return (array_search($key, array_column($array, $column)));
}

// use it
array_search_multidim($products, 'slug', 'breville-one-touch-tea-maker-BTM800XL');

The original example(by xfoxawy) can be found on the DOCS.
The array_column() page.


Update

Due to Vael comment I was curious, so I made a simple test to meassure the performance of the method that uses array_search and the method proposed on the accepted answer.

I created an array which contained 1000 arrays, the structure was like this (all data was randomized):

[
      {
            "_id": "57fe684fb22a07039b3f196c",
            "index": 0,
            "guid": "98dd3515-3f1e-4b89-8bb9-103b0d67e613",
            "isActive": true,
            "balance": "$2,372.04",
            "picture": "http://placehold.it/32x32",
            "age": 21,
            "eyeColor": "blue",
            "name": "Green",
            "company": "MIXERS"
      },...
]

I ran the search test 100 times searching for different values for the name field, and then I calculated the mean time in milliseconds. Here you can see an example.

Results were that the method proposed on this answer needed about 2E-7 to find the value, while the accepted answer method needed about 8E-7.

Like I said before both times are pretty aceptable for an application using an array with this size. If the size grows a lot, let's say 1M elements, then this little difference will be increased too.

Update II

I've added a test for the method based in array_walk_recursive which was mentionend on some of the answers here. The result got is the correct one. And if we focus on the performance, its a bit worse than the others examined on the test. In the test, you can see that is about 10 times slower than the method based on array_search. Again, this isn't a very relevant difference for the most of the applications.

Update III

Thanks to @mickmackusa for spotting several limitations on this method:

  • This method will fail on associative keys.
  • This method will only work on indexed subarrays (starting from 0 and have consecutively ascending keys).

getting " (1) no such column: _id10 " error

I think you missed a equal sign at:

Cursor c = ourDatabase.query(DATABASE_TABLE, column, KEY_ROWID + "" + l, null, null, null, null);  

Change to:

Cursor c = ourDatabase.query(DATABASE_TABLE, column, KEY_ROWID + " = " + l, null, null, null, null); 

JQuery - File attributes

To get the filenames, use:

var files = document.getElementById('inputElementID').files;

Using jQuery (since you already are) you can adapt this to the following:

$('input[type="file"][multiple]').change(
    function(e){
        var files = this.files;
        for (i=0;i<files.length;i++){
            console.log(files[i].fileName + ' (' + files[i].fileSize + ').');
        }
        return false;
    });

JS Fiddle demo.

CSS hover vs. JavaScript mouseover

In reguards to using jQuery to do hover, I always use the plugin HoverIntent as it doesn't fire the event until you pause over an element for brief period of time... this stops firing off lots of mouse over events if you accidentally run the mouse over them or simply whilst choosing an option.

No 'Access-Control-Allow-Origin' header in Angular 2 app

I had the same problem when I was practising Angular5. Then I came across https://spring.io/guides/gs/rest-service-cors/ which helped me to resolve the issue.

I have kept @CrossOrigin(exposedHeaders="Access-Control-Allow-Origin") on my request mapping method. We can also configure this globally in spring boot application.

Oracle SqlDeveloper JDK path

another thing you could try is to rename your old jdk folder, lets say its:

C:\Program Files\Java\jdk1.7.0_04

change it to saomething like:

C:\Program Files\Java\xxxjdk1.7.0_04

Now, you should once again asked to set your jdk folder location on Oracle SqlDeveloper launch, and you can chose the right path.

Not the most elegant solution, but it worked for me.

Milos

Compiler error: "class, interface, or enum expected"

You forgot your class declaration:

public class MyClass {
...

How to set the height of table header in UITableView?

If you changed height of tableView's headerView, just reset headerView's frame, then, reset headerView of tableView:

self.headerView.frame = newFrame;
self.tableView.tableHeaderView = self.headerView;

Importing PNG files into Numpy?

According to the doc, scipy.misc.imread is deprecated starting SciPy 1.0.0, and will be removed in 1.2.0. Consider using imageio.imread instead.

Example:

import imageio

im = imageio.imread('my_image.png')
print(im.shape)

You can also use imageio to load from fancy sources:

im = imageio.imread('http://upload.wikimedia.org/wikipedia/commons/d/de/Wikipedia_Logo_1.0.png')

Edit:

To load all of the *.png files in a specific folder, you could use the glob package:

import imageio
import glob

for im_path in glob.glob("path/to/folder/*.png"):
     im = imageio.imread(im_path)
     print(im.shape)
     # do whatever with the image here

Most efficient way to reverse a numpy array

As mentioned above, a[::-1] really only creates a view, so it's a constant-time operation (and as such doesn't take longer as the array grows). If you need the array to be contiguous (for example because you're performing many vector operations with it), ascontiguousarray is about as fast as flipud/fliplr:

enter image description here


Code to generate the plot:

import numpy
import perfplot


perfplot.show(
    setup=lambda n: numpy.random.randint(0, 1000, n),
    kernels=[
        lambda a: a[::-1],
        lambda a: numpy.ascontiguousarray(a[::-1]),
        lambda a: numpy.fliplr([a])[0],
    ],
    labels=["a[::-1]", "ascontiguousarray(a[::-1])", "fliplr"],
    n_range=[2 ** k for k in range(25)],
    xlabel="len(a)",
)

Cmake is not able to find Python-libraries

You can fix the errors by appending to the cmake command the -DPYTHON_LIBRARY and -DPYTHON_INCLUDE_DIR flags filled with the respective folders.

Thus, the trick is to fill those parameters with the returned information from the python interpreter, which is the most reliable. This may work independently of your python location/version (also for Anaconda users):

$ cmake .. \
-DPYTHON_INCLUDE_DIR=$(python -c "from distutils.sysconfig import get_python_inc; print(get_python_inc())")  \
-DPYTHON_LIBRARY=$(python -c "import distutils.sysconfig as sysconfig; print(sysconfig.get_config_var('LIBDIR'))")

If the version of python that you want to link against cmake is Python3.X and the default python symlink points to Python2.X, python3 -c ... can be used instead of python -c ....

In case that the error persists, you may need to update the cmake to a higher version as stated by @pdpcosta and repeat the process again.

regex match any single character (one character only)

Match any single character

  • Use the dot . character as a wildcard to match any single character.

Example regex: a.c

abc   // match
a c   // match
azc   // match
ac    // no match
abbc  // no match

Match any specific character in a set

  • Use square brackets [] to match any characters in a set.
  • Use \w to match any single alphanumeric character: 0-9, a-z, A-Z, and _ (underscore).
  • Use \d to match any single digit.
  • Use \s to match any single whitespace character.

Example 1 regex: a[bcd]c

abc   // match
acc   // match
adc   // match
ac    // no match
abbc  // no match

Example 2 regex: a[0-7]c

a0c   // match
a3c   // match
a7c   // match
a8c   // no match
ac    // no match
a55c  // no match

Match any character except ...

Use the hat in square brackets [^] to match any single character except for any of the characters that come after the hat ^.

Example regex: a[^abc]c

aac   // no match
abc   // no match
acc   // no match
a c   // match
azc   // match
ac    // no match
azzc  // no match

(Don't confuse the ^ here in [^] with its other usage as the start of line character: ^ = line start, $ = line end.)

Match any character optionally

Use the optional character ? after any character to specify zero or one occurrence of that character. Thus, you would use .? to match any single character optionally.

Example regex: a.?c

abc   // match
a c   // match
azc   // match
ac    // match
abbc  // no match

See also

The entity type <type> is not part of the model for the current context

The message was pretty clear but I didn't get it at first...

I'm working with two Entity Framework DB contexts sysContext and shardContext in the same method.

The entity I had modified\updated is from one context but then I tried to save it to the other context like this:

invite.uid = user.uid;

sysContext.Entry(invite).State = EntityState.Modified;

sysContext.SaveChanges(); // Got the exception here

but the correct version should be this:

invite.uid = user.uid;

shardContext.Entry(invite).State = EntityState.Modified;

shardContext.SaveChanges();

After passing the entity to the correct context this error went away.

No route matches "/users/sign_out" devise rails 3

Many answers to the question already. For me the problem was two fold:

  1. when I expand my routes:

    devise_for :users do 
       get '/users/sign_out' => 'devise/sessions#destroy'
    end
    
  2. I was getting warning that this is depreciated so I have replaced it with:

    devise_scope :users do
       get '/users/sign_out' => 'devise/sessions#destroy'
    end
    
  3. I thought I will remove my jQuery. Bad choice. Devise is using jQuery to "fake" DELETE request and send it as GET. Therefore you need to:

    //= require jquery
    //= require jquery_ujs
    
  4. and of course same link as many mentioned before:

    <%= link_to "Sign out", destroy_user_session_path, :method => :delete %>
    

How to split a String by space

While the accepted answer is good, be aware that you will end up with a leading empty string if your input string starts with a white space. For example, with:

String str = " Hello I'm your String";
String[] splitStr = str.split("\\s+");

The result will be:

splitStr[0] == "";
splitStr[1] == "Hello";
splitStr[2] == "I'm";
splitStr[3] == "Your";
splitStr[4] == "String";

So you might want to trim your string before splitting it:

String str = " Hello I'm your String";
String[] splitStr = str.trim().split("\\s+");

[edit]

In addition to the trim caveat, you might want to consider the unicode non-breaking space character (U+00A0). This character prints just like a regular space in string, and often lurks in copy-pasted text from rich text editors or web pages. They are not handled by .trim() which tests for characters to remove using c <= ' '; \s will not catch them either.

Instead, you can use \p{Blank} but you need to enable unicode character support as well which the regular split won't do. For example, this will work: Pattern.compile("\\p{Blank}", UNICODE_CHARACTER_CLASS).split(words) but it won't do the trim part.

The following demonstrates the problem and provides a solution. It is far from optimal to rely on regex for this, but now that Java has 8bit / 16bit byte representation, an efficient solution for this becomes quite long.

public class SplitStringTest
{
    static final Pattern TRIM_UNICODE_PATTERN = Pattern.compile("^\\p{Blank}*(.*)\\p{Blank}$", UNICODE_CHARACTER_CLASS);
    static final Pattern SPLIT_SPACE_UNICODE_PATTERN = Pattern.compile("\\p{Blank}", UNICODE_CHARACTER_CLASS);

    public static String[] trimSplitUnicodeBySpace(String str)
    {
        Matcher trimMatcher = TRIM_UNICODE_PATTERN.matcher(str);
        boolean ignore = trimMatcher.matches(); // always true but must be called since it does the actual matching/grouping
        return SPLIT_SPACE_UNICODE_PATTERN.split(trimMatcher.group(1));
    }

    @Test
    void test()
    {
        String words = " Hello I'm\u00A0your String\u00A0";
        // non-breaking space here --^ and there -----^

        String[] split = words.split(" ");
        String[] trimAndSplit = words.trim().split(" ");
        String[] splitUnicode = SPLIT_SPACE_UNICODE_PATTERN.split(words);
        String[] trimAndSplitUnicode = trimSplitUnicodeBySpace(words);

        System.out.println("words: [" + words + "]");
        System.out.println("split: [" + Arrays.stream(split).collect(Collectors.joining("][")) + "]");
        System.out.println("trimAndSplit: [" + Arrays.stream(trimAndSplit).collect(Collectors.joining("][")) + "]");
        System.out.println("splitUnicode: [" + Arrays.stream(splitUnicode).collect(Collectors.joining("][")) + "]");
        System.out.println("trimAndSplitUnicode: [" + Arrays.stream(trimAndSplitUnicode).collect(Collectors.joining("][")) + "]");
    }
}

Results in:

words: [ Hello I'm your String ]
split: [][Hello][I'm your][String ]
trimAndSplit: [Hello][I'm your][String ]
splitUnicode: [][Hello][I'm][your][String]
trimAndSplitUnicode: [Hello][I'm][your][String]

Deny all, allow only one IP through htaccess

Just in addition to @David Brown´s answer, if you want to block an IP, you must first allow all then block the IPs as such:

    <RequireAll>
      Require all granted
      Require not ip 10.0.0.0/255.0.0.0
      Require not ip 172.16.0.0/12
      Require not ip 192.168
    </RequireAll>

First line allows all
Second line blocks from 10.0.0.0 to 10.255.255.255
Third line blocks from 172.16.0.0 to 172.31.255.255
Fourth line blocks from 192.168.0.0 to 192.168.255.255

You may use any of the notations mentioned above to suit you CIDR needs.

Rounding float in Ruby

For ruby 1.8.7 you could add the following to your code:

class Float
    alias oldround:round
    def round(precision = nil)
        if precision.nil?
            return self
        else
            return ((self * 10**precision).oldround.to_f) / (10**precision)
        end 
    end 
end

How to Toggle a div's visibility by using a button click

Bootstrap 4 provides the Collapse component for that. It's using JavaScript behind the scenes, but you don't have to write any JavaScript yourself.

This feature works for <button> and <a>.

If you use a <button>, you must set the data-toggle and data-target attributes:

<button type="button" data-toggle="collapse" data-target="#collapseExample">
  Toggle
</button>
<div class="collapse" id="collapseExample">
  Lorem ipsum
</div>

If you use a <a>, you must use set href and data-toggle:

<a data-toggle="collapse" href="#collapseExample">
  Toggle
</a>
<div class="collapse" id="collapseExample">
  Lorem ipsum
</div>

Fixed Table Cell Width

table td 
{
  table-layout:fixed;
  width:20px;
  overflow:hidden;
  word-wrap:break-word;
}

Connect to SQL Server Database from PowerShell

Integrated Security and User ID \ Password authentication are mutually exclusive. To connect to SQL Server as the user running the code, remove User ID and Password from your connection string:

$SqlConnection.ConnectionString = "Server = $SQLServer; Database = $SQLDBName; Integrated Security = True;"

To connect with specific credentials, remove Integrated Security:

$SqlConnection.ConnectionString = "Server = $SQLServer; Database = $SQLDBName; User ID = $uid; Password = $pwd;"

Delete files older than 3 months old in a directory using .NET

Just create a small delete function which can help you to achieve this task, I have tested this code and it runs perfectly well.

This function deletes files older than 90 days as well as a file with extension .zip to be deleted from a folder.

Private Sub DeleteZip()

    Dim eachFileInMydirectory As New DirectoryInfo("D:\Test\")
    Dim fileName As IO.FileInfo

    Try
        For Each fileName In eachFileInMydirectory.GetFiles
            If fileName.Extension.Equals("*.zip") AndAlso (Now - fileName.CreationTime).Days > 90 Then
                fileName.Delete()
            End If
        Next

    Catch ex As Exception
        WriteToLogFile("No Files older than 90 days exists be deleted " & ex.Message)
    End Try
End Sub

fatal: ambiguous argument 'origin': unknown revision or path not in the working tree

This worked for me on win replace REL_PATH_TO_FILE with the relative path to the file to remove Removing sensitive data from a repository The docs say full path - but that errored for me -so I tried rel path and it worked.

<from the repo dir>git filter-branch --force --index-filter "git rm --cached --ignore-unmatch REL_PATH_TO_FILE" --prune-empty --tag-name-filter cat -- --all

Read input from console in Ruby?

Are you talking about gets?

puts "Enter A"
a = gets.chomp
puts "Enter B"
b = gets.chomp
c = a.to_i + b.to_i
puts c

Something like that?

Update

Kernel.gets tries to read the params found in ARGV and only asks to console if not ARGV found. To force to read from console even if ARGV is not empty use STDIN.gets

How to make VS Code to treat other file extensions as certain language?

Hold down Ctrl+Shift+P (or cmd on Mac), select "Change Language Mode" and there it is.

But I still can't find a way to make VS Code recognized files with specific extension as some certain language.

How to grep with a list of words

To find a very long list of words in big files, it can be more efficient to use egrep:

remove the last \n of A
$ tr '\n' '|' < A > A_regex
$ egrep -f A_regex B

how to automatically scroll down a html page?

You can use two different techniques to achieve this.

The first one is with javascript: set the scrollTop property of the scrollable element (e.g. document.body.scrollTop = 1000;).

The second is setting the link to point to a specific id in the page e.g.

<a href="mypage.html#sectionOne">section one</a>

Then if in your target page you'll have that ID the page will be scrolled automatically.

How to manually install an artifact in Maven 2?

If you ever get similar errors when using Windows PowerShell, you should try Windows' simple command-line. I didn't find out what caused this, but PowerShell seems to interpret some of Maven's parameters.

Compare two dates with JavaScript

Let's suppose that you deal with this 2014[:-/.]06[:-/.]06 or this 06[:-/.]06[:-/.]2014 date format, then you may compare dates this way

var a = '2014.06/07', b = '2014-06.07', c = '07-06/2014', d = '07/06.2014';

parseInt(a.replace(/[:\s\/\.-]/g, '')) == parseInt(b.replace(/[:\s\/\.-]/g, '')); // true
parseInt(c.replace(/[:\s\/\.-]/g, '')) == parseInt(d.replace(/[:\s\/\.-]/g, '')); // true
parseInt(a.replace(/[:\s\/\.-]/g, '')) < parseInt(b.replace(/[:\s\/\.-]/g, '')); // false
parseInt(c.replace(/[:\s\/\.-]/g, '')) > parseInt(d.replace(/[:\s\/\.-]/g, '')); // false

As you can see, we strip separator(s) and then compare integers.

How do you add CSS with Javascript?

You can also do this using DOM Level 2 CSS interfaces (MDN):

var sheet = window.document.styleSheets[0];
sheet.insertRule('strong { color: red; }', sheet.cssRules.length);

...on all but (naturally) IE8 and prior, which uses its own marginally-different wording:

sheet.addRule('strong', 'color: red;', -1);

There is a theoretical advantage in this compared to the createElement-set-innerHTML method, in that you don't have to worry about putting special HTML characters in the innerHTML, but in practice style elements are CDATA in legacy HTML, and ‘<’ and ‘&’ are rarely used in stylesheets anyway.

You do need a stylesheet in place before you can started appending to it like this. That can be any existing active stylesheet: external, embedded or empty, it doesn't matter. If there isn't one, the only standard way to create it at the moment is with createElement.

No grammar constraints (DTD or XML schema) detected for the document

Here's the working solution for this problem:


Step 1: Right click on project and go to properties

Step 2: Go to 'libraries' and remove the project's ' JRE system library'

Step 3: Click on 'Add library'-->'JRE System Library' -->select 'Workspace default JRE'

Step 3: Go to 'Order and Export' and mark the newly added ' JRE system library'

Step 4: Refresh and Clean the project

Eureka! It's working :)

Get first and last day of month using threeten, LocalDate

Just use withDayOfMonth, and lengthOfMonth():

LocalDate initial = LocalDate.of(2014, 2, 13);
LocalDate start = initial.withDayOfMonth(1);
LocalDate end = initial.withDayOfMonth(initial.lengthOfMonth());

How can I style the border and title bar of a window in WPF?

If someone says you can't because only Windows can control the non-client area, they're wrong!

That's just a half-truth because Windows lets you specify the dimensions of the non-client area. The fact is, this is possible only throughout the Windows' kernel methods, and you're in .NET, not C/C++. Anyway, don't worry! P/Invoke was meant just for such things! Indeed, the whole of the Windows Form UI and Console application Std-I/O methods are offered using system calls. Hence, you'd have only to perform the right system calls to set the non-client area up, as documented in MSDN.

However, this is a really hard solution I came up with a lot of time ago. Luckily, as of .NET 4.5, you can use the WindowChrome class to adjust the non-client area like you want. Here you can get to start with.

In order to make things simpler and cleaner, I'll redirect you here, a guide to change the window border dimensions to whatever you want. By setting it to 0, you'll be able to implement your custom window border in place of the system's one.

I'm sorry for not posting a clear example, but later I will for sure.

Make a dictionary with duplicate keys in Python

You can change the behavior of the built in types in Python. For your case it's really easy to create a dict subclass that will store duplicated values in lists under the same key automatically:

class Dictlist(dict):
    def __setitem__(self, key, value):
        try:
            self[key]
        except KeyError:
            super(Dictlist, self).__setitem__(key, [])
        self[key].append(value)

Output example:

>>> d = dictlist.Dictlist()
>>> d['test'] = 1
>>> d['test'] = 2
>>> d['test'] = 3
>>> d
{'test': [1, 2, 3]}
>>> d['other'] = 100
>>> d
{'test': [1, 2, 3], 'other': [100]}

Pass a simple string from controller to a view MVC3

Just define your action method like this

public string ThemePath()

and simply return the string itself.

Python Requests throwing SSLError

I had to upgrade from Python 3.4.0 to 3.4.6

pyenv virtualenv 3.4.6 myvenv
pyenv activate myvenv
pip install -r requirements.txt

How to set the LDFLAGS in CMakeLists.txt?

It depends a bit on what you want:

A) If you want to specify which libraries to link to, you can use find_library to find libs and then use link_directories and target_link_libraries to.

Of course, it is often worth the effort to write a good find_package script, which nicely adds "imported" libraries with add_library( YourLib IMPORTED ) with correct locations, and platform/build specific pre- and suffixes. You can then simply refer to 'YourLib' and use target_link_libraries.

B) If you wish to specify particular linker-flags, e.g. '-mthreads' or '-Wl,--export-all-symbols' with MinGW-GCC, you can use CMAKE_EXE_LINKER_FLAGS. There are also two similar but undocumented flags for modules, shared or static libraries:

CMAKE_MODULE_LINKER_FLAGS
CMAKE_SHARED_LINKER_FLAGS
CMAKE_STATIC_LINKER_FLAGS

How do I escape ampersands in batch files?

You can enclose it in quotes, if you supply a dummy first argument.

Note that you need to supply a dummy first argument in this case, as start will treat the first argument as a title for the new console windows, if it is quoted. So the following should work (and does here):

start "" "http://www.google.com/search?client=opera&rls=en&q=escape+ampersand&sourceid=opera&ie=utf-8&oe=utf-8"

Difference between Xms and Xmx and XX:MaxPermSize

Java objects reside in an area called the heap, while metadata such as class objects and method objects reside in the permanent generation or Perm Gen area. The permanent generation is not part of the heap.

The heap is created when the JVM starts up and may increase or decrease in size while the application runs. When the heap becomes full, garbage is collected. During the garbage collection objects that are no longer used are cleared, thus making space for new objects.

-Xmssize Specifies the initial heap size.

-Xmxsize Specifies the maximum heap size.

-XX:MaxPermSize=size Sets the maximum permanent generation space size. This option was deprecated in JDK 8, and superseded by the -XX:MaxMetaspaceSize option.

Sizes are expressed in bytes. Append the letter k or K to indicate kilobytes, m or M to indicate megabytes, g or G to indicate gigabytes.

References:

How is the java memory pool divided?

What is perm space?

Java (JVM) Memory Model – Memory Management in Java

Java 7 SE Command Line Options

Java 7 HotSpot VM Options

How do I configure different environments in Angular.js?

To achieve that, I suggest you to use AngularJS Environment Plugin: https://www.npmjs.com/package/angular-environment

Here's an example:

angular.module('yourApp', ['environment']).
config(function(envServiceProvider) {
    // set the domains and variables for each environment 
    envServiceProvider.config({
        domains: {
            development: ['localhost', 'dev.local'],
            production: ['acme.com', 'acme.net', 'acme.org']
            // anotherStage: ['domain1', 'domain2'], 
            // anotherStage: ['domain1', 'domain2'] 
        },
        vars: {
            development: {
                apiUrl: '//localhost/api',
                staticUrl: '//localhost/static'
                // antoherCustomVar: 'lorem', 
                // antoherCustomVar: 'ipsum' 
            },
            production: {
                apiUrl: '//api.acme.com/v2',
                staticUrl: '//static.acme.com'
                // antoherCustomVar: 'lorem', 
                // antoherCustomVar: 'ipsum' 
            }
            // anotherStage: { 
            //  customVar: 'lorem', 
            //  customVar: 'ipsum' 
            // } 
        }
    });

    // run the environment check, so the comprobation is made 
    // before controllers and services are built 
    envServiceProvider.check();
});

And then, you can call the variables from your controllers such as this:

envService.read('apiUrl');

Hope it helps.

How to activate virtualenv?

run this code it will get activated if you on a windows machine
source venv/Scripts/activate

enter image description here

loop through json array jquery

You have to parse the string as JSON (data[0] == "[" is an indication that data is actually a string, not an object):

data = $.parseJSON(data);
$.each(data, function(i, item) {
    alert(item);
});

How does Facebook disable the browser's integrated Developer Tools?

Besides redefining console._commandLineAPI, there are some other ways to break into InjectedScriptHost on WebKit browsers, to prevent or alter the evaluation of expressions entered into the developer's console.

Edit:

Chrome has fixed this in a past release. - which must have been before February 2015, as I created the gist at that time

So here's another possibility. This time we hook in, a level above, directly into InjectedScript rather than InjectedScriptHost as opposed to the prior version.

Which is kind of nice, as you can directly monkey patch InjectedScript._evaluateAndWrap instead of having to rely on InjectedScriptHost.evaluate as that gives you more fine-grained control over what should happen.

Another pretty interesting thing is, that we can intercept the internal result when an expression is evaluated and return that to the user instead of the normal behavior.

Here is the code, that does exactly that, return the internal result when a user evaluates something in the console.

var is;
Object.defineProperty(Object.prototype,"_lastResult",{
   get:function(){
       return this._lR;
   },
   set:function(v){
       if (typeof this._commandLineAPIImpl=="object") is=this;
       this._lR=v;
   }
});
setTimeout(function(){
   var ev=is._evaluateAndWrap;
   is._evaluateAndWrap=function(){
       var res=ev.apply(is,arguments);
       console.log();
       if (arguments[2]==="completion") {
           //This is the path you end up when a user types in the console and autocompletion get's evaluated

           //Chrome expects a wrapped result to be returned from evaluateAndWrap.
           //You can use `ev` to generate an object yourself.
           //In case of the autocompletion chrome exptects an wrapped object with the properties that can be autocompleted. e.g.;
           //{iGetAutoCompleted: true}
           //You would then go and return that object wrapped, like
           //return ev.call (is, '', '({test:true})', 'completion', true, false, true);
           //Would make `test` pop up for every autocompletion.
           //Note that syntax as well as every Object.prototype property get's added to that list later,
           //so you won't be able to exclude things like `while` from the autocompletion list,
           //unless you wou'd find a way to rewrite the getCompletions function.
           //
           return res; //Return the autocompletion result. If you want to break that, return nothing or an empty object
       } else {
           //This is the path where you end up when a user actually presses enter to evaluate an expression.
           //In order to return anything as normal evaluation output, you have to return a wrapped object.

           //In this case, we want to return the generated remote object. 
           //Since this is already a wrapped object it would be converted if we directly return it. Hence,
           //`return result` would actually replicate the very normal behaviour as the result is converted.
           //to output what's actually in the remote object, we have to stringify it and `evaluateAndWrap` that object again.`
           //This is quite interesting;
           return ev.call (is, null, '(' + JSON.stringify (res) + ')', "console", true, false, true)
       }
   };
},0);

It's a bit verbose, but I thought I put some comments into it

So normally, if a user, for example, evaluates [1,2,3,4] you'd expect the following output:

enter image description here

After monkeypatching InjectedScript._evaluateAndWrap evaluating the very same expression, gives the following output:

enter image description here

As you see the little-left arrow, indicating output, is still there, but this time we get an object. Where the result of the expression, the array [1,2,3,4] is represented as an object with all its properties described.

I recommend trying to evaluate this and that expression, including those that generate errors. It's quite interesting.

Additionally, take a look at the is - InjectedScriptHost - object. It provides some methods to play with and get a bit of insight into the internals of the inspector.

Of course, you could intercept all that information and still return the original result to the user.

Just replace the return statement in the else path by a console.log (res) following a return res. Then you'd end up with the following.

enter image description here

End of Edit


This is the prior version which was fixed by Google. Hence not a possible way anymore.

One of it is hooking into Function.prototype.call

Chrome evaluates the entered expression by calling its eval function with InjectedScriptHost as thisArg

var result = evalFunction.call(object, expression);

Given this, you can listen for the thisArg of call being evaluate and get a reference to the first argument (InjectedScriptHost)

if (window.URL) {
    var ish, _call = Function.prototype.call;
    Function.prototype.call = function () { //Could be wrapped in a setter for _commandLineAPI, to redefine only when the user started typing.
        if (arguments.length > 0 && this.name === "evaluate" && arguments [0].constructor.name === "InjectedScriptHost") { //If thisArg is the evaluate function and the arg0 is the ISH
            ish = arguments[0];
            ish.evaluate = function (e) { //Redefine the evaluation behaviour
                throw new Error ('Rejected evaluation of: \n\'' + e.split ('\n').slice(1,-1).join ("\n") + '\'');
            };
            Function.prototype.call = _call; //Reset the Function.prototype.call
            return _call.apply(this, arguments);  
        }
    };
}

You could e.g. throw an error, that the evaluation was rejected.

enter image description here

Here is an example where the entered expression gets passed to a CoffeeScript compiler before passing it to the evaluate function.

How to compare each item in a list with the rest, only once?

This code will count frequency and remove duplicate elements:

from collections import Counter

str1='the cat sat on the hat hat'

int_list=str1.split();

unique_list = []
for el in int_list:

    if el not in unique_list:
        unique_list.append(el)
    else:
        print "Element already in the list"

print unique_list

c=Counter(int_list)

c.values()

c.keys()

print c

The right way of setting <a href=""> when it's a local file

Try swapping your colon : for a bar |. that should do it

<a href="file://C|/path/to/file/file.html">Link Anchor</a>

Causes of getting a java.lang.VerifyError

In my case I had to remove this block:

compileOptions {
    sourceCompatibility JavaVersion.VERSION_1_7
    targetCompatibility JavaVersion.VERSION_1_7
}

It was showing error near Fragment.showDialog() method call.

php var_dump() vs print_r()

Generally, print_r( ) output is nicer, more concise and easier to read, aka more human-readable but cannot show data types.

With print_r() you can also store the output into a variable:

$output = print_r($array, true);

which var_dump() cannot do. Yet var_dump() can show data types.

Converting string format to datetime in mm/dd/yyyy

The following works for me.

string strToday = DateTime.Today.ToString("MM/dd/yyyy");

415 Unsupported Media Type - POST json to OData service in lightswitch 2012

It looks like this issue has to do with the difference between the Content-Type and Accept headers. In HTTP, Content-Type is used in request and response payloads to convey the media type of the current payload. Accept is used in request payloads to say what media types the server may use in the response payload.

So, having a Content-Type in a request without a body (like your GET request) has no meaning. When you do a POST request, you are sending a message body, so the Content-Type does matter.

If a server is not able to process the Content-Type of the request, it will return a 415 HTTP error. (If a server is not able to satisfy any of the media types in the request Accept header, it will return a 406 error.)

In OData v3, the media type "application/json" is interpreted to mean the new JSON format ("JSON light"). If the server does not support reading JSON light, it will throw a 415 error when it sees that the incoming request is JSON light. In your payload, your request body is verbose JSON, not JSON light, so the server should be able to process your request. It just doesn't because it sees the JSON light content type.

You could fix this in one of two ways:

  1. Make the Content-Type "application/json;odata=verbose" in your POST request, or
  2. Include the DataServiceVersion header in the request and set it be less than v3. For example:

    DataServiceVersion: 2.0;
    

(Option 2 assumes that you aren't using any v3 features in your request payload.)

Insert a line break in mailto body

<a href="mailto:[email protected]?subject=Request&body=Hi,%0DName:[your name] %0DGood day " target="_blank"></a>

Try adding %0D to break the line. This will definitely work.

Above code will display the following:

Hi,
Name:[your name] 
Good day