Programs & Examples On #Fslex

Fslex is a F# variant of lex, a program that generates lexical analyzers ("scanners" or "lexers"). Fslex is commonly used with fsyacc, the parser generator.

URL to compose a message in Gmail (with full Gmail interface and specified to, bcc, subject, etc.)

It's worth pointing out that if you have multiple Gmail accounts, you may want to use the URL approach because you can customize which account to compose from.

e.g.

https://mail.google.com/mail/u/0/#inbox?compose=new   
https://mail.google.com/mail/u/1/#inbox?compose=new

Or if you know the email address you are sending from, replace the numeric index with the email address:

https://mail.google.com/mail/u/[email protected]/#inbox?compose=new

What equivalents are there to TortoiseSVN, on Mac OSX?

I use svnX (http://code.google.com/p/svnx/downloads/list), it is free and usable, but not as user friendly as tortoise. It shows you the review before commit with diff for every file... but sometimes I still had to go to command line to fix some things

UML class diagram enum

Typically you model the enum itself as a class with the enum stereotype

Create a .tar.bz2 file Linux

Try this from different folder:

sudo tar -cvjSf folder.tar.bz2 folder/*

how to pass this element to javascript onclick function and add a class to that clicked element

<div class="row" style="padding-left:21px;">
    <ul class="nav nav-tabs" style="padding-left:40px;">
        <li class="active filter"><a href="#month" onclick="Data(this)">This Month</a></li>
        <li class="filter"><a href="#year" onclick="Data(this)">Year</a></li>
        <li class="filter"><a href="#last60" onclick="Data(this)">60 Days</a></li>
        <li class="filter"><a href="#last90" onclick="Data(this)">90 Days</a></li>
    </ul>

</div>

<script>
    function Data(element)
    {     
       element.removeClass('active');
       element.addClass('active') ;
    }
</script>

Alter a MySQL column to be AUTO_INCREMENT

Below statement works. Note that you need to mention the data type again for the column name (redeclare the data type the column was before).

ALTER TABLE document
MODIFY COLUMN document_id int AUTO_INCREMENT;

How to use setInterval and clearInterval?

I used angular with electron,

In my case, setInterval returns a Nodejs Timer object. which when I called clearInterval(timerobject) it did not work.

I had to get the id first and call to clearInterval

clearInterval(timerobject._id)

I have struggled many hours with this. hope this helps.

How to change Bootstrap's global default font size?

Add !importent in your css

* {
   font-size: 16px !importent;
   line-height: 2;
}

how to remove empty strings from list, then remove duplicate values from a list

Amiram Korach solution is indeed tidy. Here's an alternative for the sake of versatility.

var count = dtList.Count;
// Perform a reverse tracking.
for (var i = count - 1; i > -1; i--)
{
    if (dtList[i]==string.Empty) dtList.RemoveAt(i);
}
// Keep only the unique list items.
dtList = dtList.Distinct().ToList();

"TypeError: (Integer) is not JSON serializable" when serializing JSON in Python?

You have Numpy Data Type, Just change to normal int() or float() data type. it will work fine.

How do I do logging in C# without using 3rd party libraries?

public void Logger(string lines)
{
  //Write the string to a file.append mode is enabled so that the log
  //lines get appended to  test.txt than wiping content and writing the log

  using(System.IO.StreamWriter file = new System.IO.StreamWriter("c:\\test.txt", true))
  {
    file.WriteLine(lines);
  }
}

For more information MSDN

TypeScript: Interfaces vs Types


When to use type?


Generic Transformations

Use the type when you are transforming multiple types into a single generic type.

Example:

type Nullable<T> = T | null | undefined
type NonNull<T> = T extends (null | undefined) ? never : T

Type Aliasing

We can use the type for creating the aliases for long or complicated types that are hard to read as well as inconvenient to type again and again.

Example:

type Primitive = number | string | boolean | null | undefined

Creating an alias like this makes the code more concise and readable.


Type Capturing

Use the type to capture the type of an object when the type is unknown.

Example:

const orange = { color: "Orange", vitamin: "C"}
type Fruit = typeof orange
let apple: Fruit

Here, we get the unknown type of orange, call it a Fruit and then use the Fruit to create a new type-safe object apple.


When to use interface?


Polymorphism

An interface is a contract to implement a shape of the data. Use the interface to make it clear that it is intended to be implemented and used as a contract about how the object will be used.

Example:

interface Bird {
    size: number
    fly(): void
    sleep(): void
}

class Hummingbird implements Bird { ... }
class Bellbird implements Bird { ... }

Though you can use the type to achieve this, the Typescript is seen more as an object oriented language and the interface has a special place in object oriented languages. It's easier to read the code with interface when you are working in a team environment or contributing to the open source community. It's easy on the new programmers coming from the other object oriented languages too.

The official Typescript documentation also says:

... we recommend using an interface over a type alias when possible.

This also suggests that the type is more intended for creating type aliases than creating the types themselves.


Declaration Merging

You can use the declaration merging feature of the interface for adding new properties and methods to an already declared interface. This is useful for the ambient type declarations of third party libraries. When some declarations are missing for a third party library, you can declare the interface again with the same name and add new properties and methods.

Example:

We can extend the above Bird interface to include new declarations.

interface Bird {
    color: string
    eat(): void
}

That's it! It's easier to remember when to use what than getting lost in subtle differences between the two.

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

It's interesting things with IDE (IntelliJ in this case):

  • if you leave default, i.e. don't declare spring-boot-starter-tomcat as provided, a spring-boot-maven-plugin (SBMP) put tomcat's jars to your war -> and you'll probably get errors deploying this war to container (there could be a versions conflict)

  • else you'll get classpath with no compile dependency on tomcat-embed (SBMP will build executable war/jar with provided deps included anyway)

    • intelliJ honestly doesn't see provided deps at runtime (they are not in classpath) when you run its Spring Boot run configuration.
    • and with no tomcat-embed you can't run Spring-Boot with embedded servlet container.

There is some tricky workaround: put Tomcat's jars to classpath of your idea-module via UI: File->Project Structure->(Libraries or Modules/Dependencies tab) .

  • tomcat-embed-core
  • tomcat-embed-el
  • tomcat-embed-websocket
  • tomcat-embed-logging-juli

Better solution for maven case

Instead of adding module dependencies in Idea, it is better to declare maven profile with compile scope of spring-boot-starter-tomcat library.

<profiles>
    <profile>
        <id>embed-tomcat</id>
        <dependencies>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-tomcat</artifactId>
                <scope>compile</scope>
            </dependency>
        </dependencies>
    </profile>
</profiles>

while spring-boot-starter-tomcat was declared provided in <dependencies/>, making this profile active in IDE or CLI (mvn -Pembed-tomcat ...) allow you to launch build with embedded tomcat.

How to indent HTML tags in Notepad++

In Notepad++ v7.8.9 you can use the Tab key to increase the indention level, and use Shift + Tab to decrease the indentation level.

How to tell if JRE or JDK is installed

@maciej-cygan described the process well, however in order to find your java path:

$ which java

it gives you the path of java binary file which is a linked file in /usr/bin directory. next:

$ cd /usr/bin/ && ls -la | grep java

find the pointed location which is something as follows (for me):

enter image description here then cd to the pointed directory to find the real home directory for Java. next:

$ ls -la | grep java

which is as follows in this case:

enter image description here

so as it's obvious in the screenshot, my Java home directory is /usr/lib/jvm/java-11-openjdk-amd64. So accordingly I need to add JAVA_HOME to my bash profile (.bashrc, .bash_profile, etc. depending on your OS) like below:

JAVA_HOME="/usr/lib/jvm/java-11-openjdk-amd64"

Here you go!

What is the difference between <%, <%=, <%# and -%> in ERB in Rails?

<% %> and <%- and -%> are for any Ruby code, but doesn't output the results (e.g. if statements). the two are the same.

<%= %> is for outputting the results of Ruby code

<%# %> is an ERB comment

Here's a good guide: http://api.rubyonrails.org/classes/ActionView/Base.html

How to test the `Mosquitto` server?

If you are using Windows, open up a command prompt and type 'netstat -an'.

If your server is running, you should be able to see the port 1883.

cmd displaying mosquitto port

If you cannot go to Task Manager > Services and start/restart the Mosquitto server from there. If you cannot find it here too, your installation of Mosquitto has not been successful.

A more detailed tutorial for setting up Mosquitto with Windows / is linked here.

Change Timezone in Lumen or Laravel 5

Go to config -> app.php and change 'timezone' => 'Asia/Jakarta',

(this is my timezone)

ModuleNotFoundError: No module named 'sklearn'

Cause

Conda and pip install scikit-learn under ~/anaconda3/envs/$ENV/lib/python3.7/site-packages, however Jupyter notebook looks for the package under ~/anaconda3/lib/python3.7/site-packages.

Therefore, even when the environment is specified to conda, it does not work.

conda install -n $ENV scikit-learn # Does not work

Solution

pip 3 install the package under ~/anaconda3/lib/python3.7/site-packages.

Verify

After pip3, in a Jupyter notebook.

import sklearn
sklearn.__file__

~/anaconda3/lib/python3.7/site-packages/sklearn/init.py'

How to Display Multiple Google Maps per page with API V3

You haven't defined a div with id="map_canvas", you only have id="map_canvas2" and id="route2". The div ids need to match the argument in the GMap() constructor.

What are these ^M's that keep showing up in my files in emacs?

I'm using Android Studio (JetBrains IntelliJ IDEA) on Mac OS and my problem was that ^M started to show up in some files in my pull request on GitHub. What worked for me was changing line separator for a file.

Open the desired file in the editor go to File go to Line Separators then choose the best option for you (for me it was LF - Unix and OS X(\n) )

According to the next article this problem is a result of confused line endings between operating systems: http://jonathonstaff.com/blog/issues-with-line-endings/

And more information you can find here: https://www.jetbrains.com/help/idea/configuring-line-separators.html#d84378e48

enter image description here

How to create a cron job using Bash automatically without the interactive editor?

A variant which only edits crontab if the desired string is not found there:

CMD="/sbin/modprobe fcpci"
JOB="@reboot $CMD"
TMPC="mycron"
grep "$CMD" -q <(crontab -l) || (crontab -l>"$TMPC"; echo "$JOB">>"$TMPC"; crontab "$TMPC")

calling a java servlet from javascript

Sorry, I read jsp not javascript. You need to do something like (note that this is a relative url and may be different depending on the url of the document this javascript is in):

document.location = 'path/to/servlet';

Where your servlet-mapping in web.xml looks something like this:

<servlet-mapping>
    <servlet-name>someServlet</servlet-name>
    <url-pattern>/path/to/servlet*</url-pattern>
</servlet-mapping>

jQuery Ajax error handling, show custom exception messages

_x000D_
_x000D_
 error:function (xhr, ajaxOptions, thrownError) {_x000D_
        alert(xhr.status);_x000D_
        alert(thrownError);_x000D_
      }
_x000D_
_x000D_
_x000D_ in code error ajax request for catch error connect between client to server if you want show error message of your application send in success scope

such as

_x000D_
_x000D_
success: function(data){_x000D_
   //   data is object  send  form server _x000D_
   //   property of data _x000D_
   //   status  type boolean _x000D_
   //   msg     type string_x000D_
   //   result  type string_x000D_
  if(data.status){ // true  not error _x000D_
         $('#api_text').val(data.result);_x000D_
  }_x000D_
  else _x000D_
  {_x000D_
      $('#error_text').val(data.msg);_x000D_
  }_x000D_
_x000D_
}
_x000D_
_x000D_
_x000D_

Assign one struct to another in C

Yes, assignment is supported for structs. However, there are problems:

struct S {
   char * p;
};

struct S s1, s2;
s1.p = malloc(100);
s2 = s1;

Now the pointers of both structs point to the same block of memory - the compiler does not copy the pointed to data. It is now difficult to know which struct instance owns the data. This is why C++ invented the concept of user-definable assignment operators - you can write specific code to handle this case.

How to redirect to a different domain using NGINX?

Temporary redirect

rewrite ^ http://www.RedirectToThisDomain.com$request_uri? redirect;

Permanent redirect

rewrite ^ http://www.RedirectToThisDomain.com$request_uri? permanent;

In nginx configuration file for specific site:

server {    
    server_name www.example.com;
    rewrite ^ http://www.RedictToThisDomain.com$request_uri? redirect;

}

Is there a mechanism to loop x times in ES6 (ECMAScript 6) without mutable variables?

OK!

The code below is written using ES6 syntaxes but could just as easily be written in ES5 or even less. ES6 is not a requirement to create a "mechanism to loop x times"


If you don't need the iterator in the callback, this is the most simple implementation

_x000D_
_x000D_
const times = x => f => {_x000D_
  if (x > 0) {_x000D_
    f()_x000D_
    times (x - 1) (f)_x000D_
  }_x000D_
}_x000D_
_x000D_
// use it_x000D_
times (3) (() => console.log('hi'))_x000D_
_x000D_
// or define intermediate functions for reuse_x000D_
let twice = times (2)_x000D_
_x000D_
// twice the power !_x000D_
twice (() => console.log('double vision'))
_x000D_
_x000D_
_x000D_

If you do need the iterator, you can use a named inner function with a counter parameter to iterate for you

_x000D_
_x000D_
const times = n => f => {_x000D_
  let iter = i => {_x000D_
    if (i === n) return_x000D_
    f (i)_x000D_
    iter (i + 1)_x000D_
  }_x000D_
  return iter (0)_x000D_
}_x000D_
_x000D_
times (3) (i => console.log(i, 'hi'))
_x000D_
_x000D_
_x000D_


Stop reading here if you don't like learning more things ...

But something should feel off about those...

  • single branch if statements are ugly — what happens on the other branch ?
  • multiple statements/expressions in the function bodies — are procedure concerns being mixed ?
  • implicitly returned undefined — indication of impure, side-effecting function

"Isn't there a better way ?"

There is. Let's first revisit our initial implementation

// times :: Int -> (void -> void) -> void
const times = x => f => {
  if (x > 0) {
    f()               // has to be side-effecting function
    times (x - 1) (f)
  }
}

Sure, it's simple, but notice how we just call f() and don't do anything with it. This really limits the type of function we can repeat multiple times. Even if we have the iterator available, f(i) isn't much more versatile.

What if we start with a better kind of function repetition procedure ? Maybe something that makes better use of input and output.

Generic function repetition

_x000D_
_x000D_
// repeat :: forall a. Int -> (a -> a) -> a -> a_x000D_
const repeat = n => f => x => {_x000D_
  if (n > 0)_x000D_
    return repeat (n - 1) (f) (f (x))_x000D_
  else_x000D_
    return x_x000D_
}_x000D_
_x000D_
// power :: Int -> Int -> Int_x000D_
const power = base => exp => {_x000D_
  // repeat <exp> times, <base> * <x>, starting with 1_x000D_
  return repeat (exp) (x => base * x) (1)_x000D_
}_x000D_
_x000D_
console.log(power (2) (8))_x000D_
// => 256
_x000D_
_x000D_
_x000D_

Above, we defined a generic repeat function which takes an additional input which is used to start the repeated application of a single function.

// repeat 3 times, the function f, starting with x ...
var result = repeat (3) (f) (x)

// is the same as ...
var result = f(f(f(x)))

Implementing times with repeat

Well this is easy now; almost all of the work is already done.

_x000D_
_x000D_
// repeat :: forall a. Int -> (a -> a) -> a -> a_x000D_
const repeat = n => f => x => {_x000D_
  if (n > 0)_x000D_
    return repeat (n - 1) (f) (f (x))_x000D_
  else_x000D_
    return x_x000D_
}_x000D_
_x000D_
// times :: Int -> (Int -> Int) -> Int _x000D_
const times = n=> f=>_x000D_
  repeat (n) (i => (f(i), i + 1)) (0)_x000D_
_x000D_
// use it_x000D_
times (3) (i => console.log(i, 'hi'))
_x000D_
_x000D_
_x000D_

Since our function takes i as an input and returns i + 1, this effectively works as our iterator which we pass to f each time.

We've fixed our bullet list of issues too

  • No more ugly single branch if statements
  • Single-expression bodies indicate nicely separated concerns
  • No more useless, implicitly returned undefined

JavaScript comma operator, the

In case you're having trouble seeing how the last example is working, it depends on your awareness of one of JavaScript's oldest battle axes; the comma operator – in short, it evaluates expressions from left to right and returns the value of the last evaluated expression

(expr1 :: a, expr2 :: b, expr3 :: c) :: c

In our above example, I'm using

(i => (f(i), i + 1))

which is just a succinct way of writing

(i => { f(i); return i + 1 })

Tail Call Optimisation

As sexy as the recursive implementations are, at this point it would be irresponsible for me to recommend them given that no JavaScript VM I can think of supports proper tail call elimination – babel used to transpile it, but it's been in "broken; will reimplement" status for well over a year.

repeat (1e6) (someFunc) (x)
// => RangeError: Maximum call stack size exceeded

As such, we should revisit our implementation of repeat to make it stack-safe.

The code below does use mutable variables n and x but note that all mutations are localized to the repeat function – no state changes (mutations) are visible from outside of the function

_x000D_
_x000D_
// repeat :: Int -> (a -> a) -> (a -> a)_x000D_
const repeat = n => f => x =>_x000D_
  {_x000D_
    let m = 0, acc = x_x000D_
    while (m < n)_x000D_
      (m = m + 1, acc = f (acc))_x000D_
    return acc_x000D_
  }_x000D_
_x000D_
// inc :: Int -> Int_x000D_
const inc = x =>_x000D_
  x + 1_x000D_
_x000D_
console.log (repeat (1e8) (inc) (0))_x000D_
// 100000000
_x000D_
_x000D_
_x000D_

This is going to have a lot of you saying "but that's not functional !" – I know, just relax. We can implement a Clojure-style loop/recur interface for constant-space looping using pure expressions; none of that while stuff.

Here we abstract while away with our loop function – it looks for a special recur type to keep the loop running. When a non-recur type is encountered, the loop is finished and the result of the computation is returned

_x000D_
_x000D_
const recur = (...args) =>_x000D_
  ({ type: recur, args })_x000D_
  _x000D_
const loop = f =>_x000D_
  {_x000D_
    let acc = f ()_x000D_
    while (acc.type === recur)_x000D_
      acc = f (...acc.args)_x000D_
    return acc_x000D_
  }_x000D_
_x000D_
const repeat = $n => f => x =>_x000D_
  loop ((n = $n, acc = x) =>_x000D_
    n === 0_x000D_
      ? acc_x000D_
      : recur (n - 1, f (acc)))_x000D_
      _x000D_
const inc = x =>_x000D_
  x + 1_x000D_
_x000D_
const fibonacci = $n =>_x000D_
  loop ((n = $n, a = 0, b = 1) =>_x000D_
    n === 0_x000D_
      ? a_x000D_
      : recur (n - 1, b, a + b))_x000D_
      _x000D_
console.log (repeat (1e7) (inc) (0)) // 10000000_x000D_
console.log (fibonacci (100))        // 354224848179262000000
_x000D_
_x000D_
_x000D_

How to change ViewPager's page?

Without checking your code, I think what you are describing is that your pages are out of sync and you have stale data.

You say you are changing the number of pages, then crashing because you are accessing the old set of pages. This sounds to me like you are not calling pageAdapter.notifyDataSetChanged() after changing your data.

When your viewPager is showing page 3 of a set of 10 pages, and you change to a set with only 5, then call notifyDataSetChanged(), what you'll find is you are now viewing page 3 of the new set. If you were previously viewing page 8 of the old set, after putting in the new set and calling notifyDataSetChanged() you will find you are now viewing the last page of the new set without crashing.

If you simply change your current page, you may just be masking the problem.

Controller 'ngModel', required by directive '...', can't be found

I faced the same error, in my case I miss-spelled ng-model directive something like "ng-moel"

Wrong one: ng-moel="user.name" Right one: ng-model="user.name"

enter image description here

Export to csv in jQuery

I recently posted a free software library for this: "html5csv.js" -- GitHub

It is intended to help streamline the creation of small simulator apps in Javascript that might need to import or export csv files, manipulate, display, edit the data, perform various mathematical procedures like fitting, etc.

After loading "html5csv.js" the problem of scanning a table and creating a CSV is a one-liner:

CSV.begin('#PrintDiv').download('MyData.csv').go();

Here is a JSFiddle demo of your example with this code.

Internally, for Firefox/Chrome this is a data URL oriented solution, similar to that proposed by @italo, @lepe, and @adeneo (on another question). For IE

The CSV.begin() call sets up the system to read the data into an internal array. That fetch then occurs. Then the .download() generates a data URL link internally and clicks it with a link-clicker. This pushes a file to the end user.

According to caniuse IE10 doesn't support <a download=...>. So for IE my library calls navigator.msSaveBlob() internally, as suggested by @Manu Sharma

Why my $.ajax showing "preflight is invalid redirect error"?

I had the same error, though the problem was that I had a typo in the url

url: 'http://api.example.com/TYPO'

The API had a redirect to another domain for all URL's that is wrong (404 errors).

So fixing the typo to the correct URL fixed it for me.

Python's time.clock() vs. time.time() accuracy?

Depends on what you care about. If you mean WALL TIME (as in, the time on the clock on your wall), time.clock() provides NO accuracy because it may manage CPU time.

Pandas: drop a level from a multi-level column index?

I have struggled with this problem since I don’t know why my droplevel() function does not work. Work through several and learn that ‘a’ in your table is columns name and ‘b’, ‘c’ are index. Do like this will help

df.columns.name = None
df.reset_index() #make index become label

How to Cast Objects in PHP

class It {
    public $a = '';

    public function __construct($a) {
        $this->a = $a;
    }
    public function printIt() {
        ;
    }
}

//contains static function to 'convert' instance of parent It to sub-class instance of Thing

class Thing extends it {
    public $b = '';

    public function __construct($a, $b) {
        $this->a = $a;
        $this->b = $b;
    }
    public function printThing() {
        echo $this->a . $this->b;
    }
        //static function housed by target class since trying to create an instance of Thing
    static function thingFromIt(It $it, $b) {
        return new Thing($it->a, $b);
    }
}


//create an instance of It
$it = new It('1');

//create an instance of Thing 
$thing = Thing::thingFromIt($it, '2');


echo 'Class for $it: ' . get_class($it);
echo 'Class for $thing: ' . get_class($thing);

Returns:

Class for $it: It
Class for $thing: Thing

How can I add a table of contents to a Jupyter / JupyterLab notebook?

Here is my approach, clunky as it is and available in github:

Put in the very first notebook cell, the import cell:

from IPythonTOC import IPythonTOC

toc = IPythonTOC()

Somewhere after the import cell, put in the genTOCEntry cell but don't run it yet:

''' if you called toc.genTOCMarkdownCell before running this cell, 
the title has been set in the class '''

print toc.genTOCEntry()

Below the genTOCEntry cell`, make a TOC cell as a markdown cell:

<a id='TOC'></a>

#TOC

As the notebook is developed, put this genTOCMarkdownCell before starting a new section:

with open('TOCMarkdownCell.txt', 'w') as outfile:

    outfile.write(toc.genTOCMarkdownCell('Introduction'))

!cat TOCMarkdownCell.txt

!rm TOCMarkdownCell.txt

Move the genTOCMarkdownCell down to the point in your notebook where you want to start a new section and make the argument to genTOCMarkdownCell the string title for your new section then run it. Add a markdown cell right after it and copy the output from genTOCMarkdownCell into the markdown cell that starts your new section. Then go to the genTOCEntry cell near the top of your notebook and run it. For example, if you make the argument to genTOCMarkdownCell as shown above and run it, you get this output to paste into the first markdown cell of your newly indexed section:

<a id='Introduction'></a>

###Introduction

Then when you go to the top of your notebook and run genTocEntry, you get the output:

[Introduction](#Introduction)

Copy this link string and paste it into the TOC markdown cell as follows:

<a id='TOC'></a>

#TOC

[Introduction](#Introduction)

After you edit the TOC cell to insert the link string and then you press shift-enter, the link to your new section will appear in your notebook Table of Contents as a web link and clicking it will position the browser to your new section.

One thing I often forget is that clicking a line in the TOC makes the browser jump to that cell but doesn't select it. Whatever cell was active when we clicked on the TOC link is still active, so a down or up arrow or shift-enter refers to still active cell, not the cell we got by clicking on the TOC link.

Setting focus to iframe contents

Try listening for events in the parent document and passing the event to a handler in the iframe document.

Why does make think the target is up to date?

It happens when you have a file with the same name as Makefile target name in the directory where the Makefile is present.

enter image description here

Explain ggplot2 warning: "Removed k rows containing missing values"

Just for the shake of completing the answer given by eipi10.

I was facing the same problem, without using scale_y_continuous nor coord_cartesian.

The conflict was coming from the x axis, where I defined limits = c(1, 30). It seems such limits do not provide enough space if you want to "dodge" your bars, so R still throws the error

Removed 8 rows containing missing values (geom_bar)

Adjusting the limits of the x axis to limits = c(0, 31) solved the problem.

In conclusion, even if you are not putting limits to your y axis, check out your x axis' behavior to ensure you have enough space

What is the best regular expression to check if a string is a valid URL?

I wrote my URL (actually IRI, internationalized) pattern to comply with RFC 3987 (http://www.faqs.org/rfcs/rfc3987.html). These are in PCRE syntax.

For absolute IRIs (internationalized):

/^[a-z](?:[-a-z0-9\+\.])*:(?:\/\/(?:(?:%[0-9a-f][0-9a-f]|[-a-z0-9\._~\x{A0}-\x{D7FF}\x{F900}-\x{FDCF}\x{FDF0}-\x{FFEF}\x{10000}-\x{1FFFD}\x{20000}-\x{2FFFD}\x{30000}-\x{3FFFD}\x{40000}-\x{4FFFD}\x{50000}-\x{5FFFD}\x{60000}-\x{6FFFD}\x{70000}-\x{7FFFD}\x{80000}-\x{8FFFD}\x{90000}-\x{9FFFD}\x{A0000}-\x{AFFFD}\x{B0000}-\x{BFFFD}\x{C0000}-\x{CFFFD}\x{D0000}-\x{DFFFD}\x{E1000}-\x{EFFFD}!\$&'\(\)\*\+,;=:])*@)?(?:\[(?:(?:(?:[0-9a-f]{1,4}:){6}(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(?:\.(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3})|::(?:[0-9a-f]{1,4}:){5}(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(?:\.(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3})|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(?:\.(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3})|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(?:\.(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3})|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(?:\.(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3})|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(?:\.(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3})|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(?:\.(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3})|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|v[0-9a-f]+\.[-a-z0-9\._~!\$&'\(\)\*\+,;=:]+)\]|(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(?:\.(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3}|(?:%[0-9a-f][0-9a-f]|[-a-z0-9\._~\x{A0}-\x{D7FF}\x{F900}-\x{FDCF}\x{FDF0}-\x{FFEF}\x{10000}-\x{1FFFD}\x{20000}-\x{2FFFD}\x{30000}-\x{3FFFD}\x{40000}-\x{4FFFD}\x{50000}-\x{5FFFD}\x{60000}-\x{6FFFD}\x{70000}-\x{7FFFD}\x{80000}-\x{8FFFD}\x{90000}-\x{9FFFD}\x{A0000}-\x{AFFFD}\x{B0000}-\x{BFFFD}\x{C0000}-\x{CFFFD}\x{D0000}-\x{DFFFD}\x{E1000}-\x{EFFFD}!\$&'\(\)\*\+,;=])*)(?::[0-9]*)?(?:\/(?:(?:%[0-9a-f][0-9a-f]|[-a-z0-9\._~\x{A0}-\x{D7FF}\x{F900}-\x{FDCF}\x{FDF0}-\x{FFEF}\x{10000}-\x{1FFFD}\x{20000}-\x{2FFFD}\x{30000}-\x{3FFFD}\x{40000}-\x{4FFFD}\x{50000}-\x{5FFFD}\x{60000}-\x{6FFFD}\x{70000}-\x{7FFFD}\x{80000}-\x{8FFFD}\x{90000}-\x{9FFFD}\x{A0000}-\x{AFFFD}\x{B0000}-\x{BFFFD}\x{C0000}-\x{CFFFD}\x{D0000}-\x{DFFFD}\x{E1000}-\x{EFFFD}!\$&'\(\)\*\+,;=:@]))*)*|\/(?:(?:(?:(?:%[0-9a-f][0-9a-f]|[-a-z0-9\._~\x{A0}-\x{D7FF}\x{F900}-\x{FDCF}\x{FDF0}-\x{FFEF}\x{10000}-\x{1FFFD}\x{20000}-\x{2FFFD}\x{30000}-\x{3FFFD}\x{40000}-\x{4FFFD}\x{50000}-\x{5FFFD}\x{60000}-\x{6FFFD}\x{70000}-\x{7FFFD}\x{80000}-\x{8FFFD}\x{90000}-\x{9FFFD}\x{A0000}-\x{AFFFD}\x{B0000}-\x{BFFFD}\x{C0000}-\x{CFFFD}\x{D0000}-\x{DFFFD}\x{E1000}-\x{EFFFD}!\$&'\(\)\*\+,;=:@]))+)(?:\/(?:(?:%[0-9a-f][0-9a-f]|[-a-z0-9\._~\x{A0}-\x{D7FF}\x{F900}-\x{FDCF}\x{FDF0}-\x{FFEF}\x{10000}-\x{1FFFD}\x{20000}-\x{2FFFD}\x{30000}-\x{3FFFD}\x{40000}-\x{4FFFD}\x{50000}-\x{5FFFD}\x{60000}-\x{6FFFD}\x{70000}-\x{7FFFD}\x{80000}-\x{8FFFD}\x{90000}-\x{9FFFD}\x{A0000}-\x{AFFFD}\x{B0000}-\x{BFFFD}\x{C0000}-\x{CFFFD}\x{D0000}-\x{DFFFD}\x{E1000}-\x{EFFFD}!\$&'\(\)\*\+,;=:@]))*)*)?|(?:(?:(?:%[0-9a-f][0-9a-f]|[-a-z0-9\._~\x{A0}-\x{D7FF}\x{F900}-\x{FDCF}\x{FDF0}-\x{FFEF}\x{10000}-\x{1FFFD}\x{20000}-\x{2FFFD}\x{30000}-\x{3FFFD}\x{40000}-\x{4FFFD}\x{50000}-\x{5FFFD}\x{60000}-\x{6FFFD}\x{70000}-\x{7FFFD}\x{80000}-\x{8FFFD}\x{90000}-\x{9FFFD}\x{A0000}-\x{AFFFD}\x{B0000}-\x{BFFFD}\x{C0000}-\x{CFFFD}\x{D0000}-\x{DFFFD}\x{E1000}-\x{EFFFD}!\$&'\(\)\*\+,;=:@]))+)(?:\/(?:(?:%[0-9a-f][0-9a-f]|[-a-z0-9\._~\x{A0}-\x{D7FF}\x{F900}-\x{FDCF}\x{FDF0}-\x{FFEF}\x{10000}-\x{1FFFD}\x{20000}-\x{2FFFD}\x{30000}-\x{3FFFD}\x{40000}-\x{4FFFD}\x{50000}-\x{5FFFD}\x{60000}-\x{6FFFD}\x{70000}-\x{7FFFD}\x{80000}-\x{8FFFD}\x{90000}-\x{9FFFD}\x{A0000}-\x{AFFFD}\x{B0000}-\x{BFFFD}\x{C0000}-\x{CFFFD}\x{D0000}-\x{DFFFD}\x{E1000}-\x{EFFFD}!\$&'\(\)\*\+,;=:@]))*)*|(?!(?:%[0-9a-f][0-9a-f]|[-a-z0-9\._~\x{A0}-\x{D7FF}\x{F900}-\x{FDCF}\x{FDF0}-\x{FFEF}\x{10000}-\x{1FFFD}\x{20000}-\x{2FFFD}\x{30000}-\x{3FFFD}\x{40000}-\x{4FFFD}\x{50000}-\x{5FFFD}\x{60000}-\x{6FFFD}\x{70000}-\x{7FFFD}\x{80000}-\x{8FFFD}\x{90000}-\x{9FFFD}\x{A0000}-\x{AFFFD}\x{B0000}-\x{BFFFD}\x{C0000}-\x{CFFFD}\x{D0000}-\x{DFFFD}\x{E1000}-\x{EFFFD}!\$&'\(\)\*\+,;=:@])))(?:\?(?:(?:%[0-9a-f][0-9a-f]|[-a-z0-9\._~\x{A0}-\x{D7FF}\x{F900}-\x{FDCF}\x{FDF0}-\x{FFEF}\x{10000}-\x{1FFFD}\x{20000}-\x{2FFFD}\x{30000}-\x{3FFFD}\x{40000}-\x{4FFFD}\x{50000}-\x{5FFFD}\x{60000}-\x{6FFFD}\x{70000}-\x{7FFFD}\x{80000}-\x{8FFFD}\x{90000}-\x{9FFFD}\x{A0000}-\x{AFFFD}\x{B0000}-\x{BFFFD}\x{C0000}-\x{CFFFD}\x{D0000}-\x{DFFFD}\x{E1000}-\x{EFFFD}!\$&'\(\)\*\+,;=:@])|[\x{E000}-\x{F8FF}\x{F0000}-\x{FFFFD}\x{100000}-\x{10FFFD}\/\?])*)?(?:\#(?:(?:%[0-9a-f][0-9a-f]|[-a-z0-9\._~\x{A0}-\x{D7FF}\x{F900}-\x{FDCF}\x{FDF0}-\x{FFEF}\x{10000}-\x{1FFFD}\x{20000}-\x{2FFFD}\x{30000}-\x{3FFFD}\x{40000}-\x{4FFFD}\x{50000}-\x{5FFFD}\x{60000}-\x{6FFFD}\x{70000}-\x{7FFFD}\x{80000}-\x{8FFFD}\x{90000}-\x{9FFFD}\x{A0000}-\x{AFFFD}\x{B0000}-\x{BFFFD}\x{C0000}-\x{CFFFD}\x{D0000}-\x{DFFFD}\x{E1000}-\x{EFFFD}!\$&'\(\)\*\+,;=:@])|[\/\?])*)?$/i

To also allow relative IRIs:

/^(?:[a-z](?:[-a-z0-9\+\.])*:(?:\/\/(?:(?:%[0-9a-f][0-9a-f]|[-a-z0-9\._~\x{A0}-\x{D7FF}\x{F900}-\x{FDCF}\x{FDF0}-\x{FFEF}\x{10000}-\x{1FFFD}\x{20000}-\x{2FFFD}\x{30000}-\x{3FFFD}\x{40000}-\x{4FFFD}\x{50000}-\x{5FFFD}\x{60000}-\x{6FFFD}\x{70000}-\x{7FFFD}\x{80000}-\x{8FFFD}\x{90000}-\x{9FFFD}\x{A0000}-\x{AFFFD}\x{B0000}-\x{BFFFD}\x{C0000}-\x{CFFFD}\x{D0000}-\x{DFFFD}\x{E1000}-\x{EFFFD}!\$&'\(\)\*\+,;=:])*@)?(?:\[(?:(?:(?:[0-9a-f]{1,4}:){6}(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(?:\.(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3})|::(?:[0-9a-f]{1,4}:){5}(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(?:\.(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3})|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(?:\.(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3})|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(?:\.(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3})|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(?:\.(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3})|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(?:\.(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3})|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(?:\.(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3})|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|v[0-9a-f]+\.[-a-z0-9\._~!\$&'\(\)\*\+,;=:]+)\]|(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(?:\.(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3}|(?:%[0-9a-f][0-9a-f]|[-a-z0-9\._~\x{A0}-\x{D7FF}\x{F900}-\x{FDCF}\x{FDF0}-\x{FFEF}\x{10000}-\x{1FFFD}\x{20000}-\x{2FFFD}\x{30000}-\x{3FFFD}\x{40000}-\x{4FFFD}\x{50000}-\x{5FFFD}\x{60000}-\x{6FFFD}\x{70000}-\x{7FFFD}\x{80000}-\x{8FFFD}\x{90000}-\x{9FFFD}\x{A0000}-\x{AFFFD}\x{B0000}-\x{BFFFD}\x{C0000}-\x{CFFFD}\x{D0000}-\x{DFFFD}\x{E1000}-\x{EFFFD}!\$&'\(\)\*\+,;=])*)(?::[0-9]*)?(?:\/(?:(?:%[0-9a-f][0-9a-f]|[-a-z0-9\._~\x{A0}-\x{D7FF}\x{F900}-\x{FDCF}\x{FDF0}-\x{FFEF}\x{10000}-\x{1FFFD}\x{20000}-\x{2FFFD}\x{30000}-\x{3FFFD}\x{40000}-\x{4FFFD}\x{50000}-\x{5FFFD}\x{60000}-\x{6FFFD}\x{70000}-\x{7FFFD}\x{80000}-\x{8FFFD}\x{90000}-\x{9FFFD}\x{A0000}-\x{AFFFD}\x{B0000}-\x{BFFFD}\x{C0000}-\x{CFFFD}\x{D0000}-\x{DFFFD}\x{E1000}-\x{EFFFD}!\$&'\(\)\*\+,;=:@]))*)*|\/(?:(?:(?:(?:%[0-9a-f][0-9a-f]|[-a-z0-9\._~\x{A0}-\x{D7FF}\x{F900}-\x{FDCF}\x{FDF0}-\x{FFEF}\x{10000}-\x{1FFFD}\x{20000}-\x{2FFFD}\x{30000}-\x{3FFFD}\x{40000}-\x{4FFFD}\x{50000}-\x{5FFFD}\x{60000}-\x{6FFFD}\x{70000}-\x{7FFFD}\x{80000}-\x{8FFFD}\x{90000}-\x{9FFFD}\x{A0000}-\x{AFFFD}\x{B0000}-\x{BFFFD}\x{C0000}-\x{CFFFD}\x{D0000}-\x{DFFFD}\x{E1000}-\x{EFFFD}!\$&'\(\)\*\+,;=:@]))+)(?:\/(?:(?:%[0-9a-f][0-9a-f]|[-a-z0-9\._~\x{A0}-\x{D7FF}\x{F900}-\x{FDCF}\x{FDF0}-\x{FFEF}\x{10000}-\x{1FFFD}\x{20000}-\x{2FFFD}\x{30000}-\x{3FFFD}\x{40000}-\x{4FFFD}\x{50000}-\x{5FFFD}\x{60000}-\x{6FFFD}\x{70000}-\x{7FFFD}\x{80000}-\x{8FFFD}\x{90000}-\x{9FFFD}\x{A0000}-\x{AFFFD}\x{B0000}-\x{BFFFD}\x{C0000}-\x{CFFFD}\x{D0000}-\x{DFFFD}\x{E1000}-\x{EFFFD}!\$&'\(\)\*\+,;=:@]))*)*)?|(?:(?:(?:%[0-9a-f][0-9a-f]|[-a-z0-9\._~\x{A0}-\x{D7FF}\x{F900}-\x{FDCF}\x{FDF0}-\x{FFEF}\x{10000}-\x{1FFFD}\x{20000}-\x{2FFFD}\x{30000}-\x{3FFFD}\x{40000}-\x{4FFFD}\x{50000}-\x{5FFFD}\x{60000}-\x{6FFFD}\x{70000}-\x{7FFFD}\x{80000}-\x{8FFFD}\x{90000}-\x{9FFFD}\x{A0000}-\x{AFFFD}\x{B0000}-\x{BFFFD}\x{C0000}-\x{CFFFD}\x{D0000}-\x{DFFFD}\x{E1000}-\x{EFFFD}!\$&'\(\)\*\+,;=:@]))+)(?:\/(?:(?:%[0-9a-f][0-9a-f]|[-a-z0-9\._~\x{A0}-\x{D7FF}\x{F900}-\x{FDCF}\x{FDF0}-\x{FFEF}\x{10000}-\x{1FFFD}\x{20000}-\x{2FFFD}\x{30000}-\x{3FFFD}\x{40000}-\x{4FFFD}\x{50000}-\x{5FFFD}\x{60000}-\x{6FFFD}\x{70000}-\x{7FFFD}\x{80000}-\x{8FFFD}\x{90000}-\x{9FFFD}\x{A0000}-\x{AFFFD}\x{B0000}-\x{BFFFD}\x{C0000}-\x{CFFFD}\x{D0000}-\x{DFFFD}\x{E1000}-\x{EFFFD}!\$&'\(\)\*\+,;=:@]))*)*|(?!(?:%[0-9a-f][0-9a-f]|[-a-z0-9\._~\x{A0}-\x{D7FF}\x{F900}-\x{FDCF}\x{FDF0}-\x{FFEF}\x{10000}-\x{1FFFD}\x{20000}-\x{2FFFD}\x{30000}-\x{3FFFD}\x{40000}-\x{4FFFD}\x{50000}-\x{5FFFD}\x{60000}-\x{6FFFD}\x{70000}-\x{7FFFD}\x{80000}-\x{8FFFD}\x{90000}-\x{9FFFD}\x{A0000}-\x{AFFFD}\x{B0000}-\x{BFFFD}\x{C0000}-\x{CFFFD}\x{D0000}-\x{DFFFD}\x{E1000}-\x{EFFFD}!\$&'\(\)\*\+,;=:@])))(?:\?(?:(?:%[0-9a-f][0-9a-f]|[-a-z0-9\._~\x{A0}-\x{D7FF}\x{F900}-\x{FDCF}\x{FDF0}-\x{FFEF}\x{10000}-\x{1FFFD}\x{20000}-\x{2FFFD}\x{30000}-\x{3FFFD}\x{40000}-\x{4FFFD}\x{50000}-\x{5FFFD}\x{60000}-\x{6FFFD}\x{70000}-\x{7FFFD}\x{80000}-\x{8FFFD}\x{90000}-\x{9FFFD}\x{A0000}-\x{AFFFD}\x{B0000}-\x{BFFFD}\x{C0000}-\x{CFFFD}\x{D0000}-\x{DFFFD}\x{E1000}-\x{EFFFD}!\$&'\(\)\*\+,;=:@])|[\x{E000}-\x{F8FF}\x{F0000}-\x{FFFFD}\x{100000}-\x{10FFFD}\/\?])*)?(?:\#(?:(?:%[0-9a-f][0-9a-f]|[-a-z0-9\._~\x{A0}-\x{D7FF}\x{F900}-\x{FDCF}\x{FDF0}-\x{FFEF}\x{10000}-\x{1FFFD}\x{20000}-\x{2FFFD}\x{30000}-\x{3FFFD}\x{40000}-\x{4FFFD}\x{50000}-\x{5FFFD}\x{60000}-\x{6FFFD}\x{70000}-\x{7FFFD}\x{80000}-\x{8FFFD}\x{90000}-\x{9FFFD}\x{A0000}-\x{AFFFD}\x{B0000}-\x{BFFFD}\x{C0000}-\x{CFFFD}\x{D0000}-\x{DFFFD}\x{E1000}-\x{EFFFD}!\$&'\(\)\*\+,;=:@])|[\/\?])*)?|(?:\/\/(?:(?:%[0-9a-f][0-9a-f]|[-a-z0-9\._~\x{A0}-\x{D7FF}\x{F900}-\x{FDCF}\x{FDF0}-\x{FFEF}\x{10000}-\x{1FFFD}\x{20000}-\x{2FFFD}\x{30000}-\x{3FFFD}\x{40000}-\x{4FFFD}\x{50000}-\x{5FFFD}\x{60000}-\x{6FFFD}\x{70000}-\x{7FFFD}\x{80000}-\x{8FFFD}\x{90000}-\x{9FFFD}\x{A0000}-\x{AFFFD}\x{B0000}-\x{BFFFD}\x{C0000}-\x{CFFFD}\x{D0000}-\x{DFFFD}\x{E1000}-\x{EFFFD}!\$&'\(\)\*\+,;=:])*@)?(?:\[(?:(?:(?:[0-9a-f]{1,4}:){6}(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(?:\.(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3})|::(?:[0-9a-f]{1,4}:){5}(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(?:\.(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3})|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(?:\.(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3})|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(?:\.(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3})|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(?:\.(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3})|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(?:\.(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3})|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(?:\.(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3})|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|v[0-9a-f]+\.[-a-z0-9\._~!\$&'\(\)\*\+,;=:]+)\]|(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(?:\.(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3}|(?:%[0-9a-f][0-9a-f]|[-a-z0-9\._~\x{A0}-\x{D7FF}\x{F900}-\x{FDCF}\x{FDF0}-\x{FFEF}\x{10000}-\x{1FFFD}\x{20000}-\x{2FFFD}\x{30000}-\x{3FFFD}\x{40000}-\x{4FFFD}\x{50000}-\x{5FFFD}\x{60000}-\x{6FFFD}\x{70000}-\x{7FFFD}\x{80000}-\x{8FFFD}\x{90000}-\x{9FFFD}\x{A0000}-\x{AFFFD}\x{B0000}-\x{BFFFD}\x{C0000}-\x{CFFFD}\x{D0000}-\x{DFFFD}\x{E1000}-\x{EFFFD}!\$&'\(\)\*\+,;=])*)(?::[0-9]*)?(?:\/(?:(?:%[0-9a-f][0-9a-f]|[-a-z0-9\._~\x{A0}-\x{D7FF}\x{F900}-\x{FDCF}\x{FDF0}-\x{FFEF}\x{10000}-\x{1FFFD}\x{20000}-\x{2FFFD}\x{30000}-\x{3FFFD}\x{40000}-\x{4FFFD}\x{50000}-\x{5FFFD}\x{60000}-\x{6FFFD}\x{70000}-\x{7FFFD}\x{80000}-\x{8FFFD}\x{90000}-\x{9FFFD}\x{A0000}-\x{AFFFD}\x{B0000}-\x{BFFFD}\x{C0000}-\x{CFFFD}\x{D0000}-\x{DFFFD}\x{E1000}-\x{EFFFD}!\$&'\(\)\*\+,;=:@]))*)*|\/(?:(?:(?:(?:%[0-9a-f][0-9a-f]|[-a-z0-9\._~\x{A0}-\x{D7FF}\x{F900}-\x{FDCF}\x{FDF0}-\x{FFEF}\x{10000}-\x{1FFFD}\x{20000}-\x{2FFFD}\x{30000}-\x{3FFFD}\x{40000}-\x{4FFFD}\x{50000}-\x{5FFFD}\x{60000}-\x{6FFFD}\x{70000}-\x{7FFFD}\x{80000}-\x{8FFFD}\x{90000}-\x{9FFFD}\x{A0000}-\x{AFFFD}\x{B0000}-\x{BFFFD}\x{C0000}-\x{CFFFD}\x{D0000}-\x{DFFFD}\x{E1000}-\x{EFFFD}!\$&'\(\)\*\+,;=:@]))+)(?:\/(?:(?:%[0-9a-f][0-9a-f]|[-a-z0-9\._~\x{A0}-\x{D7FF}\x{F900}-\x{FDCF}\x{FDF0}-\x{FFEF}\x{10000}-\x{1FFFD}\x{20000}-\x{2FFFD}\x{30000}-\x{3FFFD}\x{40000}-\x{4FFFD}\x{50000}-\x{5FFFD}\x{60000}-\x{6FFFD}\x{70000}-\x{7FFFD}\x{80000}-\x{8FFFD}\x{90000}-\x{9FFFD}\x{A0000}-\x{AFFFD}\x{B0000}-\x{BFFFD}\x{C0000}-\x{CFFFD}\x{D0000}-\x{DFFFD}\x{E1000}-\x{EFFFD}!\$&'\(\)\*\+,;=:@]))*)*)?|(?:(?:%[0-9a-f][0-9a-f]|[-a-z0-9\._~\x{A0}-\x{D7FF}\x{F900}-\x{FDCF}\x{FDF0}-\x{FFEF}\x{10000}-\x{1FFFD}\x{20000}-\x{2FFFD}\x{30000}-\x{3FFFD}\x{40000}-\x{4FFFD}\x{50000}-\x{5FFFD}\x{60000}-\x{6FFFD}\x{70000}-\x{7FFFD}\x{80000}-\x{8FFFD}\x{90000}-\x{9FFFD}\x{A0000}-\x{AFFFD}\x{B0000}-\x{BFFFD}\x{C0000}-\x{CFFFD}\x{D0000}-\x{DFFFD}\x{E1000}-\x{EFFFD}!\$&'\(\)\*\+,;=@])+)(?:\/(?:(?:%[0-9a-f][0-9a-f]|[-a-z0-9\._~\x{A0}-\x{D7FF}\x{F900}-\x{FDCF}\x{FDF0}-\x{FFEF}\x{10000}-\x{1FFFD}\x{20000}-\x{2FFFD}\x{30000}-\x{3FFFD}\x{40000}-\x{4FFFD}\x{50000}-\x{5FFFD}\x{60000}-\x{6FFFD}\x{70000}-\x{7FFFD}\x{80000}-\x{8FFFD}\x{90000}-\x{9FFFD}\x{A0000}-\x{AFFFD}\x{B0000}-\x{BFFFD}\x{C0000}-\x{CFFFD}\x{D0000}-\x{DFFFD}\x{E1000}-\x{EFFFD}!\$&'\(\)\*\+,;=:@]))*)*|(?!(?:%[0-9a-f][0-9a-f]|[-a-z0-9\._~\x{A0}-\x{D7FF}\x{F900}-\x{FDCF}\x{FDF0}-\x{FFEF}\x{10000}-\x{1FFFD}\x{20000}-\x{2FFFD}\x{30000}-\x{3FFFD}\x{40000}-\x{4FFFD}\x{50000}-\x{5FFFD}\x{60000}-\x{6FFFD}\x{70000}-\x{7FFFD}\x{80000}-\x{8FFFD}\x{90000}-\x{9FFFD}\x{A0000}-\x{AFFFD}\x{B0000}-\x{BFFFD}\x{C0000}-\x{CFFFD}\x{D0000}-\x{DFFFD}\x{E1000}-\x{EFFFD}!\$&'\(\)\*\+,;=:@])))(?:\?(?:(?:%[0-9a-f][0-9a-f]|[-a-z0-9\._~\x{A0}-\x{D7FF}\x{F900}-\x{FDCF}\x{FDF0}-\x{FFEF}\x{10000}-\x{1FFFD}\x{20000}-\x{2FFFD}\x{30000}-\x{3FFFD}\x{40000}-\x{4FFFD}\x{50000}-\x{5FFFD}\x{60000}-\x{6FFFD}\x{70000}-\x{7FFFD}\x{80000}-\x{8FFFD}\x{90000}-\x{9FFFD}\x{A0000}-\x{AFFFD}\x{B0000}-\x{BFFFD}\x{C0000}-\x{CFFFD}\x{D0000}-\x{DFFFD}\x{E1000}-\x{EFFFD}!\$&'\(\)\*\+,;=:@])|[\x{E000}-\x{F8FF}\x{F0000}-\x{FFFFD}\x{100000}-\x{10FFFD}\/\?])*)?(?:\#(?:(?:%[0-9a-f][0-9a-f]|[-a-z0-9\._~\x{A0}-\x{D7FF}\x{F900}-\x{FDCF}\x{FDF0}-\x{FFEF}\x{10000}-\x{1FFFD}\x{20000}-\x{2FFFD}\x{30000}-\x{3FFFD}\x{40000}-\x{4FFFD}\x{50000}-\x{5FFFD}\x{60000}-\x{6FFFD}\x{70000}-\x{7FFFD}\x{80000}-\x{8FFFD}\x{90000}-\x{9FFFD}\x{A0000}-\x{AFFFD}\x{B0000}-\x{BFFFD}\x{C0000}-\x{CFFFD}\x{D0000}-\x{DFFFD}\x{E1000}-\x{EFFFD}!\$&'\(\)\*\+,;=:@])|[\/\?])*)?)$/i

How they were compiled (in PHP):

<?php

/* Regex convenience functions (character class, non-capturing group) */
function cc($str, $suffix = '', $negate = false) {
    return '[' . ($negate ? '^' : '') . $str . ']' . $suffix;
}
function ncg($str, $suffix = '') {
    return '(?:' . $str . ')' . $suffix;
}

/* Preserved from RFC3986 */

$ALPHA = 'a-z';
$DIGIT = '0-9';
$HEXDIG = $DIGIT . 'a-f';

$sub_delims = '!\\$&\'\\(\\)\\*\\+,;=';
$gen_delims = ':\\/\\?\\#\\[\\]@';
$reserved = $gen_delims . $sub_delims;
$unreserved = '-' . $ALPHA . $DIGIT . '\\._~';

$pct_encoded = '%' . cc($HEXDIG) . cc($HEXDIG);

$dec_octet = ncg(implode('|', array(
    cc($DIGIT),
    cc('1-9') . cc($DIGIT),
    '1' . cc($DIGIT) . cc($DIGIT),
    '2' . cc('0-4') . cc($DIGIT),
    '25' . cc('0-5')
)));

$IPv4address = $dec_octet . ncg('\\.' . $dec_octet, '{3}');

$h16 = cc($HEXDIG, '{1,4}');
$ls32 = ncg($h16 . ':' . $h16 . '|' . $IPv4address);

$IPv6address = ncg(implode('|', array(
    ncg($h16 . ':', '{6}') . $ls32,
    '::' . ncg($h16 . ':', '{5}') . $ls32,
    ncg($h16, '?') . '::' . ncg($h16 . ':', '{4}') . $ls32,
    ncg($h16 . ':' . $h16, '?') . '::' . ncg($h16 . ':', '{3}') . $ls32,
    ncg(ncg($h16 . ':', '{0,2}') . $h16, '?') . '::' . ncg($h16 . ':', '{2}') . $ls32,
    ncg(ncg($h16 . ':', '{0,3}') . $h16, '?') . '::' . $h16 . ':' . $ls32,
    ncg(ncg($h16 . ':', '{0,4}') . $h16, '?') . '::' . $ls32,
    ncg(ncg($h16 . ':', '{0,5}') . $h16, '?') . '::' . $h16,
    ncg(ncg($h16 . ':', '{0,6}') . $h16, '?') . '::',
)));

$IPvFuture = 'v' . cc($HEXDIG, '+') . cc($unreserved . $sub_delims . ':', '+');

$IP_literal = '\\[' . ncg(implode('|', array($IPv6address, $IPvFuture))) . '\\]';

$port = cc($DIGIT, '*');

$scheme = cc($ALPHA) . ncg(cc('-' . $ALPHA . $DIGIT . '\\+\\.'), '*');

/* New or changed in RFC3987 */

$iprivate = '\x{E000}-\x{F8FF}\x{F0000}-\x{FFFFD}\x{100000}-\x{10FFFD}';

$ucschar = '\x{A0}-\x{D7FF}\x{F900}-\x{FDCF}\x{FDF0}-\x{FFEF}' .
    '\x{10000}-\x{1FFFD}\x{20000}-\x{2FFFD}\x{30000}-\x{3FFFD}' .
    '\x{40000}-\x{4FFFD}\x{50000}-\x{5FFFD}\x{60000}-\x{6FFFD}' .
    '\x{70000}-\x{7FFFD}\x{80000}-\x{8FFFD}\x{90000}-\x{9FFFD}' .
    '\x{A0000}-\x{AFFFD}\x{B0000}-\x{BFFFD}\x{C0000}-\x{CFFFD}' .
    '\x{D0000}-\x{DFFFD}\x{E1000}-\x{EFFFD}';

$iunreserved = '-' . $ALPHA . $DIGIT . '\\._~' . $ucschar;

$ipchar = ncg($pct_encoded . '|' . cc($iunreserved . $sub_delims . ':@'));

$ifragment = ncg($ipchar . '|' . cc('\\/\\?'), '*');

$iquery = ncg($ipchar . '|' . cc($iprivate . '\\/\\?'), '*');

$isegment_nz_nc = ncg($pct_encoded . '|' . cc($iunreserved . $sub_delims . '@'), '+');
$isegment_nz = ncg($ipchar, '+');
$isegment = ncg($ipchar, '*');

$ipath_empty = '(?!' . $ipchar . ')';
$ipath_rootless = ncg($isegment_nz) . ncg('\\/' . $isegment, '*');
$ipath_noscheme = ncg($isegment_nz_nc) . ncg('\\/' . $isegment, '*');
$ipath_absolute = '\\/' . ncg($ipath_rootless, '?'); // Spec says isegment-nz *( "/" isegment )
$ipath_abempty = ncg('\\/' . $isegment, '*');

$ipath = ncg(implode('|', array(
    $ipath_abempty,
    $ipath_absolute,
    $ipath_noscheme,
    $ipath_rootless,
    $ipath_empty
))) . ')';

$ireg_name = ncg($pct_encoded . '|' . cc($iunreserved . $sub_delims . '@'), '*');

$ihost = ncg(implode('|', array($IP_literal, $IPv4address, $ireg_name)));
$iuserinfo = ncg($pct_encoded . '|' . cc($iunreserved . $sub_delims . ':'), '*');
$iauthority = ncg($iuserinfo . '@', '?') . $ihost . ncg(':' . $port, '?');

$irelative_part = ncg(implode('|', array(
    '\\/\\/' . $iauthority . $ipath_abempty . '',
    '' . $ipath_absolute . '',
    '' . $ipath_noscheme . '',
    '' . $ipath_empty . ''
)));

$irelative_ref = $irelative_part . ncg('\\?' . $iquery, '?') . ncg('\\#' . $ifragment, '?');

$ihier_part = ncg(implode('|', array(
    '\\/\\/' . $iauthority . $ipath_abempty . '',
    '' . $ipath_absolute . '',
    '' . $ipath_rootless . '',
    '' . $ipath_empty . ''
)));

$absolute_IRI = $scheme . ':' . $ihier_part . ncg('\\?' . $iquery, '?');

$IRI = $scheme . ':' . $ihier_part . ncg('\\?' . $iquery, '?') . ncg('\\#' . $ifragment, '?');

$IRI_reference = ncg($IRI . '|' . $irelative_ref);

Edit 7 March 2011: Because of the way PHP handles backslashes in quoted strings, these are unusable by default. You'll need to double-escape backslashes except where the backslash has a special meaning in regex. You can do that this way:

$escape_backslash = '/(?<!\\)\\(?![\[\]\\\^\$\.\|\*\+\(\)QEnrtaefvdwsDWSbAZzB1-9GX]|x\{[0-9a-f]{1,4}\}|\c[A-Z]|)/';
$absolute_IRI = preg_replace($escape_backslash, '\\\\', $absolute_IRI);
$IRI = preg_replace($escape_backslash, '\\\\', $IRI);
$IRI_reference = preg_replace($escape_backslash, '\\\\', $IRI_reference);

Merge data frames based on rownames in R

See ?merge:

the name "row.names" or the number 0 specifies the row names.

Example:

R> de <- merge(d, e, by=0, all=TRUE)  # merge by row names (by=0 or by="row.names")
R> de[is.na(de)] <- 0                 # replace NA values
R> de
  Row.names   a   b   c   d   e   f   g   h   i  j  k  l  m  n  o  p  q  r  s
1         1 1.0 2.0 3.0 4.0 5.0 6.0 7.0 8.0 9.0 10 11 12 13 14 15 16 17 18 19
2         2 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9  1  0  0  0  0  0  0  0  0  0
3         3 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0  0 21 22 23 24 25 26 27 28 29
   t
1 20
2  0
3 30

Send form data with jquery ajax json

Sending data from formfields back to the server (php) is usualy done by the POST method which can be found back in the superglobal array $_POST inside PHP. There is no need to transform it to JSON before you send it to the server. Little example:

<?php

if($_SERVER['REQUEST_METHOD'] == 'POST')
{
    echo '<pre>';
    print_r($_POST);
}
?>
<form action="" method="post">
<input type="text" name="email" value="[email protected]" />
<button type="submit">Send!</button>

With AJAX you are able to do exactly the same thing, only without page refresh.

ExtJs Gridpanel store refresh

Try refreshing the view:

Ext.getCmp('yourGridId').getView().refresh();

cordova Android requirements failed: "Could not find an installed version of Gradle"

Solution for Windows (Windows 10) is:

  1. Make sure you have Java 8 installed
  2. Download Gradle binary from https://gradle.org/install/
  3. Create a new directory C:\Gradle with File Explorer
  4. Extract and copy gradle-6.7.1 to C:\Gradle
  5. Configure your PATH environment variable to include the path C:\Gradle\gradle-6.7.1\bin
  6. Run gradle -v to confirm all is okay. C:>Gradle -v

Gradle 6.7.1

Build time: 2020-11-16 17:09:24 UTC Revision: 2972ff02f3210d2ceed2f1ea880f026acfbab5c0

Kotlin: 1.3.72 Groovy: 2.5.12 Ant: Apache Ant(TM) version 1.10.8 compiled on May 10 2020 JVM: 1.8.0_144 (Oracle Corporation 25.144-b01) OS: Windows 10 10.0 x86

C:>

Finally, run [Cordova environments] to check that all is set for development.

C:\Users\opiyog\AndroidStudioProjects\IONIC\SecondApp>cordova requirements

Requirements check results for android: Java JDK: installed 1.8.0 Android SDK: installed true Android target: installed android-30,android-29,android-28,android-27,android-26,android-25,android-24,android-23,android-22,android-21,android-19 Gradle: installed C:\Gradle\gradle-6.7.1\bin\gradle.BAT

PHP Function Comments

You can get the comments of a particular method by using the ReflectionMethod class and calling ->getDocComment().

http://www.php.net/manual/en/reflectionclass.getdoccomment.php

What is the difference between rb and r+b modes in file objects

On Windows, 'b' appended to the mode opens the file in binary mode, so there are also modes like 'rb', 'wb', and 'r+b'. Python on Windows makes a distinction between text and binary files; the end-of-line characters in text files are automatically altered slightly when data is read or written. This behind-the-scenes modification to file data is fine for ASCII text files, but it’ll corrupt binary data like that in JPEG or EXE files. Be very careful to use binary mode when reading and writing such files. On Unix, it doesn’t hurt to append a 'b' to the mode, so you can use it platform-independently for all binary files.

Source: Reading and Writing Files

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

Only "keyboard focusable" elements can be focused with .focus(). div aren't meant to be natively focusable. You have to add tabindex="0" attributes to it to achieve that. input, button, a etc... are natively focusable.

How to set background image of a view?

Besides all of the other responses here, I really don't think that using backgroundColor in this way is the proper way to do things. Personally, I would create a UIImageView and insert it into your view hierarchy. You can either insert it into your top view and push it all the way to the back with sendSubviewToBack: or you can make the UIImageView the parent view.

I wouldn't worry about things like how efficient each implementation is at this point because unless you actually see an issue, it really doesn't matter. Your first priority for now should be writing code that you can understand and can easily be changed. Creating a UIColor to use as your background image isn't the clearest method of doing this.

Make a borderless form movable?

There's no property you can flip to make this just happen magically. Look at the events for the form and it becomes fairly trivial to implement this by setting this.Top and this.Left. Specifically you'll want to look at MouseDown, MouseUp and MouseMove.

MySQL select rows where left join is null

Try:

SELECT A.id FROM
(
  SELECT table1.id FROM table1 
  LEFT JOIN table2 ON table1.id = table2.user_one
  WHERE table2.user_one IS NULL
) A
JOIN (
  SELECT table1.id FROM table1 
  LEFT JOIN table2 ON table1.id = table2.user_two
  WHERE table2.user_two IS NULL
) B
ON A.id = B.id

See Demo

Or you could use two LEFT JOINS with aliases like:

SELECT table1.id FROM table1 
 LEFT JOIN table2 A ON table1.id = A.user_one
 LEFT JOIN table2 B ON table1.id = B.user_two
 WHERE A.user_one IS NULL
 AND B.user_two IS NULL

See 2nd Demo

Which Python memory profiler is recommended?

My module memory_profiler is capable of printing a line-by-line report of memory usage and works on Unix and Windows (needs psutil on this last one). Output is not very detailed but the goal is to give you an overview of where the code is consuming more memory, not an exhaustive analysis on allocated objects.

After decorating your function with @profile and running your code with the -m memory_profiler flag it will print a line-by-line report like this:

Line #    Mem usage  Increment   Line Contents
==============================================
     3                           @profile
     4      5.97 MB    0.00 MB   def my_func():
     5     13.61 MB    7.64 MB       a = [1] * (10 ** 6)
     6    166.20 MB  152.59 MB       b = [2] * (2 * 10 ** 7)
     7     13.61 MB -152.59 MB       del b
     8     13.61 MB    0.00 MB       return a

Using margin / padding to space <span> from the rest of the <p>

Use div instead of span, or add display: block; to your css style for the span tag.

One-liner if statements, how to convert this if-else-statement

All you'd need in your case is:

return expression;

The reason why is that the expression itself evaluates to a boolean value of true or false, so it's redundant to have an if block (or even a ?: operator).

How do I force a vertical scrollbar to appear?

Give your body tag an overflow: scroll;

body {
    overflow: scroll;
}

or if you only want a vertical scrollbar use overflow-y

body {
    overflow-y: scroll;
}

How do I view the SQL generated by the Entity Framework?

If you are using a DbContext, you can do the following to get the SQL:

var result = from i in myContext.appEntities
             select new Model
             {
                 field = i.stuff,
             };
var sql = result.ToString();

Combine two arrays

This works:

$a = array(1 => 1, 2 => 2, 3 => 3);
$b = array(4 => 4, 5 => 5, 6 => 6);
$c = $a + $b;
print_r($c);

Django: ImproperlyConfigured: The SECRET_KEY setting must not be empty

For anyone using PyCharm: the green "Run selected configuration" button would produce this error, yet running the following works:

py manage.py runserver 127.0.0.1:8000 --settings=app_name.settings.development

To fix this you need to edit the configuration's environment variables. To do this click the "Select run/debug configuration" drop-down menu to the left of the green run button and then click on "edit configuration". Under the "environment" tab change the environment variable DJANGO_SETTINGS_MODULE to app_name.settings.development.

R plot: size and resolution

A reproducible example:

the_plot <- function()
{
  x <- seq(0, 1, length.out = 100)
  y <- pbeta(x, 1, 10)
  plot(
    x,
    y,
    xlab = "False Positive Rate",
    ylab = "Average true positive rate",
    type = "l"
  )
}

James's suggestion of using pointsize, in combination with the various cex parameters, can produce reasonable results.

png(
  "test.png",
  width     = 3.25,
  height    = 3.25,
  units     = "in",
  res       = 1200,
  pointsize = 4
)
par(
  mar      = c(5, 5, 2, 2),
  xaxs     = "i",
  yaxs     = "i",
  cex.axis = 2,
  cex.lab  = 2
)
the_plot()
dev.off()

Of course the better solution is to abandon this fiddling with base graphics and use a system that will handle the resolution scaling for you. For example,

library(ggplot2)

ggplot_alternative <- function()
{
  the_data <- data.frame(
    x <- seq(0, 1, length.out = 100),
    y = pbeta(x, 1, 10)
  )

ggplot(the_data, aes(x, y)) +
    geom_line() +
    xlab("False Positive Rate") +
    ylab("Average true positive rate") +
    coord_cartesian(0:1, 0:1)
}

ggsave(
  "ggtest.png",
  ggplot_alternative(),
  width = 3.25,
  height = 3.25,
  dpi = 1200
)

java.lang.NoSuchMethodError: org.apache.commons.codec.binary.Base64.encodeBase64String() in Java EE application

Some Google tooling such as GWT has an embedded version of commons-codec with a pre-1.4 Base64 class. You may need to make such tooling JARs inaccessible to your code by refactoring your project such that only the parts of your code that need that tooling can see the dependency.

WAMP/XAMPP is responding very slow over localhost

For my it was the xdebug. I disabled and it worked as it should be !

[XDebug]
zend_extension = C:\xampp\php\ext\php_xdebug-2.3.2-5.6-vc11.dll

How to deploy a war file in Tomcat 7

Perform the following steps:

  • Stop the Tomcat
  • Right Click on Project and click on "Clean and Build"
  • Go to your project Directory and inside Dist Folder you will get war file that you copy on your tomcat
  • webApp Folder
  • Start the tomcat
  • automatic war file extract and run your project

How do I install Python 3 on an AWS EC2 instance?

On Debian derivatives such as Ubuntu, use apt. Check the apt repository for the versions of Python available to you. Then, run a command similar to the following, substituting the correct package name:

sudo apt-get install python3

On Red Hat and derivatives, use yum. Check the yum repository for the versions of Python available to you. Then, run a command similar to the following, substituting the correct package name:

sudo yum install python36

On SUSE and derivatives, use zypper. Check the repository for the versions of Python available to you. Then. run a command similar to the following, substituting the correct package name:

sudo zypper install python3

Which @NotNull Java annotation should I use?

One of the nice things about IntelliJ is that you don't need to use their annotations. You can write your own, or you can use those of whatever other tool you like. You're not even limited to a single type. If you're using two libraries that use different @NotNull annotations, you can tell IntelliJ to use both of them. To do this, go to "Configure Inspections", click on the "Constant Conditions & Exceptions" inspection, and hit the "Configure inspections" button. I use the Nullness Checker wherever I can, so I set up IntelliJ to use those annotations, but you can make it work with whatever other tool you want. (I have no opinion on the other tools because I've been using IntelliJ's inspections for years, and I love them.)

How to get Git to clone into current directory

Improving on @GoZoner's answer:

git clone <repository> foo; shopt -s dotglob nullglob; mv foo/* .; rmdir foo

The shopt command is taken from this SO answer and changes the behavior of the 'mv' command on Bash to include dotfiles, which you'll need to include the .git directory and any other hidden files.

Also note that this is only guaranteed to work as-is if the current directory (.) is empty, but it will work as long as none of the files in the cloned repo have the same name as files in the current directory. If you don't care what's in the current directory, you can add the -f (force) option to the 'mv' command.

Display Two <div>s Side-by-Side

Try this : (http://jsfiddle.net/TpqVx/)

.left-div {
    float: left;
    width: 100px;
    /*height: 20px;*/
    margin-right: 8px;
    background-color: linen;
}
.right-div {

    margin-left: 108px;
    background-color: lime;
}??

<div class="left-div">
    &nbsp;
</div>
<div class="right-div">
    My requirements are <b>[A]</b> Content in the two divs should line up at the top, <b>[B]</b> Long text in right-div should not wrap underneath left-div, and <b>[C]</b> I do not want to specify a width of right-div. I don't want to set the width of right-div because this markup needs to work within different widths.
</div>
<div style='clear:both;'>&nbsp;</div>

Hints :

  • Just use float:left in your left-most div only.
  • No real reason to use height, but anyway...
  • Good practice to use <div 'clear:both'>&nbsp;</div> after your last div.

To show error message without alert box in Java Script

I m agree with @ReNjITh.R answer but If you want to display error message just beside textbox. Just like below

enter image description here

<html>
<head>
<script type="text/javascript">
    function validate() 
    {
        if(myform.fname.value.length==0)
        {
           document.getElementById('errfn').innerHTML="this is invalid name";
        }
    }
</script>
</head>
<body>
    <form name="myform">
         First_Name
         <input type=text id=fname name=fname onblur="validate()" /><span id="errfn"></span>
        <br> <br>
         Last_Name
         <input type=text id=lname name=lname onblur="validate()"/><br>
         <input type=button value=check /> 
    </form>
</body>

Oracle 'Partition By' and 'Row_Number' keyword

That selects the row number per country code, account, and currency. So, the rows with country code "US", account "XYZ" and currency "$USD" will each get a row number assigned from 1-n; the same goes for every other combination of those columns in the result set.

This query is kind of funny, because the order by clause does absolutely nothing. All the rows in each partition have the same country code, account, and currency, so there's no point ordering by those columns. The ultimate row numbers assigned in this particular query will therefore be unpredictable.

Hope that helps...

How does RewriteBase work in .htaccess

AFAIK, RewriteBase is only used to fix cases where mod_rewrite is running in a .htaccess file not at the root of a site and it guesses the wrong web path (as opposed to filesystem path) for the folder it is running in. So if you have a RewriteRule in a .htaccess in a folder that maps to http://example.com/myfolder you can use:

RewriteBase myfolder

If mod_rewrite isn't working correctly.

Trying to use it to achieve something unusual, rather than to fix this problem sounds like a recipe to getting very confused.

Asus Zenfone 5 not detected by computer

I had the same problem. I solved it the following way :

1. Go to Settings->Storage->Click the USB icon at top
2. Make sure that MTP is selected

TypeError: 'undefined' is not a function (evaluating '$(document)')

You can pass $ in function()

jQuery(document).ready(function($){

// jQuery code is in here

});

or you can replace $(document); with this jQuery(document);

or you can use jQuery.noConflict()

var jq=jQuery.noConflict();
jq(document).ready(function(){  
  jq('selector').show();
});

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

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

public class ThreadProvider implements CustomInterface{
...
}

Then in your controller try this:

@Controller
public class ChiusuraController {

    @Autowired
    private CustomInterface chiusuraProvider;
}

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

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

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

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

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

Hive query output to file

To directly save the file in HDFS, use the below command:

hive> insert overwrite  directory '/user/cloudera/Sample' row format delimited fields terminated by '\t' stored as textfile select * from table where id >100;

This will put the contents in the folder /user/cloudera/Sample in HDFS.

How to make two plots side-by-side using Python?

Check this page out: http://matplotlib.org/examples/pylab_examples/subplots_demo.html

plt.subplots is similar. I think it's better since it's easier to set parameters of the figure. The first two arguments define the layout (in your case 1 row, 2 columns), and other parameters change features such as figure size:

import numpy as np
import matplotlib.pyplot as plt

x1 = np.linspace(0.0, 5.0)
x2 = np.linspace(0.0, 2.0)
y1 = np.cos(2 * np.pi * x1) * np.exp(-x1)
y2 = np.cos(2 * np.pi * x2)

fig, axes = plt.subplots(nrows=1, ncols=2, figsize=(5, 3))
axes[0].plot(x1, y1)
axes[1].plot(x2, y2)
fig.tight_layout()

enter image description here

JQuery - Set Attribute value

Use an ID to uniquely identify the checkbox. Your current example is trying to select the checkbox with an id of '#chk0':

<input type="checkbox" id="chk0" name="chk0" value="true" disabled>

$('#chk0').attr("disabled", "disabled");

You'll also need to remove the attribute for disabled to enable the checkbox. Something like:

$('#chk0').removeAttr("disabled");

See the docs for removeAttr

The value XHTML for disabling/enabling an input element is as follows:

<input type="checkbox" id="chk0" name="chk0" value="true" disabled="disabled" />
<input type="checkbox" id="chk0" name="chk0" value="true" />

Note that it's the absence of the disabled attribute that makes the input element enabled.

Split text file into smaller multiple text file using command line

Syntax looks like:

$ split [OPTION] [INPUT [PREFIX]] 

where prefix is PREFIXaa, PREFIXab, ...

Just use proper one and youre done or just use mv for renameing. I think $ mv * *.txt should work but test it first on smaller scale.

:)

Select top 10 records for each category

If you are using SQL 2005 you can do something like this...

SELECT rs.Field1,rs.Field2 
    FROM (
        SELECT Field1,Field2, Rank() 
          over (Partition BY Section
                ORDER BY RankCriteria DESC ) AS Rank
        FROM table
        ) rs WHERE Rank <= 10

If your RankCriteria has ties then you may return more than 10 rows and Matt's solution may be better for you.

How to select distinct rows in a datatable and store into an array

string[] TobeDistinct = {"Name","City","State"};
DataTable dtDistinct = GetDistinctRecords(DTwithDuplicate, TobeDistinct);

//Following function will return Distinct records for Name, City and State column.
public static DataTable GetDistinctRecords(DataTable dt, string[] Columns)
{
    DataTable dtUniqRecords = new DataTable();
    dtUniqRecords = dt.DefaultView.ToTable(true, Columns);
    return dtUniqRecords;
}

Counting DISTINCT over multiple columns

It works for me. In oracle:

SELECT SUM(DECODE(COUNT(*),1,1,1))
FROM DocumentOutputItems GROUP BY DocumentId, DocumentSessionId;

In jpql:

SELECT SUM(CASE WHEN COUNT(i)=1 THEN 1 ELSE 1 END)
FROM DocumentOutputItems i GROUP BY i.DocumentId, i.DocumentSessionId;

Installing and Running MongoDB on OSX

Mac Installation:

  1. Install brew

    ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
    
  2. Update and verify you are good with

    brew update
    brew doctor
    
  3. Install mongodb with

    brew install mongodb
    
  4. Create folder for mongo data files:

    mkdir -p /data/db
    
  5. Set permissions

    sudo chown -R `id -un` /data/db
    
  6. Open another terminal window & run and keep running a mongo server/daemon

    mongod
    
  7. Return to previous terminal and run a mongodb shell to access data

    mongo
    

To quit each of these later:

  1. The Shell:

    quit()
    
  2. The Server

    ctrl-c
    

Center an item with position: relative

Alternatively, you may also use the CSS3 Flexible Box Model. It's a great way to create flexible layouts that can also be applied to center content like so:

#parent {
    -webkit-box-align:center;
    -webkit-box-pack:center;
    display:-webkit-box;
}

How can I close a dropdown on click outside?

You can use (document:click) event:

@Component({
  host: {
    '(document:click)': 'onClick($event)',
  },
})
class SomeComponent() {
  constructor(private _eref: ElementRef) { }

  onClick(event) {
   if (!this._eref.nativeElement.contains(event.target)) // or some similar check
     doSomething();
  }
}

Another approach is to create custom event as a directive. Check out these posts by Ben Nadel:

104, 'Connection reset by peer' socket error, or When does closing a socket result in a RST rather than FIN?

Normally, you'd get an RST if you do a close which doesn't linger (i.e. in which data can be discarded by the stack if it hasn't been sent and ACK'd) and a normal FIN if you allow the close to linger (i.e. the close waits for the data in transit to be ACK'd).

Perhaps all you need to do is set your socket to linger so that you remove the race condition between a non lingering close done on the socket and the ACKs arriving?

How to install the Raspberry Pi cross compiler on my Linux host machine?

The initial question has been posted quite some time ago and in the meantime Debian has made huge headway in the area of multiarch support.

Multiarch is a great achievement for cross compilation!

In a nutshell the following steps are required to leverage multiarch for Raspbian Jessie cross compilation:

  • On your Ubuntu host install Debian Jessie amd64 within a chroot or a LXC container.
  • Enable the foreign architecture armhf.
  • Install the cross compiler from the emdebian tools repository.
  • Tweak the cross compiler (it would generate code for ARMv7-A by default) by writing a custom gcc specs file.
  • Install armhf libraries (libstdc++ etc.) from the Raspbian repository.
  • Build your source code.

Since this is a lot of work I have automated the above setup. You can read about it here:

Cross Compiling for Raspbian

Why am I getting this error: No mapping specified for the following EntitySet/AssociationSet - Entity1?

Sharing this for other people. In my case, we were working on a shared MVC solution, and using a common module for tables that we use for dropdowns. I got the error when I updated the Entity model by adding a new table. It turns out that when I updated the the EDMX, it probably updated my rights access on the database, which resulted to not having access to that certain table giving me no mapping specified.

Just re-adding and giving access to my user solved the problem.

How to get the squared symbol (²) to display in a string

I create equations with random numbers in VBA and for x squared put in x^2.

I read each square (or textbox) text into a string.

I then read each character in the string in turn and note the location of the ^ ("hats")'s in each.

Say the hats were at positions 4, 8 and 12.

I then "chop out" the first hat - the position of the character to be superscripted is now 4, the position of the other hats is now 7 and 11. I chop out the second hat, the character to superscript is now at 7 and the hat has moved to 10. I chop out the last hat .. the superscript character is now position 10.

I now select each character in turn and change the font to superscript.

Thus I can fill a whole spreadsheet with algebra using ^ and then call a routine to tidy it up.

For big powers like x to the 23 I build x^2^3 and the above routine does it.

Java Array, Finding Duplicates

Cause you are comparing the first element of the array against itself so It finds that there are duplicates even where there aren't.

MVC [HttpPost/HttpGet] for Action

In Mvc 4 you can use AcceptVerbsAttribute, I think this is a very clean solution

[AcceptVerbs(WebRequestMethods.Http.Get, WebRequestMethods.Http.Post)]
public IHttpActionResult Login()
{
   // Login logic
}

firefox proxy settings via command line

You can easily launch Firefox from the command line with a proxy server using the -proxy-server option.

This works on Mac, Windows and Linux.

path_to_firefox/firefox.exe -proxy-server %proxy_URL%

Mac Example:

/Applications/Firefox.app/Contents/MacOS/firefox -proxy-server proxy.example.com

Android ListView with onClick items

In your activity, where you defined your listview

you write

listview.setOnItemClickListener(new OnItemClickListener(){   
    @Override
    public void onItemClick(AdapterView<?>adapter,View v, int position){
        ItemClicked item = adapter.getItemAtPosition(position);

        Intent intent = new Intent(Activity.this,destinationActivity.class);
        //based on item add info to intent
        startActivity(intent);
    }
});

in your adapter's getItem you write

public ItemClicked getItem(int position){
    return items.get(position);
}

How do I draw a grid onto a plot in Python?

Here is a small example how to add a matplotlib grid in Gtk3 with Python 2 (not working in Python 3):

#!/usr/bin/env python
#-*- coding: utf-8 -*-

import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk
from matplotlib.figure import Figure
from matplotlib.backends.backend_gtk3agg import FigureCanvasGTK3Agg as FigureCanvas

win = Gtk.Window()
win.connect("delete-event", Gtk.main_quit)
win.set_title("Embedding in GTK3")

f = Figure(figsize=(1, 1), dpi=100)
ax = f.add_subplot(111)
ax.grid()

canvas = FigureCanvas(f)
canvas.set_size_request(400, 400)
win.add(canvas)

win.show_all()
Gtk.main()

enter image description here

The POM for project is missing, no dependency information available

The scope <scope>provided</scope> gives you an opportunity to tell that the jar would be available at runtime, so do not bundle it. It does not mean that you do not need it at compile time, hence maven would try to download that.

Now I think, the below maven artifact do not exist at all. I tries searching google, but not able to find. Hence you are getting this issue.

Change groupId to <groupId>net.sourceforge.ant4x</groupId> to get the latest jar.

<dependency>
  <groupId>net.sourceforge.ant4x</groupId>
  <artifactId>ant4x</artifactId>
  <version>${net.sourceforge.ant4x-version}</version>
  <scope>provided</scope>
</dependency>

Another solution for this problem is:

  1. Run your own maven repo.
  2. download the jar
  3. Install the jar into the repository.
  4. Add a code in your pom.xml something like:

Where http://localhost/repo is your local repo URL:

<repositories>
    <repository>
        <id>wmc-central</id>
        <url>http://localhost/repo</url>
    </repository>
    <-- Other repository config ... -->
</repositories>

HTML/CSS: how to put text both right and left aligned in a paragraph

enter image description here

If the texts has different sizes and they must be underlined this is the solution:

<table>
  <tr>
    <td class='left'>January</td>
    <td class='right'>2014</td>
  </tr>
</table>

css:

table{
    width: 100%;
    border-bottom: 2px solid black;
    /*this is the size of the small text's baseline over part  (˜25px*3/4)*/
    line-height: 19.5px; 
}
table td{
    vertical-align: baseline;
}
.left{
    font-family: Arial;
    font-size: 40px;
    text-align: left;

}
.right{
    font-size: 25px;
    text-align: right;
}

demo here

How to get current date time in milliseconds in android

The problem is that System. currentTimeMillis(); returns the number of milliseconds from 1970-01-01T00:00:00Z, but new Date() gives the current local time. Adding the ZONE_OFFSET and DST_OFFSET from the Calendar class gives you the time in UTC.

Calendar rightNow = Calendar.getInstance();

// offset to add since we're not UTC

long offset = rightNow.get(Calendar.ZONE_OFFSET) +
    rightNow.get(Calendar.DST_OFFSET);

long sinceMidnight = (rightNow.getTimeInMillis() + offset) %
    (24 * 60 * 60 * 1000);

System.out.println(sinceMidnight + " milliseconds since midnight");

Firebase FCM force onTokenRefresh() to be called

    [Service]
[IntentFilter(new[] { "com.google.firebase.INSTANCE_ID_EVENT" })]
class MyFirebaseIIDService: FirebaseInstanceIdService
{
    const string TAG = "MyFirebaseIIDService";
    NotificationHub hub;

    public override void OnTokenRefresh()
    {
        var refreshedToken = FirebaseInstanceId.Instance.Token;
        Log.Debug(TAG, "FCM token: " + refreshedToken);
        SendRegistrationToServer(refreshedToken);
    }

    void SendRegistrationToServer(string token)
    {
        // Register with Notification Hubs
        hub = new NotificationHub(Constants.NotificationHubName,
                                    Constants.ListenConnectionString, this);
        Employee employee = JsonConvert.DeserializeObject<Employee>(Settings.CurrentUser);
        //if user is not logged in 
        if (employee != null)
        {
            var tags = new List<string>() { employee.Email};
            var regID = hub.Register(token, tags.ToArray()).RegistrationId;

            Log.Debug(TAG, $"Successful registration of ID {regID}");
        }
        else
        {
            FirebaseInstanceId.GetInstance(Firebase.FirebaseApp.Instance).DeleteInstanceId();
            hub.Unregister();
        }
    }
}

How to upgrade Git on Windows to the latest version?

Update Git Through Command Prompt

  1. Check Version git --version

  2. If your git version is 2.27.0.windows.1 or earlier

  3. If the version is equal to or greater than Git 2.27.0.windows.1

  4. Use command git update-git-for-windows

if you want to video tutorial click here

Git push/clone to new server

There are many ways to move repositories around, git bundle is a nice way if you have insufficient network availability. Since a Git repository is really just a directory full of files, you can "clone" a repository by making a copy of the .git directory in whatever way suits you best.

The most efficient way is to use an external repository somewhere (use GitHub or set up Gitosis), and then git push.

download csv file from web api in angular js

The a.download is not supported by IE. At least at the HTML5 "supported" pages. :(

Remove carriage return in Unix

I'm going to assume you mean carriage returns (CR, "\r", 0x0d) at the ends of lines rather than just blindly within a file (you may have them in the middle of strings for all I know). Using this test file with a CR at the end of the first line only:

$ cat infile
hello
goodbye

$ cat infile | od -c
0000000   h   e   l   l   o  \r  \n   g   o   o   d   b   y   e  \n
0000017

dos2unix is the way to go if it's installed on your system:

$ cat infile | dos2unix -U | od -c
0000000   h   e   l   l   o  \n   g   o   o   d   b   y   e  \n
0000016

If for some reason dos2unix is not available to you, then sed will do it:

$ cat infile | sed 's/\r$//' | od -c
0000000   h   e   l   l   o  \n   g   o   o   d   b   y   e  \n
0000016

If for some reason sed is not available to you, then ed will do it, in a complicated way:

$ echo ',s/\r\n/\n/
> w !cat
> Q' | ed infile 2>/dev/null | od -c
0000000   h   e   l   l   o  \n   g   o   o   d   b   y   e  \n
0000016

If you don't have any of those tools installed on your box, you've got bigger problems than trying to convert files :-)

Best way to combine two or more byte arrays in C#

Many of the answers seem to me to be ignoring the stated requirements:

  • The result should be a byte array
  • It should be as efficient as possible

These two together rule out a LINQ sequence of bytes - anything with yield is going to make it impossible to get the final size without iterating through the whole sequence.

If those aren't the real requirements of course, LINQ could be a perfectly good solution (or the IList<T> implementation). However, I'll assume that Superdumbell knows what he wants.

(EDIT: I've just had another thought. There's a big semantic difference between making a copy of the arrays and reading them lazily. Consider what happens if you change the data in one of the "source" arrays after calling the Combine (or whatever) method but before using the result - with lazy evaluation, that change will be visible. With an immediate copy, it won't. Different situations will call for different behaviour - just something to be aware of.)

Here are my proposed methods - which are very similar to those contained in some of the other answers, certainly :)

public static byte[] Combine(byte[] first, byte[] second)
{
    byte[] ret = new byte[first.Length + second.Length];
    Buffer.BlockCopy(first, 0, ret, 0, first.Length);
    Buffer.BlockCopy(second, 0, ret, first.Length, second.Length);
    return ret;
}

public static byte[] Combine(byte[] first, byte[] second, byte[] third)
{
    byte[] ret = new byte[first.Length + second.Length + third.Length];
    Buffer.BlockCopy(first, 0, ret, 0, first.Length);
    Buffer.BlockCopy(second, 0, ret, first.Length, second.Length);
    Buffer.BlockCopy(third, 0, ret, first.Length + second.Length,
                     third.Length);
    return ret;
}

public static byte[] Combine(params byte[][] arrays)
{
    byte[] ret = new byte[arrays.Sum(x => x.Length)];
    int offset = 0;
    foreach (byte[] data in arrays)
    {
        Buffer.BlockCopy(data, 0, ret, offset, data.Length);
        offset += data.Length;
    }
    return ret;
}

Of course the "params" version requires creating an array of the byte arrays first, which introduces extra inefficiency.

Set font-weight using Bootstrap classes

In Bootstrap 4:

class="font-weight-bold"

Or:

<strong>text</strong>

sending email via php mail function goes to spam

What we usually do with e-mail, preventing spam-folders as the end destination, is using either Gmail as the smtp server or Mandrill as the smtp server.

How to write inline if statement for print?

If you don't want to from __future__ import print_function you can do the following:

a = 100
b = True
print a if b else "",  # Note the comma!
print "see no new line"

Which prints:

100 see no new line

If you're not aversed to from __future__ import print_function or are using python 3 or later:

from __future__ import print_function
a = False
b = 100
print(b if a else "", end = "")

Adding the else is the only change you need to make to make your code syntactically correct, you need the else for the conditional expression (the "in line if else blocks")

The reason I didn't use None or 0 like others in the thread have used, is because using None/0 would cause the program to print None or print 0 in the cases where b is False.

If you want to read about this topic I've included a link to the release notes for the patch that this feature was added to Python.

The 'pattern' above is very similar to the pattern shown in PEP 308:

This syntax may seem strange and backwards; why does the condition go in the middle of the expression, and not in the front as in C's c ? x : y? The decision was checked by applying the new syntax to the modules in the standard library and seeing how the resulting code read. In many cases where a conditional expression is used, one value seems to be the 'common case' and one value is an 'exceptional case', used only on rarer occasions when the condition isn't met. The conditional syntax makes this pattern a bit more obvious:

contents = ((doc + '\n') if doc else '')

So I think overall this is a reasonable way of approching it but you can't argue with the simplicity of:

if logging: print data

How to place the cursor (auto focus) in text box when a page gets loaded without javascript support?

An expansion for those who did a bit of fiddling around like I did.

The following work (from W3):

<input type="text" autofocus />
<input type="text" autofocus="" />
<input type="text" autofocus="autofocus" />
<input type="text" autofocus="AuToFoCuS" />

It is important to note that this does not work in CSS though. I.e. you can't use:

.first-input {
    autofocus:"autofocus"
}

At least it didn't work for me...

Proper way to initialize a C# dictionary with values?

With C# 6.0, you can create a dictionary in following way:

var dict = new Dictionary<string, int>
{
    ["one"] = 1,
    ["two"] = 2,
    ["three"] = 3
};

It even works with custom types.

How to install Android app on LG smart TV?

Here is a great guide how to do that, if your TV is android TV: https://pedronveloso.com/how-to-install-an-apk-on-android-tv/

Have you enabled 'unknown sources' from security and restrictions settings?

How can I find all *.js file in directory recursively in Linux?

find /abs/path/ -name '*.js'

Edit: As Brian points out, add -type f if you want only plain files, and not directories, links, etc.

How to convert a column of DataTable to a List

Try this:

static void Main(string[] args)
{
    var dt = new DataTable
    {
        Columns = { { "Lastname",typeof(string) }, { "Firstname",typeof(string) } }
    };
    dt.Rows.Add("Lennon", "John");
    dt.Rows.Add("McCartney", "Paul");
    dt.Rows.Add("Harrison", "George");
    dt.Rows.Add("Starr", "Ringo");

    List<string> s = dt.AsEnumerable().Select(x => x[0].ToString()).ToList();

    foreach(string e in s)
        Console.WriteLine(e);

    Console.ReadLine();
}

ASP.Net MVC: How to display a byte array image from model

This is an modified version of Manoj's answer that I use on a project. Just updated to take a class, html attributes and use the TagBuilder.

    public static IHtmlString Image(this HtmlHelper helper, byte[] image, string imgclass, 
                                     object htmlAttributes = null)
    {
        var builder = new TagBuilder("img");
        builder.MergeAttribute("class", imgclass);
        builder.MergeAttributes(new RouteValueDictionary(htmlAttributes));

        var imageString = image != null ? Convert.ToBase64String(image) : "";
        var img = string.Format("data:image/jpg;base64,{0}", imageString);
        builder.MergeAttribute("src", img);

        return MvcHtmlString.Create(builder.ToString(TagRenderMode.SelfClosing));
    }

Which can be used then as follows:

    @Html.Image(Model.Image, "img-cls", new { width="200", height="200" })

"E: Unable to locate package python-pip" on Ubuntu 18.04

To solve the problem of:

E: Unable to locate package python-pip

you should do this. This works with the python2.7 and you not going to get disappointed by it. follow the steps that are mention below. go to get-pip.py and copy all the code from it.
open the terminal using CTRL + ALT +T

vi get-pip.py

paste the copied code here and then exit from the vi editor by pressing

ESC then :wq => press Enter

lastly, now run the code and see the magic

sudo python get-pip.py

It automatically adds the pip command in your Linux.
you can see the output of my machine

Get current time in milliseconds using C++ and Boost

// Get current date/time in milliseconds.
#include "boost/date_time/posix_time/posix_time.hpp"
namespace pt = boost::posix_time;

int main()
{
     pt::ptime current_date_microseconds = pt::microsec_clock::local_time();

    long milliseconds = current_date_microseconds.time_of_day().total_milliseconds();

    pt::time_duration current_time_milliseconds = pt::milliseconds(milliseconds);

    pt::ptime current_date_milliseconds(current_date_microseconds.date(), 
                                        current_time_milliseconds);

    std::cout << "Microseconds: " << current_date_microseconds 
              << " Milliseconds: " << current_date_milliseconds << std::endl;

    // Microseconds: 2013-Jul-12 13:37:51.699548 Milliseconds: 2013-Jul-12 13:37:51.699000
}

Difference between IISRESET and IIS Stop-Start command

The following was tested for IIS 8.5 and Windows 8.1.

As of IIS 7, Windows recommends restarting IIS via net stop/start. Via the command prompt (as Administrator):

> net stop WAS
> net start W3SVC

net stop WAS will stop W3SVC as well. Then when starting, net start W3SVC will start WAS as a dependency.

Get data from file input in JQuery

 <script src="~/fileupload/fileinput.min.js"></script>
 <link href="~/fileupload/fileinput.min.css" rel="stylesheet" />

Download above files named fileinput add the path i your index page.

<div class="col-sm-9 col-lg-5" style="margin: 0 0 0 8px;">
<input id="uploadFile1" name="file" type="file" class="file-loading"       
 `enter code here`accept=".pdf" multiple>
</div>

<script>
        $("#uploadFile1").fileinput({
            autoReplace: true,
            maxFileCount: 5
        });
</script>

Find if a textbox is disabled or not using jquery

.prop('disabled') will return a Boolean:

var isDisabled = $('textbox').prop('disabled');

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

How do I remove a single file from the staging area (undo git add)?

If you make changes to many tracked files but only want to stage a few of them, doing a

git add .

isn't always favorable (or recommended)- as it stages all the tracked files (some cases where you want to keep changes only to yourself and don't want to stage them to the remote repository).

nor is it ideal doing a bunch of

git add path/to/file1 path/to/file2

if you have a lot of nested directories (which is the case in most projects) - gets annoying

That's when Git GUI is helpful (probably only time I use it). Just open Git GUI, it shows staged and unstaged file sections. Select the files from the staged section that you want to unstage and press

Ctrl+U (for windows)

to unstage them.

Trim spaces from end of a NSString

A simple solution to only trim one end instead of both ends in Objective-C:

@implementation NSString (category)

/// trims the characters at the end
- (NSString *)stringByTrimmingSuffixCharactersInSet:(NSCharacterSet *)characterSet {
    NSUInteger i = self.length;
    while (i > 0 && [characterSet characterIsMember:[self characterAtIndex:i - 1]]) {
        i--;
    }
    return [self substringToIndex:i];
}

@end

And a symmetrical utility for trimming the beginning only:

@implementation NSString (category)

/// trims the characters at the beginning
- (NSString *)stringByTrimmingPrefixCharactersInSet:(NSCharacterSet *)characterSet {
    NSUInteger i = 0;
    while (i < self.length && [characterSet characterIsMember:[self characterAtIndex:i]]) {
        i++;
    }
    return [self substringFromIndex:i];
}

@end

What is the difference between '@' and '=' in directive scope in AngularJS?

This question has been already beaten to death, but I'll share this anyway in case someone else out there is struggling with the horrible mess that is AngularJS scopes. This will cover =, <, @, & and ::. The full write up can be found here.


= establishes a two way binding. Changing the property in the parent will result in change in the child, and vice versa.


< establishes a one way binding, parent to child. Changing the property in the parent will result in change in the child, but changing the child property will not affect the parent property.


@ will assign to the child property the string value of the tag attribute. If the attribute contains an expression, the child property updates whenever the expression evaluates to a different string. For example:

<child-component description="The movie title is {{$ctrl.movie.title}}" />
bindings: {
    description: '@', 
}

Here, the description property in the child scope will be the current value of the expression "The movie title is {{$ctrl.movie.title}}", where movie is an object in the parent scope.


& is a bit tricky, and in fact there seems to be no compelling reason to ever use it. It allows you to evaluate an expression in the parent scope, substituting parameters with variables from the child scope. An example (plunk):

<child-component 
  foo = "myVar + $ctrl.parentVar + myOtherVar"
</child-component>
angular.module('heroApp').component('childComponent', {
  template: "<div>{{  $ctrl.parentFoo({myVar:5, myOtherVar:'xyz'})  }}</div>",
  bindings: {
    parentFoo: '&foo'
  }
});

Given parentVar=10, the expression parentFoo({myVar:5, myOtherVar:'xyz'}) will evaluate to 5 + 10 + 'xyz' and the component will render as:

<div>15xyz</div>

When would you ever want to use this convoluted functionality? & is often used by people to pass to the child scope a callback function in the parent scope. In reality, however, the same effect can be achieved by using '<' to pass the function, which is more straightforward and avoids the awkward curly braces syntax to pass parameters ({myVar:5, myOtherVar:'xyz'}). Consider:

Callback using &:

<child-component parent-foo="$ctrl.foo(bar)"/>
angular.module('heroApp').component('childComponent', {
  template: '<button ng-click="$ctrl.parentFoo({bar:'xyz'})">Call foo in parent</button>',
  bindings: {
    parentFoo: '&'
  }
});

Callback using <:

<child-component parent-foo="$ctrl.foo"/>
angular.module('heroApp').component('childComponent', {
  template: '<button ng-click="$ctrl.parentFoo('xyz')">Call foo in parent</button>',
  bindings: {
    parentFoo: '<'
  }
});

Note that objects (and arrays) are passed by reference to the child scope, not copied. What this means is that even if it's a one-way binding, you are working with the same object in both the parent and the child scope.


To see the different prefixes in action, open this plunk.

One-time binding(initialization) using ::

[Official docs]
Later versions of AngularJS introduce the option to have a one-time binding, where the child scope property is updated only once. This improves performance by eliminating the need to watch the parent property. The syntax is different from above; to declare a one-time binding, you add :: in front of the expression in the component tag:

<child-component 
  tagline = "::$ctrl.tagline">
</child-component>

This will propagate the value of tagline to the child scope without establishing a one-way or two-way binding. Note: if tagline is initially undefined in the parent scope, angular will watch it until it changes and then make a one-time update of the corresponding property in the child scope.

Summary

The table below shows how the prefixes work depending on whether the property is an object, array, string, etc.

How the various isolate scope bindings work

What does the "undefined reference to varName" in C mean?

An initial reaction to this would be to ask and ensure that the two object files are being linked together. This is done at the compile stage by compiling both files at the same time:

gcc -o programName a.c b.c

Or if you want to compile separately, it would be:

gcc -c a.c
gcc -c b.c
gcc -o programName a.o b.o

How to find the day, month and year with moment.js

Just try with:

var check = moment(n.entry.date_entered, 'YYYY/MM/DD');

var month = check.format('M');
var day   = check.format('D');
var year  = check.format('YYYY');

JSFiddle

Getting HTTP code in PHP using curl

curl_getinfo — Get information regarding a specific transfer

Check curl_getinfo

<?php
// Create a curl handle
$ch = curl_init('http://www.yahoo.com/');

// Execute
curl_exec($ch);

// Check if any error occurred
if(!curl_errno($ch))
{
 $info = curl_getinfo($ch);

 echo 'Took ' . $info['total_time'] . ' seconds to send a request to ' . $info['url'];
}

// Close handle
curl_close($ch);

SQL injection that gets around mysql_real_escape_string()

The short answer is yes, yes there is a way to get around mysql_real_escape_string(). #For Very OBSCURE EDGE CASES!!!

The long answer isn't so easy. It's based off an attack demonstrated here.

The Attack

So, let's start off by showing the attack...

mysql_query('SET NAMES gbk');
$var = mysql_real_escape_string("\xbf\x27 OR 1=1 /*");
mysql_query("SELECT * FROM test WHERE name = '$var' LIMIT 1");

In certain circumstances, that will return more than 1 row. Let's dissect what's going on here:

  1. Selecting a Character Set

    mysql_query('SET NAMES gbk');
    

    For this attack to work, we need the encoding that the server's expecting on the connection both to encode ' as in ASCII i.e. 0x27 and to have some character whose final byte is an ASCII \ i.e. 0x5c. As it turns out, there are 5 such encodings supported in MySQL 5.6 by default: big5, cp932, gb2312, gbk and sjis. We'll select gbk here.

    Now, it's very important to note the use of SET NAMES here. This sets the character set ON THE SERVER. If we used the call to the C API function mysql_set_charset(), we'd be fine (on MySQL releases since 2006). But more on why in a minute...

  2. The Payload

    The payload we're going to use for this injection starts with the byte sequence 0xbf27. In gbk, that's an invalid multibyte character; in latin1, it's the string ¿'. Note that in latin1 and gbk, 0x27 on its own is a literal ' character.

    We have chosen this payload because, if we called addslashes() on it, we'd insert an ASCII \ i.e. 0x5c, before the ' character. So we'd wind up with 0xbf5c27, which in gbk is a two character sequence: 0xbf5c followed by 0x27. Or in other words, a valid character followed by an unescaped '. But we're not using addslashes(). So on to the next step...

  3. mysql_real_escape_string()

    The C API call to mysql_real_escape_string() differs from addslashes() in that it knows the connection character set. So it can perform the escaping properly for the character set that the server is expecting. However, up to this point, the client thinks that we're still using latin1 for the connection, because we never told it otherwise. We did tell the server we're using gbk, but the client still thinks it's latin1.

    Therefore the call to mysql_real_escape_string() inserts the backslash, and we have a free hanging ' character in our "escaped" content! In fact, if we were to look at $var in the gbk character set, we'd see:

    ?' OR 1=1 /*

    Which is exactly what the attack requires.

  4. The Query

    This part is just a formality, but here's the rendered query:

    SELECT * FROM test WHERE name = '?' OR 1=1 /*' LIMIT 1
    

Congratulations, you just successfully attacked a program using mysql_real_escape_string()...

The Bad

It gets worse. PDO defaults to emulating prepared statements with MySQL. That means that on the client side, it basically does a sprintf through mysql_real_escape_string() (in the C library), which means the following will result in a successful injection:

$pdo->query('SET NAMES gbk');
$stmt = $pdo->prepare('SELECT * FROM test WHERE name = ? LIMIT 1');
$stmt->execute(array("\xbf\x27 OR 1=1 /*"));

Now, it's worth noting that you can prevent this by disabling emulated prepared statements:

$pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);

This will usually result in a true prepared statement (i.e. the data being sent over in a separate packet from the query). However, be aware that PDO will silently fallback to emulating statements that MySQL can't prepare natively: those that it can are listed in the manual, but beware to select the appropriate server version).

The Ugly

I said at the very beginning that we could have prevented all of this if we had used mysql_set_charset('gbk') instead of SET NAMES gbk. And that's true provided you are using a MySQL release since 2006.

If you're using an earlier MySQL release, then a bug in mysql_real_escape_string() meant that invalid multibyte characters such as those in our payload were treated as single bytes for escaping purposes even if the client had been correctly informed of the connection encoding and so this attack would still succeed. The bug was fixed in MySQL 4.1.20, 5.0.22 and 5.1.11.

But the worst part is that PDO didn't expose the C API for mysql_set_charset() until 5.3.6, so in prior versions it cannot prevent this attack for every possible command! It's now exposed as a DSN parameter.

The Saving Grace

As we said at the outset, for this attack to work the database connection must be encoded using a vulnerable character set. utf8mb4 is not vulnerable and yet can support every Unicode character: so you could elect to use that instead—but it has only been available since MySQL 5.5.3. An alternative is utf8, which is also not vulnerable and can support the whole of the Unicode Basic Multilingual Plane.

Alternatively, you can enable the NO_BACKSLASH_ESCAPES SQL mode, which (amongst other things) alters the operation of mysql_real_escape_string(). With this mode enabled, 0x27 will be replaced with 0x2727 rather than 0x5c27 and thus the escaping process cannot create valid characters in any of the vulnerable encodings where they did not exist previously (i.e. 0xbf27 is still 0xbf27 etc.)—so the server will still reject the string as invalid. However, see @eggyal's answer for a different vulnerability that can arise from using this SQL mode.

Safe Examples

The following examples are safe:

mysql_query('SET NAMES utf8');
$var = mysql_real_escape_string("\xbf\x27 OR 1=1 /*");
mysql_query("SELECT * FROM test WHERE name = '$var' LIMIT 1");

Because the server's expecting utf8...

mysql_set_charset('gbk');
$var = mysql_real_escape_string("\xbf\x27 OR 1=1 /*");
mysql_query("SELECT * FROM test WHERE name = '$var' LIMIT 1");

Because we've properly set the character set so the client and the server match.

$pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$pdo->query('SET NAMES gbk');
$stmt = $pdo->prepare('SELECT * FROM test WHERE name = ? LIMIT 1');
$stmt->execute(array("\xbf\x27 OR 1=1 /*"));

Because we've turned off emulated prepared statements.

$pdo = new PDO('mysql:host=localhost;dbname=testdb;charset=gbk', $user, $password);
$stmt = $pdo->prepare('SELECT * FROM test WHERE name = ? LIMIT 1');
$stmt->execute(array("\xbf\x27 OR 1=1 /*"));

Because we've set the character set properly.

$mysqli->query('SET NAMES gbk');
$stmt = $mysqli->prepare('SELECT * FROM test WHERE name = ? LIMIT 1');
$param = "\xbf\x27 OR 1=1 /*";
$stmt->bind_param('s', $param);
$stmt->execute();

Because MySQLi does true prepared statements all the time.

Wrapping Up

If you:

  • Use Modern Versions of MySQL (late 5.1, all 5.5, 5.6, etc) AND mysql_set_charset() / $mysqli->set_charset() / PDO's DSN charset parameter (in PHP = 5.3.6)

OR

  • Don't use a vulnerable character set for connection encoding (you only use utf8 / latin1 / ascii / etc)

You're 100% safe.

Otherwise, you're vulnerable even though you're using mysql_real_escape_string()...

Setting user agent of a java URLConnection

its work for me set the User-Agent in the addRequestProperty.

URL url = new URL(<URL>);
HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
httpConn.addRequestProperty("User-Agent","Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:56.0) Gecko/20100101 Firefox/56.0");

Function or sub to add new row and data to table

Minor variation on Geoff's answer.

New Data in Array:

Sub AddDataRow(tableName As String, NewData As Variant)
    Dim sheet As Worksheet
    Dim table As ListObject
    Dim col As Integer
    Dim lastRow As Range

    Set sheet = Range(tableName).Parent
    Set table = sheet.ListObjects.Item(tableName)

    'First check if the last row is empty; if not, add a row
    If table.ListRows.Count > 0 Then
        Set lastRow = table.ListRows(table.ListRows.Count).Range
        If Application.CountBlank(lastRow) < lastRow.Columns.Count Then
            table.ListRows.Add
        End If
    End If

    'Iterate through the last row and populate it with the entries from values()
    Set lastRow = table.ListRows(table.ListRows.Count).Range
    For col = 1 To lastRow.Columns.Count
        If col <= UBound(NewData) + 1 Then lastRow.Cells(1, col) = NewData(col - 1)
    Next col
End Sub

New Data in Horizontal Range:

Sub AddDataRow(tableName As String, NewData As Range)
    Dim sheet As Worksheet
    Dim table As ListObject
    Dim col As Integer
    Dim lastRow As Range

    Set sheet = Range(tableName).Parent
    Set table = sheet.ListObjects.Item(tableName)

    'First check if the last table row is empty; if not, add a row
    If table.ListRows.Count > 0 Then
        Set lastRow = table.ListRows(table.ListRows.Count).Range
        If Application.CountBlank(lastRow) < lastRow.Columns.Count Then
            table.ListRows.Add
        End If
    End If

    'Copy NewData to new table record
    Set lastRow = table.ListRows(table.ListRows.Count).Range
    lastRow.Value = NewData.Value
End Sub

Refresh Part of Page (div)

Let's assume that you have 2 divs inside of your html file.

<div id="div1">some text</div>
<div id="div2">some other text</div>

The java program itself can't update the content of the html file because the html is related to the client, meanwhile java is related to the back-end.

You can, however, communicate between the server (the back-end) and the client.

What we're talking about is AJAX, which you achieve using JavaScript, I recommend using jQuery which is a common JavaScript library.

Let's assume you want to refresh the page every constant interval, then you can use the interval function to repeat the same action every x time.

setInterval(function()
{
    alert("hi");
}, 30000);

You could also do it like this:

setTimeout(foo, 30000);

Whereea foo is a function.

Instead of the alert("hi") you can perform the AJAX request, which sends a request to the server and receives some information (for example the new text) which you can use to load into the div.

A classic AJAX looks like this:

var fetch = true;
var url = 'someurl.java';
$.ajax(
{
    // Post the variable fetch to url.
    type : 'post',
    url : url,
    dataType : 'json', // expected returned data format.
    data : 
    {
        'fetch' : fetch // You might want to indicate what you're requesting.
    },
    success : function(data)
    {
        // This happens AFTER the backend has returned an JSON array (or other object type)
        var res1, res2;

        for(var i = 0; i < data.length; i++)
        {
            // Parse through the JSON array which was returned.
            // A proper error handling should be added here (check if
            // everything went successful or not)

            res1 = data[i].res1;
            res2 = data[i].res2;

            // Do something with the returned data
            $('#div1').html(res1);
        }
    },
    complete : function(data)
    {
        // do something, not critical.
    }
});

Wherea the backend is able to receive POST'ed data and is able to return a data object of information, for example (and very preferrable) JSON, there are many tutorials out there with how to do so, GSON from Google is something that I used a while back, you could take a look into it.

I'm not professional with Java POST receiving and JSON returning of that sort so I'm not going to give you an example with that but I hope this is a decent start.

Border for an Image view in Android?

This has been used above but not mentioned exclusively.

setCropToPadding(boolean);

If true, the image will be cropped to fit within its padding.

This will make the ImageView source to fit within the padding's added to its background.

Via XML it can be done as below-

android:cropToPadding="true"

Saving plots (AxesSubPlot) generated from python pandas with matplotlib's savefig

You can use ax.figure.savefig(), as suggested in a comment on the question:

import pandas as pd

df = pd.DataFrame([0, 1])
ax = df.plot.line()
ax.figure.savefig('demo-file.pdf')

This has no practical benefit over ax.get_figure().savefig() as suggested in other answers, so you can pick the option you find the most aesthetically pleasing. In fact, get_figure() simply returns self.figure:

# Source from snippet linked above
def get_figure(self):
    """Return the `.Figure` instance the artist belongs to."""
    return self.figure

Using momentjs to convert date to epoch then back to date

There are a few things wrong here:

  • First, terminology. "Epoch" refers to the starting point of something. The "Unix Epoch" is Midnight, January 1st 1970 UTC. You can't convert an arbitrary "date string to epoch". You probably meant "Unix Time", which is often erroneously called "Epoch Time".

  • .unix() returns Unix Time in whole seconds, but the default moment constructor accepts a timestamp in milliseconds. You should instead use .valueOf() to return milliseconds. Note that calling .unix()*1000 would also work, but it would result in a loss of precision.

  • You're parsing a string without providing a format specifier. That isn't a good idea, as values like 1/2/2014 could be interpreted as either February 1st or as January 2nd, depending on the locale of where the code is running. (This is also why you get the deprecation warning in the console.) Instead, provide a format string that matches the expected input, such as:

    moment("10/15/2014 9:00", "M/D/YYYY H:mm")
    
  • .calendar() has a very specific use. If you are near to the date, it will return a value like "Today 9:00 AM". If that's not what you expected, you should use the .format() function instead. Again, you may want to pass a format specifier.

  • To answer your questions in comments, No - you don't need to call .local() or .utc().

Putting it all together:

var ts = moment("10/15/2014 9:00", "M/D/YYYY H:mm").valueOf();
var m = moment(ts);
var s = m.format("M/D/YYYY H:mm");
alert("Values are: ts = " + ts + ", s = " + s);

On my machine, in the US Pacific time zone, it results in:

Values are: ts = 1413388800000, s = 10/15/2014 9:00

Since the input value is interpreted in terms of local time, you will get a different value for ts if you are in a different time zone.

Also note that if you really do want to work with whole seconds (possibly losing precision), moment has methods for that as well. You would use .unix() to return the timestamp in whole seconds, and moment.unix(ts) to parse it back to a moment.

var ts = moment("10/15/2014 9:00", "M/D/YYYY H:mm").unix();
var m = moment.unix(ts);

R object identification

I usually start out with some combination of:

typeof(obj)
class(obj)
sapply(obj, class)
sapply(obj, attributes)
attributes(obj)
names(obj)

as appropriate based on what's revealed. For example, try with:

obj <- data.frame(a=1:26, b=letters)
obj <- list(a=1:26, b=letters, c=list(d=1:26, e=letters))
data(cars)
obj <- lm(dist ~ speed, data=cars)

..etc.

If obj is an S3 or S4 object, you can also try methods or showMethods, showClass, etc. Patrick Burns' R Inferno has a pretty good section on this (sec #7).

EDIT: Dirk and Hadley mention str(obj) in their answers. It really is much better than any of the above for a quick and even detailed peek into an object.

How to select a range of the second row to the last row

Try this:

Dim Lastrow As Integer
Lastrow = ActiveSheet.Cells(Rows.Count, 1).End(xlUp).Row

Range("A2:L" & Lastrow).Select

Let's pretend that the value of Lastrow is 50. When you use the following:

Range("A2:L2" & Lastrow).Select

Then it is selecting a range from A2 to L250.

Difference between <input type='submit' /> and <button type='submit'>text</button>

Not sure where you get your legends from but:

Submit button with <button>

As with:

<button type="submit">(html content)</button>

IE6 will submit all text for this button between the tags, other browsers will only submit the value. Using <button> gives you more layout freedom over the design of the button. In all its intents and purposes, it seemed excellent at first, but various browser quirks make it hard to use at times.

In your example, IE6 will send text to the server, while most other browsers will send nothing. To make it cross-browser compatible, use <button type="submit" value="text">text</button>. Better yet: don't use the value, because if you add HTML it becomes rather tricky what is received on server side. Instead, if you must send an extra value, use a hidden field.

Button with <input>

As with:

<input type="button" />

By default, this does next to nothing. It will not even submit your form. You can only place text on the button and give it a size and a border by means of CSS. Its original (and current) intent was to execute a script without the need to submit the form to the server.

Normal submit button with <input>

As with:

<input type="submit" />

Like the former, but actually submits the surrounding form.

Image submit button with <input>

As with:

<input type="image" />

Like the former (submit), it will also submit a form, but you can use any image. This used to be the preferred way to use images as buttons when a form needed submitting. For more control, <button> is now used. This can also be used for server side image maps but that's a rarity these days. When you use the usemap-attribute and (with or without that attribute), the browser will send the mouse-pointer X/Y coordinates to the server (more precisely, the mouse-pointer location inside the button of the moment you click it). If you just ignore these extras, it is nothing more than a submit button disguised as an image.

There are some subtle differences between browsers, but all will submit the value-attribute, except for the <button> tag as explained above.

How to create enum like type in TypeScript?

As of TypeScript 0.9 (currently an alpha release) you can use the enum definition like this:

enum TShirtSize {
  Small,
  Medium,
  Large
}

var mySize = TShirtSize.Large;

By default, these enumerations will be assigned 0, 1 and 2 respectively. If you want to explicitly set these numbers, you can do so as part of the enum declaration.

Listing 6.2 Enumerations with explicit members

enum TShirtSize {
  Small = 3,
  Medium = 5,
  Large = 8
}

var mySize = TShirtSize.Large;

Both of these examples lifted directly out of TypeScript for JavaScript Programmers.

Note that this is different to the 0.8 specification. The 0.8 specification looked like this - but it was marked as experimental and likely to change, so you'll have to update any old code:

Disclaimer - this 0.8 example would be broken in newer versions of the TypeScript compiler.

enum TShirtSize {
  Small: 3,
  Medium: 5,
  Large: 8
}

var mySize = TShirtSize.Large;

Android Material and appcompat Manifest merger failed

If you do not intend to migrate to AndroidX follow the below steps

  1. In terminal type gradlew app:dependencies
  2. After dependencies are shown in the window press Ctrl+f and type androidX
  3. You will find all the dependencies which are using androidx lib internally you may have to downgrade that or use alternative for that to ensure it is no longer using androidX libs internally.

APT command line interface-like yes/no input?

There is a function strtobool in Python's standard library: http://docs.python.org/2/distutils/apiref.html?highlight=distutils.util#distutils.util.strtobool

You can use it to check user's input and transform it to True or False value.

How to pass multiple arguments in processStartInfo?

System.Diagnostics.Process process = new System.Diagnostics.Process();
System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Normal;
startInfo.FileName = "cmd.exe";
startInfo.Arguments = @"/c -sk server -sky exchange -pe -n CN=localhost -ir LocalMachine -is Root -ic MyCA.cer -sr LocalMachine -ss My MyAdHocTestCert.cer"

use /c as a cmd argument to close cmd.exe once its finish processing your commands

SQL Server 2008 R2 Express permissions -- cannot create database or modify users

In SSMS 2012, you'll have to use:

To enable single-user mode, in SQL instance properties, DO NOT go to "Advance" tag, there is already a "Startup Parameters" tag.

  1. Add "-m;" into parameters;
  2. Restart the service and logon this SQL instance by using windows authentication;
  3. The rest steps are same as above. Change your windows user account permission in security or reset SA account password.
  4. Last, remove "-m" parameter from "startup parameters";

How to convert a Bitmap to Drawable in android?

covert bit map to drawable in sketchware app using code

    android.graphics.drawable.BitmapDrawable d = new android.graphics.drawable.BitmapDrawable(getResources(), bitmap);

Find out where MySQL is installed on Mac OS X

If you've installed with the dmg, you can also go to the Mac "System Preferences" menu, click on "MySql" and then on the configuration tab to see the location of all MySql directories.

Reference: https://dev.mysql.com/doc/refman/8.0/en/osx-installation-prefpane.html

Correct way to work with vector of arrays

Every element of your vector is a float[4], so when you resize every element needs to default initialized from a float[4]. I take it you tried to initialize with an int value like 0?

Try:

static float zeros[4] = {0.0, 0.0, 0.0, 0.0};
myvector.resize(newsize, zeros);

Difference between Activity and FragmentActivity

A FragmentActivity is a subclass of Activity that was built for the Android Support Package.

The FragmentActivity class adds a couple new methods to ensure compatibility with older versions of Android, but other than that, there really isn't much of a difference between the two. Just make sure you change all calls to getLoaderManager() and getFragmentManager() to getSupportLoaderManager() and getSupportFragmentManager() respectively.

sql query to get earliest date

Try

select * from dataset
where id = 2
order by date limit 1

Been a while since I did sql, so this might need some tweaking.

How to yum install Node.JS on Amazon Linux

As others mentioned using epel gives a really outdated version, here is a little script I just wrote instead to add to the CI pipeline or pass it to ec2 user-data to install the latest version of node, simply replace the version with what you want, and the appropriate distro of Linux you are using.

The following example is for amazon-Linux-2-AMI

#!/bin/bash

version='v14.13.1'
distro='linux-x64'
package_name="node-$version-$distro"
package_location="/usr/local/lib/"

curl -O https://nodejs.org/download/release/latest/$package_name.tar.gz
tar -xvf $package_name.tar.gz -C $package_location
rm -rfv $package_name.tar.gz

echo "export PATH=$package_location/$package_name/bin:\$PATH" >> ~/.profile

if you want to test it in the same shell simply run

. ~/.profile

While, Do While, For loops in Assembly Language (emu8086)

For-loops:

For-loop in C:

for(int x = 0; x<=3; x++)
{
    //Do something!
}

The same loop in 8086 assembler:

        xor cx,cx   ; cx-register is the counter, set to 0
loop1   nop         ; Whatever you wanna do goes here, should not change cx
        inc cx      ; Increment
        cmp cx,3    ; Compare cx to the limit
        jle loop1   ; Loop while less or equal

That is the loop if you need to access your index (cx). If you just wanna to something 0-3=4 times but you do not need the index, this would be easier:

        mov cx,4    ; 4 iterations
loop1   nop         ; Whatever you wanna do goes here, should not change cx
        loop loop1  ; loop instruction decrements cx and jumps to label if not 0

If you just want to perform a very simple instruction a constant amount of times, you could also use an assembler-directive which will just hardcore that instruction

times 4 nop

Do-while-loops

Do-while-loop in C:

int x=1;
do{
    //Do something!
}
while(x==1)

The same loop in assembler:

        mov ax,1
loop1   nop         ; Whatever you wanna do goes here
        cmp ax,1    ; Check wether cx is 1
        je loop1    ; And loop if equal

While-loops

While-loop in C:

while(x==1){
    //Do something
}

The same loop in assembler:

        jmp loop1   ; Jump to condition first
cloop1  nop         ; Execute the content of the loop
loop1   cmp ax,1    ; Check the condition
        je cloop1   ; Jump to content of the loop if met

For the for-loops you should take the cx-register because it is pretty much standard. For the other loop conditions you can take a register of your liking. Of course replace the no-operation instruction with all the instructions you wanna perform in the loop.

How to embed image or picture in jupyter notebook, either from a local machine or from a web resource?

Insert the image directly in the Jupyter notebook.

Note: You should have a local copy of the image on your computer

You can insert the image in the Jupyter notebook itself. This way you don't need to keep the image separately in the folder.

Steps:

  1. Convert the cell to markdown by:

    • pressing M on the selected cell
      OR
    • From menu bar, Cell > Cell Type > Markdown.
      (Note: It's important to convert the cell to Markdown, otherwise the "Insert Image" option in Step 2 will not be active)
  2. Now go to menu bar and select Edit -> Insert Image.

  3. Select image from your disk and upload.

  4. Press Ctrl+Enter or Shift+Enter.

This will make the image as part of the notebook and you don't need to upload in the directory or Github. I feel this looks more clean and not prone to broken URL issue.

Drawing rotated text on a HTML5 canvas

Funkodebat posted a great solution which I have referenced many times. Still, I find myself writing my own working model each time I need this. So, here is my working model... with some added clarity.

First of all, the height of the text is equal to the pixel font size. Now, this was something I read a while ago, and it has worked out in my calculations. I'm not sure if this works with all fonts, but it seems to work with Arial, sans-serif.

Also, to make sure that you fit all of the text in your canvas (and don't trim the tails off of your "p"'s) you need to set context.textBaseline*.

You will see in the code that we are rotating the text about its center. To do this, we need to set context.textAlign = "center" and the context.textBaseline to bottom, otherwise, we trim off parts of our text.

Why resize the canvas? I usually have a canvas that isn't appended to the page. I use it to draw all of my rotated text, then I draw it onto another canvas which I display. For example, you can use this canvas to draw all of the labels for a chart (one by one) and draw the hidden canvas onto the chart canvas where you need the label (context.drawImage(hiddenCanvas, 0, 0);).

IMPORTANT NOTE: Set your font before measuring your text, and re-apply all of your styling to the context after resizing your canvas. A canvas's context is completely reset when the canvas is resized.

Hope this helps!

_x000D_
_x000D_
var c = document.getElementById("myCanvas");_x000D_
var ctx = c.getContext("2d");_x000D_
var font, text, x, y;_x000D_
_x000D_
text = "Mississippi";_x000D_
_x000D_
//Set font size before measuring_x000D_
font = 20;_x000D_
ctx.font = font + 'px Arial, sans-serif';_x000D_
//Get width of text_x000D_
var metrics = ctx.measureText(text);_x000D_
//Set canvas dimensions_x000D_
c.width = font;//The height of the text. The text will be sideways._x000D_
c.height = metrics.width;//The measured width of the text_x000D_
//After a canvas resize, the context is reset. Set the font size again_x000D_
ctx.font = font + 'px Arial';_x000D_
//Set the drawing coordinates_x000D_
x = font/2;_x000D_
y = metrics.width/2;_x000D_
//Style_x000D_
ctx.fillStyle = 'black';_x000D_
ctx.textAlign = 'center';_x000D_
ctx.textBaseline = "bottom";_x000D_
//Rotate the context and draw the text_x000D_
ctx.save();_x000D_
ctx.translate(x, y);_x000D_
ctx.rotate(-Math.PI / 2);_x000D_
ctx.fillText(text, 0, font / 2);_x000D_
ctx.restore();
_x000D_
<canvas id="myCanvas" width="300" height="150" style="border:1px solid #d3d3d3;">
_x000D_
_x000D_
_x000D_

MySQL FULL JOIN?

Various types of joins, for illustration

There are a couple of methods for full mysql FULL [OUTER] JOIN.

  1. UNION a left join and right join. UNION will remove duplicates by performing an ORDER BY operation. So depending on your data, it may not be performant.

     SELECT * FROM A 
       LEFT JOIN B ON A.key = B.key 
    
     UNION 
    
     SELECT * FROM A 
       RIGHT JOIN B ON A.key = B.key
    
  2. UNION ALL a left join and right EXCLUDING join (that's the lower right figure in the diagram). UNION ALL will not remove duplicates. Sometimes this might be the behaviour that you want. You also want to use RIGHT EXCLUDING to avoid duplicating common records from selection A and selection B - i.e Left join has already included common records from selection B, lets not repeat that again with the right join.

     SELECT * FROM A 
       LEFT JOIN B ON A.key = B.key 
    
     UNION ALL
    
     SELECT * FROM A 
       RIGHT JOIN B ON A.key = B.key
       WHERE A.key IS NULL
    

How to remove the last character from a bash grep output

I'd use sed 's/;$//'. eg:

COMPANY_NAME=`cat file.txt | grep "company_name" | cut -d '=' -f 2 | sed 's/;$//'`

How can I run another application within a panel of my C# program?

Using the win32 API it is possible to "eat" another application. Basically you get the top window for that application and set it's parent to be the handle of the panel you want to place it in. If you don't want the MDI style effect you also have to adjust the window style to make it maximised and remove the title bar.

Here is some simple sample code where I have a form with a button and a panel:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Threading;

namespace WindowsFormsApplication2
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Process p = Process.Start("notepad.exe");
            Thread.Sleep(500); // Allow the process to open it's window
            SetParent(p.MainWindowHandle, panel1.Handle);
        }

        [DllImport("user32.dll")]
        static extern IntPtr SetParent(IntPtr hWndChild, IntPtr hWndNewParent);
    }
}

I just saw another example where they called WaitForInputIdle instead of sleeping. So the code would be like this:

Process p = Process.Start("notepad.exe");
p.WaitForInputIdle();
SetParent(p.MainWindowHandle, panel1.Handle);

The Code Project has a good article one the whole process: Hosting EXE Applications in a WinForm project

How do I compare a value to a backslash?

Try like this:

if message.value[0] == "/" or message.value[0] == "\\":
  do_stuff

Does Spring Data JPA have any way to count entites using method name resolving?

@Autowired
private UserRepository userRepository;

@RequestMapping("/user/count")
private Long getNumberOfUsers(){
    return userRepository.count();
}

Padding zeros to the left in postgreSQL

The to_char() function is there to format numbers:

select to_char(column_1, 'fm000') as column_2
from some_table;

The fm prefix ("fill mode") avoids leading spaces in the resulting varchar. The 000 simply defines the number of digits you want to have.

psql (9.3.5)
Type "help" for help.

postgres=> with sample_numbers (nr) as (
postgres(>     values (1),(11),(100)
postgres(> )
postgres-> select to_char(nr, 'fm000')
postgres-> from sample_numbers;
 to_char
---------
 001
 011
 100
(3 rows)

postgres=>

For more details on the format picture, please see the manual:
http://www.postgresql.org/docs/current/static/functions-formatting.html

Why do we need to use flatMap?

It's not an array of arrays. It's an observable of observable(s).

The following returns an observable stream of string.

requestStream
  .map(function(requestUrl) {
    return requestUrl;
  });

While this returns an observable stream of observable stream of json

requestStream
  .map(function(requestUrl) {
    return Rx.Observable.fromPromise(jQuery.getJSON(requestUrl));
  });

flatMap flattens the observable automatically for us so we can observe the json stream directly

Use a URL to link to a Google map with a marker on it

In May 2017 Google launched the official Google Maps URLs documentation. The Google Maps URLs introduces universal cross-platform syntax that you can use in your applications.

Have a look at the following document:

https://developers.google.com/maps/documentation/urls/guide

You can use URLs in search, directions, map and street view modes.

For example, to show the marker at specified position you can use the following URL:

https://www.google.com/maps/search/?api=1&query=36.26577,-92.54324

For further details please read aforementioned documentation.

You can also file feature requests for this API in Google issue tracker.

Hope this helps!

Wait .5 seconds before continuing code VB.net

The problem with Threading.Thread.SLeep(2000) is that it executes first in my VB.Net program. This

Imports VB = Microsoft.VisualBasic

Public Sub wait(ByVal seconds As Single)
    Static start As Single
    start = VB.Timer()
    Do While VB.Timer() < start + seconds
        System.Windows.Forms.Application.DoEvents()
    Loop
End Sub

worked flawlessly.

Provide schema while reading csv file as a dataframe

Try the below code, you need not specify the schema. When you give inferSchema as true it should take it from your csv file.

val pagecount = sqlContext.read.format("csv")
  .option("delimiter"," ").option("quote","")
  .option("header", "true")
  .option("inferSchema", "true")
  .load("dbfs:/databricks-datasets/wikipedia-datasets/data-001/pagecounts/sample/pagecounts-20151124-170000")

If you want to manually specify the schema, you can do it as below:

import org.apache.spark.sql.types._

val customSchema = StructType(Array(
  StructField("project", StringType, true),
  StructField("article", StringType, true),
  StructField("requests", IntegerType, true),
  StructField("bytes_served", DoubleType, true))
)

val pagecount = sqlContext.read.format("csv")
  .option("delimiter"," ").option("quote","")
  .option("header", "true")
  .schema(customSchema)
  .load("dbfs:/databricks-datasets/wikipedia-datasets/data-001/pagecounts/sample/pagecounts-20151124-170000")

Declaring and using MySQL varchar variables

If you are using phpmyadmin to add new routine then don't forget to wrap your code between BEGIN and ENDenter image description here

What's wrong with foreign keys?

Reasons to use Foreign Keys:

  • you won't get Orphaned Rows
  • you can get nice "on delete cascade" behavior, automatically cleaning up tables
  • knowing about the relationships between tables in the database helps the Optimizer plan your queries for most efficient execution, since it is able to get better estimates on join cardinality.
  • FKs give a pretty big hint on what statistics are most important to collect on the database, which in turn leads to better performance
  • they enable all kinds of auto-generated support -- ORMs can generate themselves, visualization tools will be able to create nice schema layouts for you, etc.
  • someone new to the project will get into the flow of things faster since otherwise implicit relationships are explicitly documented

Reasons not to use Foreign Keys:

  • you are making the DB work extra on every CRUD operation because it has to check FK consistency. This can be a big cost if you have a lot of churn
  • by enforcing relationships, FKs specify an order in which you have to add/delete things, which can lead to refusal by the DB to do what you want. (Granted, in such cases, what you are trying to do is create an Orphaned Row, and that's not usually a good thing). This is especially painful when you are doing large batch updates, and you load up one table before another, with the second table creating consistent state (but should you be doing that sort of thing if there is a possibility that the second load fails and your database is now inconsistent?).
  • sometimes you know beforehand your data is going to be dirty, you accept that, and you want the DB to accept it
  • you are just being lazy :-)

I think (I am not certain!) that most established databases provide a way to specify a foreign key that is not enforced, and is simply a bit of metadata. Since non-enforcement wipes out every reason not to use FKs, you should probably go that route if any of the reasons in the second section apply.

List View Filter Android

Implement your adapter Filterable:

public class vJournalAdapter extends ArrayAdapter<JournalModel> implements Filterable{
private ArrayList<JournalModel> items;
private Context mContext;
....

then create your Filter class:

private class JournalFilter extends Filter{

    @Override
    protected FilterResults performFiltering(CharSequence constraint) {
        FilterResults result = new FilterResults();
        List<JournalModel> allJournals = getAllJournals();
        if(constraint == null || constraint.length() == 0){

            result.values = allJournals;
            result.count = allJournals.size();
        }else{
            ArrayList<JournalModel> filteredList = new ArrayList<JournalModel>();
            for(JournalModel j: allJournals){
                if(j.source.title.contains(constraint))
                    filteredList.add(j);
            }
            result.values = filteredList;
            result.count = filteredList.size();
        }

        return result;
    }
    @SuppressWarnings("unchecked")
    @Override
    protected void publishResults(CharSequence constraint, FilterResults results) {
        if (results.count == 0) {
            notifyDataSetInvalidated();
        } else {
            items = (ArrayList<JournalModel>) results.values;
            notifyDataSetChanged();
        }
    }

}

this way, your adapter is Filterable, you can pass filter item to adapter's filter and do the work. I hope this will be helpful.

How do MySQL indexes work?

Adding some visual representation to the list of answers. enter image description here

MySQL uses an extra layer of indirection: secondary index records point to primary index records, and the primary index itself holds the on-disk row locations. If a row offset changes, only the primary index needs to be updated.

Caveat: Disk data structure looks flat in the diagram but actually is a B+ tree.

Source: link

How to check whether a select box is empty using JQuery/Javascript

One correct way to get selected value would be

var selected_value = $('#fruit_name').val()

And then you should do

if(selected_value) { ... }

How to turn off caching on Firefox?

The Web Developer Toolbar has an option to disable caching which makes it very easy to turn it on and off when you need it.

How to print full stack trace in exception?

Use a function like this:

    public static string FlattenException(Exception exception)
    {
        var stringBuilder = new StringBuilder();

        while (exception != null)
        {
            stringBuilder.AppendLine(exception.Message);
            stringBuilder.AppendLine(exception.StackTrace);

            exception = exception.InnerException;
        }

        return stringBuilder.ToString();
    }

Then you can call it like this:

try
{
    // invoke code above
}
catch(MyCustomException we)
{
    Debug.Writeline(FlattenException(we));
}

How to get folder path for ClickOnce application

path is pointing to a subfolder under c:\Documents & Settings

That's right. ClickOnce applications are installed under the profile of the user who installed them. Did you take the path that retrieving the info from the executing assembly gave you, and go check it out?

On windows Vista and Windows 7, you will find the ClickOnce cache here:

c:\users\username\AppData\Local\Apps\2.0\obfuscatedfoldername\obfuscatedfoldername

On Windows XP, you will find it here:

C:\Documents and Settings\username\LocalSettings\Apps\2.0\obfuscatedfoldername\obfuscatedfoldername

How do I get AWS_ACCESS_KEY_ID for Amazon?

It is very dangerous to create an access_key_id in "My Account ==> Security Credentials". Because the key has all authority. Please create "IAM" user and attach only some policies you need.

ASP.NET: HTTP Error 500.19 – Internal Server Error 0x8007000d

I understand that this error can occur because of many different reasons. In my case it was because I uninstalled WSUS service from Server Roles and the whole IIS went down. After doing a bit of research I found that uninstalling WSUS removes a few dlls which are used to do http compression. Since those dlls were missing and the IIS was still looking for them I did a reset using the following command in CMD:

appcmd set config -section:system.webServer/httpCompression /-[name='xpress']

Bingo! The problem is sorted now. Dont forget to run it as an administrator. You might also need to do "iisreset" as well. Just in case.

Hope it helps others. Cheers

Best XML Parser for PHP

the crxml parser is a real easy to parser.

This class has got a search function, which takes a node name with any namespace as an argument. It searches the xml for the node and prints out the access statement to access that node using this class. This class also makes xml generation very easy.

you can download this class at

http://freshmeat.net/projects/crxml

or from phpclasses.org

http://www.phpclasses.org/package/6769-PHP-Manipulate-XML-documents-as-array.html

Regular expression to extract text between square brackets

if you want fillter only small alphabet letter between square bracket a-z

(\[[a-z]*\])

if you want small and caps letter a-zA-Z

(\[[a-zA-Z]*\]) 

if you want small caps and number letter a-zA-Z0-9

(\[[a-zA-Z0-9]*\]) 

if you want everything between square bracket

if you want text , number and symbols

(\[.*\])

Why should text files end with a newline?

Why should (text) files end with a newline?

As well expressed by many, because:

  1. Many programs do not behave well, or fail without it.

  2. Even programs that well handle a file lack an ending '\n', the tool's functionality may not meet the user's expectations - which can be unclear in this corner case.

  3. Programs rarely disallow final '\n' (I do not know of any).


Yet this begs the next question:

What should code do about text files without a newline?

  1. Most important - Do not write code that assumes a text file ends with a newline. Assuming a file conforms to a format leads to data corruption, hacker attacks and crashes. Example:

    // Bad code
    while (fgets(buf, sizeof buf, instream)) {
      // What happens if there is no \n, buf[] is truncated leading to who knows what
      buf[strlen(buf) - 1] = '\0';  // attempt to rid trailing \n
      ...
    }
    
  2. If the final trailing '\n' is needed, alert the user to its absence and the action taken. IOWs, validate the file's format. Note: This may include a limit to the maximum line length, character encoding, etc.

  3. Define clearly, document, the code's handling of a missing final '\n'.

  4. Do not, as possible, generate a file the lacks the ending '\n'.

NoClassDefFoundError on Maven dependency

You have to make classpath in pom file for your dependency. Therefore you have to copy all the dependencies into one place.

Check my blog.

<build>
  <plugins>
    <plugin>
      <groupId>org.apache.maven.plugins</groupId>
      <artifactId>maven-dependency-plugin</artifactId>
      <version>2.1</version>
      <executions>
        <execution>
          <id>copy-dependencies</id>
          <phase>package</phase>
          <goals>
            <goal>copy-dependencies</goal>
          </goals>
          <configuration>
            <outputDirectory>${project.build.directory}/lib</outputDirectory>
            <overWriteReleases>false</overWriteReleases>
            <overWriteSnapshots>false</overWriteSnapshots>
            <overWriteIfNewer>true</overWriteIfNewer>
          </configuration>
        </execution>
      </executions>
    </plugin>
    <plugin>
      <groupId>org.apache.maven.plugins</groupId>
      <artifactId>maven-jar-plugin</artifactId>
      <version>2.4</version>
      <configuration>
        <archive>
          <manifest>
            <addClasspath>true</addClasspath>
            <classpathPrefix>lib/</classpathPrefix>
            <mainClass>$fullqualified path to your main Class</mainClass>
          </manifest>
        </archive>
      </configuration>
    </plugin>
  </plugins>
</build>

Map<String, String>, how to print both the "key string" and "value string" together

There are various ways to achieve this. Here are three.

    Map<String, String> map = new HashMap<String, String>();
    map.put("key1", "value1");
    map.put("key2", "value2");
    map.put("key3", "value3");

    System.out.println("using entrySet and toString");
    for (Entry<String, String> entry : map.entrySet()) {
        System.out.println(entry);
    }
    System.out.println();

    System.out.println("using entrySet and manual string creation");
    for (Entry<String, String> entry : map.entrySet()) {
        System.out.println(entry.getKey() + "=" + entry.getValue());
    }
    System.out.println();

    System.out.println("using keySet");
    for (String key : map.keySet()) {
        System.out.println(key + "=" + map.get(key));
    }
    System.out.println();

Output

using entrySet and toString
key1=value1
key2=value2
key3=value3

using entrySet and manual string creation
key1=value1
key2=value2
key3=value3

using keySet
key1=value1
key2=value2
key3=value3

How can I create a border around an Android LinearLayout?

Try this:

For example, let's define res/drawable/my_custom_background.xml as:

(create this layout in your drawable folder) layout_border.xml

  <?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item>
        <shape android:shape="rectangle">
            <stroke android:width="2dp" android:height="2dp"
                android:color="#FF0000" />
            <solid android:color="#000000" />
            <padding android:left="1dp" android:top="1dp" android:right="1dp"
                android:bottom="1dp" />

            <corners android:radius="1dp" android:bottomRightRadius="5dp"
                android:bottomLeftRadius="0dp" android:topLeftRadius="5dp"
                android:topRightRadius="0dp" />
        </shape>
    </item>

</layer-list>

main.xml

<LinearLayout 
    android:layout_gravity="center"
    android:layout_width="200dp" 
    android:layout_height="200dp"   
    android:background="@drawable/layout_border" />
</LinearLayout>

LINQ to Entities does not recognize the method

I got the same error in this code:

 var articulos_en_almacen = xx.IV00102.Where(iv => alm_x_suc.Exists(axs => axs.almacen == iv.LOCNCODE.Trim())).Select(iv => iv.ITEMNMBR.Trim()).ToList();

this was the exactly error:

System.NotSupportedException: 'LINQ to Entities does not recognize the method 'Boolean Exists(System.Predicate`1[conector_gp.Models.almacenes_por_sucursal])' method, and this method cannot be translated into a store expression.'

I solved this way:

var articulos_en_almacen = xx.IV00102.ToList().Where(iv => alm_x_suc.Exists(axs => axs.almacen == iv.LOCNCODE.Trim())).Select(iv => iv.ITEMNMBR.Trim()).ToList();

I added a .ToList() before my table, this decouple the Entity and linq code, and avoid my next linq expression be translated

NOTE: this solution isn't optimal, because avoid entity filtering, and simply loads all table into memory

How to check task status in Celery?

res = method.delay()
    
print(f"id={res.id}, state={res.state}, status={res.status} ")

print(res.get())

How can you get the first digit in an int (C#)?

int temp = i;
while (temp >= 10)
{
    temp /= 10;
}

Result in temp

How to compare strings in sql ignoring case?

I don't recall the exact syntax, but you may set the table column to be case insensitive. But be careful because then you won't be able to match based on case anymore and if you WANT 'cool' to not match 'CoOl' it will no longer be possible.

"FATAL: Module not found error" using modprobe

Try insmod instead of modprobe. Modprobe looks in the module directory /lib/modules/uname -r for all the modules and other files

Injection of autowired dependencies failed;

Do you have a bean declared in your context file that has an id of "articleService"? I believe that autowiring matches the id of a bean in your context files with the variable name that you are attempting to Autowire.

Closing WebSocket correctly (HTML5, Javascript)

The thing of it is there are 2 main protocol versions of WebSockets in use today. The old version which uses the [0x00][message][0xFF] protocol, and then there's the new version using Hybi formatted packets.

The old protocol version is used by Opera and iPod/iPad/iPhones so it's actually important that backward compatibility is implemented in WebSockets servers. With these browsers using the old protocol, I discovered that refreshing the page, or navigating away from the page, or closing the browser, all result in the browser automatically closing the connection. Great!!

However with browsers using the new protocol version (eg. Firefox, Chrome and eventually IE10), only closing the browser will result in the browser automatically closing the connection. That is to say, if you refresh the page, or navigate away from the page, the browser does NOT automatically close the connection. However, what the browser does do, is send a hybi packet to the server with the first byte (the proto ident) being 0x88 (better known as the close data frame). Once the server receives this packet it can forcefully close the connection itself, if you so choose.

Python __call__ special method practical example

The function call operator.

class Foo:
    def __call__(self, a, b, c):
        # do something

x = Foo()
x(1, 2, 3)

The __call__ method can be used to redefined/re-initialize the same object. It also facilitates the use of instances/objects of a class as functions by passing arguments to the objects.

.NET NewtonSoft JSON deserialize map to a different property name

Adding to Jacks solution. I need to Deserialize using the JsonProperty and Serialize while ignoring the JsonProperty (or vice versa). ReflectionHelper and Attribute Helper are just helper classes that get a list of properties or attributes for a property. I can include if anyone actually cares. Using the example below you can serialize the viewmodel and get "Amount" even though the JsonProperty is "RecurringPrice".

    /// <summary>
    /// Ignore the Json Property attribute. This is usefule when you want to serialize or deserialize differently and not 
    /// let the JsonProperty control everything.
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public class IgnoreJsonPropertyResolver<T> : DefaultContractResolver
    {
        private Dictionary<string, string> PropertyMappings { get; set; }

        public IgnoreJsonPropertyResolver()
        {
            this.PropertyMappings = new Dictionary<string, string>();
            var properties = ReflectionHelper<T>.GetGetProperties(false)();
            foreach (var propertyInfo in properties)
            {
                var jsonProperty = AttributeHelper.GetAttribute<JsonPropertyAttribute>(propertyInfo);
                if (jsonProperty != null)
                {
                    PropertyMappings.Add(jsonProperty.PropertyName, propertyInfo.Name);
                }
            }
        }

        protected override string ResolvePropertyName(string propertyName)
        {
            string resolvedName = null;
            var resolved = this.PropertyMappings.TryGetValue(propertyName, out resolvedName);
            return (resolved) ? resolvedName : base.ResolvePropertyName(propertyName);
        }
    }

Usage:

        var settings = new JsonSerializerSettings();
        settings.DateFormatString = "YYYY-MM-DD";
        settings.ContractResolver = new IgnoreJsonPropertyResolver<PlanViewModel>();
        var model = new PlanViewModel() {Amount = 100};
        var strModel = JsonConvert.SerializeObject(model,settings);

Model:

public class PlanViewModel
{

    /// <summary>
    ///     The customer is charged an amount over an interval for the subscription.
    /// </summary>
    [JsonProperty(PropertyName = "RecurringPrice")]
    public double Amount { get; set; }

    /// <summary>
    ///     Indicates the number of intervals between each billing. If interval=2, the customer would be billed every two
    ///     months or years depending on the value for interval_unit.
    /// </summary>
    public int Interval { get; set; } = 1;

    /// <summary>
    ///     Number of free trial days that can be granted when a customer is subscribed to this plan.
    /// </summary>
    public int TrialPeriod { get; set; } = 30;

    /// <summary>
    /// This indicates a one-time fee charged upfront while creating a subscription for this plan.
    /// </summary>
    [JsonProperty(PropertyName = "SetupFee")]
    public double SetupAmount { get; set; } = 0;


    /// <summary>
    /// String representing the type id, usually a lookup value, for the record.
    /// </summary>
    [JsonProperty(PropertyName = "TypeId")]
    public string Type { get; set; }

    /// <summary>
    /// Billing Frequency
    /// </summary>
    [JsonProperty(PropertyName = "BillingFrequency")]
    public string Period { get; set; }


    /// <summary>
    /// String representing the type id, usually a lookup value, for the record.
    /// </summary>
    [JsonProperty(PropertyName = "PlanUseType")]
    public string Purpose { get; set; }
}

How to find the date of a day of the week from a date using PHP?

PHP Manual said :

w Numeric representation of the day of the week

You can therefore construct a date with mktime, and use in it date("w", $yourTime);

Why can't I make a vector of references?

boost::ptr_vector<int> will work.

Edit: was a suggestion to use std::vector< boost::ref<int> >, which will not work because you can't default-construct a boost::ref.

how to overcome ERROR 1045 (28000): Access denied for user 'ODBC'@'localhost' (using password: NO) permanently

Try using following command it work.

mysql --user=root --password=root_password

Bold & Non-Bold Text In A Single UILabel?

There's category based on bbrame's category. It works similar, but allows you boldify same UILabel multiple times with cumulative results.

UILabel+Boldify.h

@interface UILabel (Boldify)
- (void) boldSubstring: (NSString*) substring;
- (void) boldRange: (NSRange) range;
@end

UILabel+Boldify.m

@implementation UILabel (Boldify)
- (void)boldRange:(NSRange)range {
    if (![self respondsToSelector:@selector(setAttributedText:)]) {
        return;
    }
    NSMutableAttributedString *attributedText;
    if (!self.attributedText) {
        attributedText = [[NSMutableAttributedString alloc] initWithString:self.text];
    } else {
        attributedText = [[NSMutableAttributedString alloc] initWithAttributedString:self.attributedText];
    }
    [attributedText setAttributes:@{NSFontAttributeName:[UIFont boldSystemFontOfSize:self.font.pointSize]} range:range];
    self.attributedText = attributedText;
}

- (void)boldSubstring:(NSString*)substring {
    NSRange range = [self.text rangeOfString:substring];
    [self boldRange:range];
}
@end

With this corrections you may use it multiple times, eg:

myLabel.text = @"Updated: 2012/10/14 21:59 PM";
[myLabel boldSubstring: @"Updated:"];
[myLabel boldSubstring: @"21:59 PM"];

will result with: "Updated: 2012/10/14 21:59 PM".

How do I undo 'git add' before commit?

Use the * command to handle multiple files at a time:

git reset HEAD *.prj
git reset HEAD *.bmp
git reset HEAD *gdb*

etc.

Stop setInterval

You have to assign the returned value of the setInterval function to a variable

var interval;
$(document).on('ready',function(){
    interval = setInterval(updateDiv,3000);
});

and then use clearInterval(interval) to clear it again.

Check if all checkboxes are selected

This is how I achieved it in my code:

if($('.citiescheckbox:checked').length == $('.citiescheckbox').length){
    $('.citycontainer').hide();
}else{
    $('.citycontainer').show();
}

Calculate rolling / moving average in C++

Incrementing on @Nilesh's answer (credit goes to him), you can:

  • keep track of the sum, no need to divide and then multiply every time, generating error
  • avoid if conditions using % operator

This is UNTESTED sample code to show the idea, it could also be wrapped into a class:

const unsigned int size=10; // ten elements buffer

unsigned int counterPosition=0;
unsigned int counterNum=0;

int buffer[size];
long sum=0;

void reset() {
    for(int i=0;i<size;i++) {
        buffer[i]=0;
    }
}

float addValue(int value) {
    unsigned  int oldPos = ((counterPosition + 1) % size);

    buffer[counterPosition] = value;
    sum = (sum - buffer[oldPos] + value); 

    counterPosition=(counterPosition+1) % size;
    if(counterNum<size) counterNum++;

    return ((float)sum)/(float)counterNum;
}

float removeValue() {
    unsigned  int oldPos =((counterPosition + 1) % size);

    buffer[counterPosition] = 0;
    sum = (sum - buffer[oldPos]); 

    if(counterNum>1) { // leave one last item at the end, forever
        counterPosition=(counterPosition+1) % size;
        counterNum--; // here the two counters are different
    }
    return ((float)sum)/(float)counterNum;
}

It should be noted that, if the buffer is reset to all zeroes, this method works fine while receiving the first values in as - buffer[oldPos] is zero and counter grows. First output is the first number received. Second output is the average of only the first two, and so on, fading in the values while they arrive until size items are reached.

It is also worth considering that this method, like any other for rolling average, is asymmetrical, if you stop at the end of the input array, because the same fading does not happen at the end (it can happen after the end of data, with the right calculations).

That is correct. The rolling average of 100 elements with a buffer of 10 gives different results: 10 fading in, 90 perfectly rolling 10 elements, and finally 10 fading out, giving a total of 110 results for 100 numbers fed in! It's your choice to decide which ones to show (and if it's better going the straight way, old to recent, or backwards, recent to old).

To fade out correctly after the end, you can go on adding zeroes one by one and reducing the count of items by one every time until you have reached size elements (still keeping track of correct position of old values).

Usage is like this:

int avg=0;
reset();

avg=addValue(2); // Rpeat for 100 times
avg=addValue(3); // Use avg value

...

avg=addValue(-4);
avg=addValue(12); // last numer, 100th input 

// If you want to fade out repeat 10 times after the end of data:

avg=removeValue(); // Rpeat for last 10 times after data has finished
avg=removeValue(); // Use avg value
...
avg=removeValue();
avg=removeValue();

What is the difference between Linear search and Binary search?

Linear search also referred to as sequential search looks at each element in sequence from the start to see if the desired element is present in the data structure. When the amount of data is small, this search is fast.Its easy but work needed is in proportion to the amount of data to be searched.Doubling the number of elements will double the time to search if the desired element is not present.

Binary search is efficient for larger array. In this we check the middle element.If the value is bigger that what we are looking for, then look in the first half;otherwise,look in the second half. Repeat this until the desired item is found. The table must be sorted for binary search. It eliminates half the data at each iteration.Its logarithmic.

If we have 1000 elements to search, binary search takes about 10 steps, linear search 1000 steps.

how to get rid of notification circle in right side of the screen?

This stuff comes from ES file explorer

Just go into this app > settings

Then there is an option that says logging floating window, you just need to disable that and you will get rid of this infernal bubble for good

How to plot all the columns of a data frame in R

With lattice:

library(lattice)

df <- data.frame(time = 1:10,
                 a = cumsum(rnorm(10)),
                 b = cumsum(rnorm(10)),
                 c = cumsum(rnorm(10)))

form <- as.formula(paste(paste(names(df)[- 1],  collapse = ' + '),  
                         'time',  sep = '~'))

xyplot(form,  data = df,  type = 'b',  outer = TRUE)

How to define Singleton in TypeScript

This is the simplest way

class YourSingletoneClass {
  private static instance: YourSingletoneClass;

  private constructor(public ifYouHaveAnyParams: string) {

  }
  static getInstance() {
    if(!YourSingletoneClass.instance) {
      YourSingletoneClass.instance = new YourSingletoneClass('If you have any params');
    }
    return YourSingletoneClass.instance;
  }
}

javascript - match string against the array of regular expressions

let expressions = [ '/something/', '/something_else/', '/and_something_else/'];

let str = 'else';

here will be the check for following expressions:

if( expressions.find(expression => expression.includes(str) ) ) {

}

using Array .find() method to traverse array and .include to check substring

cannot load such file -- bundler/setup (LoadError)

I've fixed that problem by creating test rails project and install all gems then I've replaced my current Gemfile.lock with the test and all thing works fine.

I think that this problem from bundler versions with hosting, so please make sure that hosting bundler is the same version with your project.

How can I get LINQ to return the object which has the max value for a given property?

In LINQ you can solve it the following way:

Item itemMax = (from i in items
     let maxId = items.Max(m => m.ID)
     where i.ID == maxId
     select i).FirstOrDefault();

How to send a html email with the bash command "sendmail"?

The following works:

(
echo "From: ${from}";
echo "To: ${to}";
echo "Subject: ${subject}";
echo "Content-Type: text/html";
echo "MIME-Version: 1.0";
echo "";
echo "${message}";
) | sendmail -t

For troubleshooting msmtp, which is compatible with sendmail, see:

System.BadImageFormatException: Could not load file or assembly (from installutil.exe)

We found a different solution to a problem with the same symptom:

We saw this error when we updated the project from .net 4.7.1 to 4.7.2.

The problem was that even though we were not referencing System.Net.Http any more in the project, it was listed in the dependentAssembily section of our web.config. Removing this and any other unused assembly references from the web.config solved the problem.

Can I specify maxlength in css?

I don't think you can, and CSS is supposed to describe how the page looks not what it does, so even if you could, it's not really how you should be using it.

Perhaps you should think about using JQuery to apply common functionality to your form components?

How to add Android Support Repository to Android Studio?

Found a solution.

1) Go to where your SDK is located that android studio/eclipse is using. If you are using Android studio, go to extras\android\m2repository\com\android\support\. If you are using eclipse, go to \extras\android\support\

2) See what folders you have, for me I had gridlayout-v7, support-v4 and support-v13.

3) click into support-v4 and see what number the following folder is, mine was named 13.0

Since you are using "com.android.support:support-v4:18.0.+", change this to reflect what version you have, for example I have support-v4 so first part v4 stays the same. Since the next path is 13.0, change your 18.0 to:

"com.android.support:support-v4:13.0.+"

This worked for me, hope it helps!

Update:

I noticed I had android studio set up with the wrong SDK which is why originally had difficulty updating! The path should be C:\Users\Username\AppData\Local\Android\android-sdk\extras\

Also note, if your SDK is up to date, the code will be:

"com.android.support:support-v4:19.0.+"

ssl.SSLError: tlsv1 alert protocol version

For python2 users on MacOS (python@2 formula won't be found), as brew stopped support of python2 you need to use such command! But don't forget to unlink old python if it was pre-installed.

brew install https://raw.githubusercontent.com/Homebrew/homebrew-core/86a44a0a552c673a05f11018459c9f5faae3becc/Formula/[email protected]

If you've done some mistake, simply brew uninstall python@2 old way, and try again.

thank you hyperknot (answer here)