Programs & Examples On #Asyncpostbackerror

get parent's view from a layout

If you are trying to find a View from your Fragment then try doing it like this:

int w = ((EditText)getActivity().findViewById(R.id.editText1)).getLayoutParams().width;

Connection reset by peer: mod_fcgid: error reading data from FastCGI server

I had very similar errors in the Apache2 log files:

(104)Connection reset by peer: mod_fcgid: error reading data from FastCGI server
Premature end of script headers: phpinfo.php

After checking the wrapper scripts and Apache2 settings, I realized that /var/www/ did not have accordant permissions. Thus the FCGId Wrapper scripts could not be read at all.

ls -la /var/www
drwxrws---  5 www-data     www-data     4096 Oct  7 11:17 .

For my scenario chmod -o+rx /var/www was required of course, since the used SuExec users are not member of www-data user group - and they should not be member for security reasons of course.

Split function equivalent in T-SQL?

Try this

DECLARE @xml xml, @str varchar(100), @delimiter varchar(10)
SET @str = '1,2,3,4,5,6,7,8,9,10,11,12,13,14,15'
SET @delimiter = ','
SET @xml = cast(('<X>'+replace(@str, @delimiter, '</X><X>')+'</X>') as xml)
SELECT C.value('.', 'varchar(10)') as value FROM @xml.nodes('X') as X(C)

OR

DECLARE @str varchar(100), @delimiter varchar(10)
SET @str = '1,2,3,4,5,6,7,8,9,10,11,12,13,14,15'
SET @delimiter = ','
;WITH cte AS
(
    SELECT 0 a, 1 b
    UNION ALL
    SELECT b, CHARINDEX(@delimiter, @str, b) + LEN(@delimiter)
    FROM CTE
    WHERE b > a
)
SELECT SUBSTRING(@str, a,
CASE WHEN b > LEN(@delimiter) 
    THEN b - a - LEN(@delimiter) 
    ELSE LEN(@str) - a + 1 END) value      
FROM cte WHERE a > 0

Many more ways of doing the same is here How to split comma delimited string?

Using the grep and cut delimiter command (in bash shell scripting UNIX) - and kind of "reversing" it?

You don't need to change the delimiter to display the right part of the string with cut.

The -f switch of the cut command is the n-TH element separated by your delimiter : :, so you can just type :

 grep puddle2_1557936 | cut -d ":" -f2

Another solutions (adapt it a bit) if you want fun :

Using :

grep -oP 'puddle2_1557936:\K.*' <<< 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'                                                                        
/home/rogers.williams/folderz/puddle2

or still with look around

grep -oP '(?<=puddle2_1557936:).*' <<< 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'                                                                    
/home/rogers.williams/folderz/puddle2

or with :

perl -lne '/puddle2_1557936:(.*)/ and print $1' <<< 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'                                                      
/home/rogers.williams/folderz/puddle2

or using (thanks to glenn jackman)

ruby -F: -ane '/puddle2_1557936/ and puts $F[1]' <<< 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'
/home/rogers.williams/folderz/puddle2

or with :

awk -F'puddle2_1557936:' '{print $2}'  <<< 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'
/home/rogers.williams/folderz/puddle2

or with :

python -c 'import sys; print(sys.argv[1].split("puddle2_1557936:")[1])' 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'
/home/rogers.williams/folderz/puddle2

or using only :

IFS=: read _ a <<< "puddle2_1557936:/home/rogers.williams/folderz/puddle2"
echo "$a"
/home/rogers.williams/folderz/puddle2

or using in a :

js<<EOF
var x = 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'
print(x.substr(x.indexOf(":")+1))
EOF
/home/rogers.williams/folderz/puddle2

or using in a :

php -r 'preg_match("/puddle2_1557936:(.*)/", $argv[1], $m); echo "$m[1]\n";' 'puddle2_1557936:/home/rogers.williams/folderz/puddle2' 
/home/rogers.williams/folderz/puddle2

add scroll bar to table body

you can wrap the content of the <tbody> in a scrollable <div> :

html

....
<tbody>
  <tr>
    <td colspan="2">
      <div class="scrollit">
        <table>
          <tr>
            <td>January</td>
            <td>$100</td>
          </tr>
          <tr>
            <td>February</td>
            <td>$80</td>
          </tr>
          <tr>
            <td>January</td>
            <td>$100</td>
          </tr>
          <tr>
            <td>February</td>
            <td>$80</td>
          </tr>
          ...

css

.scrollit {
    overflow:scroll;
    height:100px;
}

see my jsfiddle, forked from yours: http://jsfiddle.net/VTNax/2/

How to enable Ad Hoc Distributed Queries

The following command may help you..

EXEC sp_configure 'show advanced options', 1
RECONFIGURE
GO
EXEC sp_configure 'ad hoc distributed queries', 1
RECONFIGURE
GO

With Spring can I make an optional path variable?

Simplified example of Nicolai Ehmann's comment and wildloop's answer (works with Spring 4.3.3+), basically you can use required = false now:

  @RequestMapping(value = {"/json/{type}", "/json" }, method = RequestMethod.GET)
  public @ResponseBody TestBean testAjax(@PathVariable(required = false) String type) {
    if (type != null) {
      // ...
    }
    return new TestBean();
  }

How do I add an image to a JButton

@Rogach

and you may like to add:

// to remote the spacing between the image and button's borders
button.setMargin(new Insets(0, 0, 0, 0));
// to add a different background
button.setBackground( ... );
// to remove the border
button.setBorder(null);

android asynctask sending callbacks to ui

You can create an interface, pass it to AsyncTask (in constructor), and then call method in onPostExecute()

For example:

Your interface:

public interface OnTaskCompleted{
    void onTaskCompleted();
}

Your Activity:

public class YourActivity implements OnTaskCompleted{
    // your Activity
}

And your AsyncTask:

public class YourTask extends AsyncTask<Object,Object,Object>{ //change Object to required type
    private OnTaskCompleted listener;

    public YourTask(OnTaskCompleted listener){
        this.listener=listener;
    }

    // required methods

    protected void onPostExecute(Object o){
        // your stuff
        listener.onTaskCompleted();
    }
}

EDIT

Since this answer got quite popular, I want to add some things.

If you're a new to Android development, AsyncTask is a fast way to make things work without blocking UI thread. It does solves some problems indeed, there is nothing wrong with how the class works itself. However, it brings some implications, such as:

  • Possibility of memory leaks. If you keep reference to your Activity, it will stay in memory even after user left the screen (or rotated the device).
  • AsyncTask is not delivering result to Activity if Activity was already destroyed. You have to add extra code to manage all this stuff or do you operations twice.
  • Convoluted code which does everything in Activity

When you feel that you matured enough to move on with Android, take a look at this article which, I think, is a better way to go for developing your Android apps with asynchronous operations.

OnClick in Excel VBA

In order to trap repeated clicks on the same cell, you need to move the focus to a different cell, so that each time you click, you are in fact moving the selection.

The code below will select the top left cell visible on the screen, when you click on any cell. Obviously, it has the flaw that it won't trap a click on the top left cell, but that can be managed (eg by selecting the top right cell if the activecell is the top left).

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
  'put your code here to process the selection, then..
  ActiveWindow.VisibleRange.Cells(1, 1).Select
End Sub

What is web.xml file and what are all things can I do with it?

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0">
  <servlet>
    <servlet-name>mvc-dispatcher</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet>
    <description></description>
    <display-name>pdfServlet</display-name>
    <servlet-name>pdfServlet</servlet-name>
    <servlet-class>com.sapta.smartcam.servlet.pdfServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>mvc-dispatcher</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>
  <servlet-mapping>
    <servlet-name>pdfServlet</servlet-name>
    <url-pattern>/pdfServlet</url-pattern>
  </servlet-mapping>
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/mvc-dispatcher-servlet.xml</param-value>
  </context-param>
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>

asterisk : Unable to connect to remote asterisk (does /var/run/asterisk.ctl exist?)

Only you need to empty /tmp directory using command & hit reboot your system. now you are able to play on asterisk CLI whatever you want.

Why "no projects found to import"?

In new updated eclipse the option "create project from existing source" is found here, File>New>Project>Android>Android Project from Existing Code. Then browse to root directory.

enter image description here

Add event handler for body.onload by javascript within <body> part

body.addEventListener("load", init(), false);

That init() is saying run this function now and assign whatever it returns to the load event.

What you want is to assign the reference to the function, not the result. So you need to drop the ().

body.addEventListener("load", init, false);

Also you should be using window.onload and not body.onload

addEventListener is supported in most browsers except IE 8.

Loop through all the files with a specific extension

No fancy tricks needed:

for i in *.java; do
    [ -f "$i" ] || break
    ...
done

The guard ensures that if there are no matching files, the loop will exit without trying to process a non-existent file name *.java. In bash (or shells supporting something similar), you can use the nullglob option to simply ignore a failed match and not enter the body of the loop.

shopt -s nullglob
for i in *.java; do
    ...
done

XPath Query: get attribute href from a tag

For the following HTML document:

<html>
  <body>
    <a href="http://www.example.com">Example</a> 
    <a href="http://www.stackoverflow.com">SO</a> 
  </body>
</html>

The xpath query /html/body//a/@href (or simply //a/@href) will return:

    http://www.example.com
    http://www.stackoverflow.com

To select a specific instance use /html/body//a[N]/@href,

    $ /html/body//a[2]/@href
    http://www.stackoverflow.com

To test for strings contained in the attribute and return the attribute itself place the check on the tag not on the attribute:

    $ /html/body//a[contains(@href,'example')]/@href
    http://www.example.com

Mixing the two:

    $ /html/body//a[contains(@href,'com')][2]/@href
    http://www.stackoverflow.com

Android: Quit application when press back button

Use this code very simple solution

 @Override
    public void onBackPressed() {
      super.onBackPressed(); // this line close the  app on backpress
 }

Add legend to ggplot2 line plot

I tend to find that if I'm specifying individual colours in multiple geom's, I'm doing it wrong. Here's how I would plot your data:

##Subset the necessary columns
dd_sub = datos[,c(20, 2,3,5)]
##Then rearrange your data frame
library(reshape2)
dd = melt(dd_sub, id=c("fecha"))

All that's left is a simple ggplot command:

ggplot(dd) + geom_line(aes(x=fecha, y=value, colour=variable)) +
  scale_colour_manual(values=c("red","green","blue"))

Example plot

enter image description here

Why is access to the path denied?

An UnauthorizedAccessException exception is thrown when the operating system denies access because of an I/O error or a security error.

If you are attempting to access a file or registry key, make sure it is not read-only.

git replace local version with remote version

I would checkout the remote file from the "master" (the remote/origin repository) like this:

git checkout master <FileWithPath>

Example: git checkout master components/indexTest.html

Changing the CommandTimeout in SQL Management studio

If you are getting a timeout while on the table designer, change the "Transaction time-out after" value under Tools --> Options --> Designers --> Table and Database Designers

This will get rid of this message: "Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding."

enter image description here

CodeIgniter query: How to move a column value to another column in the same row and save the current time in the original column?

$data = array( 
    'name'      => $_POST['name'] , 
    'groupname' => $_POST['groupname'], 
    'age'       => $_POST['age']
);

$this->db->where('id', $_POST['id']);

$this->db->update('tbl_user', $data);

Correct path for img on React.js

In create-react-app relative paths for images don't seem to work. Instead, you can import an image:

import logo from './logo.png' // relative path to image 

class Nav extends Component { 
    render() { 
        return ( 
            <img src={logo} alt={"logo"}/> 
        )  
    }
}

How can we redirect a Java program console output to multiple files?

To solve the problem I use ${string_prompt} variable. It shows a input dialog when application runs. I can set the date/time manually at that dialog.

  1. Move cursor at the end of file path. enter image description here

  2. Click variables and select string_prompt enter image description here

  3. Select Apply and Run enter image description here enter image description here

Writing new lines to a text file in PowerShell

It's also possible to assign newline and carriage return to variables and then append them to texts inside PowerShell scripts:

$OFS = "`r`n"
$msg = "This is First Line" + $OFS + "This is Second Line" + $OFS
Write-Host $msg

The most sophisticated way for creating comma-separated Strings from a Collection/Array/List?

Note: This answers was good when it was written 11 years ago, but now there are far better options to do this more cleanly in a single line, both using only Java built-in classes or using a utility library. See other answers below.


Since strings are immutable, you may want to use the StringBuilder class if you're going to alter the String in the code.

The StringBuilder class can be seen as a mutable String object which allocates more memory when its content is altered.

The original suggestion in the question can be written even more clearly and efficiently, by taking care of the redundant trailing comma:

    StringBuilder result = new StringBuilder();
    for(String string : collectionOfStrings) {
        result.append(string);
        result.append(",");
    }
    return result.length() > 0 ? result.substring(0, result.length() - 1): "";

How to ORDER BY a SUM() in MySQL?

Don'y forget that if you are mixing grouped (ie. SUM) fields and non-grouped fields, you need to GROUP BY one of the non-grouped fields.

Try this:

SELECT SUM(something) AS fieldname
FROM tablename
ORDER BY fieldname

OR this:

SELECT Field1, SUM(something) AS Field2
FROM tablename
GROUP BY Field1
ORDER BY Field2

And you can always do a derived query like this:

SELECT
   f1, f2
FROM
    (
        SELECT SUM(x+y) as f1, foo as F2
        FROM tablename 
        GROUP BY f2
    ) as table1
ORDER BY 
    f1

Many possibilities!

Jquery Validate custom error message location

What you should use is the errorLabelContainer

_x000D_
_x000D_
jQuery(function($) {_x000D_
  var validator = $('#form').validate({_x000D_
    rules: {_x000D_
      first: {_x000D_
        required: true_x000D_
      },_x000D_
      second: {_x000D_
        required: true_x000D_
      }_x000D_
    },_x000D_
    messages: {},_x000D_
    errorElement : 'div',_x000D_
    errorLabelContainer: '.errorTxt'_x000D_
  });_x000D_
});
_x000D_
.errorTxt{_x000D_
  border: 1px solid red;_x000D_
  min-height: 20px;_x000D_
}
_x000D_
<script type="text/javascript" src="http://code.jquery.com/jquery-1.11.1.js"></script>_x000D_
<script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.12.0/jquery.validate.js"></script>_x000D_
<script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.12.0/additional-methods.js"></script>_x000D_
_x000D_
<form id="form" method="post" action="">_x000D_
  <input type="text" name="first" />_x000D_
  <input type="text" name="second" />_x000D_
  <div class="errorTxt"></div>_x000D_
  <input type="submit" class="button" value="Submit" />_x000D_
</form>
_x000D_
_x000D_
_x000D_


If you want to retain your structure then

_x000D_
_x000D_
jQuery(function($) {_x000D_
  var validator = $('#form').validate({_x000D_
    rules: {_x000D_
      first: {_x000D_
        required: true_x000D_
      },_x000D_
      second: {_x000D_
        required: true_x000D_
      }_x000D_
    },_x000D_
    messages: {},_x000D_
    errorPlacement: function(error, element) {_x000D_
      var placement = $(element).data('error');_x000D_
      if (placement) {_x000D_
        $(placement).append(error)_x000D_
      } else {_x000D_
        error.insertAfter(element);_x000D_
      }_x000D_
    }_x000D_
  });_x000D_
});
_x000D_
#errNm1 {_x000D_
  border: 1px solid red;_x000D_
}_x000D_
#errNm2 {_x000D_
  border: 1px solid green;_x000D_
}
_x000D_
<script type="text/javascript" src="http://code.jquery.com/jquery-1.11.1.js"></script>_x000D_
<script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.12.0/jquery.validate.js"></script>_x000D_
<script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.12.0/additional-methods.js"></script>_x000D_
_x000D_
<form id="form" method="post" action="">_x000D_
  <input type="text" name="first" data-error="#errNm1" />_x000D_
  <input type="text" name="second" data-error="#errNm2" />_x000D_
  <div class="errorTxt">_x000D_
    <span id="errNm2"></span>_x000D_
    <span id="errNm1"></span>_x000D_
  </div>_x000D_
  <input type="submit" class="button" value="Submit" />_x000D_
</form>
_x000D_
_x000D_
_x000D_

How to run Ruby code from terminal?

You can run ruby commands in one line with the -e flag:

ruby -e "puts 'hi'"

Check the man page for more information.

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

Here is a list of what can be pickled. In particular, functions are only picklable if they are defined at the top-level of a module.

This piece of code:

import multiprocessing as mp

class Foo():
    @staticmethod
    def work(self):
        pass

if __name__ == '__main__':   
    pool = mp.Pool()
    foo = Foo()
    pool.apply_async(foo.work)
    pool.close()
    pool.join()

yields an error almost identical to the one you posted:

Exception in thread Thread-2:
Traceback (most recent call last):
  File "/usr/lib/python2.7/threading.py", line 552, in __bootstrap_inner
    self.run()
  File "/usr/lib/python2.7/threading.py", line 505, in run
    self.__target(*self.__args, **self.__kwargs)
  File "/usr/lib/python2.7/multiprocessing/pool.py", line 315, in _handle_tasks
    put(task)
PicklingError: Can't pickle <type 'function'>: attribute lookup __builtin__.function failed

The problem is that the pool methods all use a mp.SimpleQueue to pass tasks to the worker processes. Everything that goes through the mp.SimpleQueue must be pickable, and foo.work is not picklable since it is not defined at the top level of the module.

It can be fixed by defining a function at the top level, which calls foo.work():

def work(foo):
    foo.work()

pool.apply_async(work,args=(foo,))

Notice that foo is pickable, since Foo is defined at the top level and foo.__dict__ is picklable.

Accessing member of base class

You are incorrectly using the super and this keyword. Here is an example of how they work:

class Animal {
    public name: string;
    constructor(name: string) { 
        this.name = name;
    }
    move(meters: number) {
        console.log(this.name + " moved " + meters + "m.");
    }
}

class Horse extends Animal {
    move() {
        console.log(super.name + " is Galloping...");
        console.log(this.name + " is Galloping...");
        super.move(45);
    }
}

var tom: Animal = new Horse("Tommy the Palomino");

Animal.prototype.name = 'horseee'; 

tom.move(34);
// Outputs:

// horseee is Galloping...
// Tommy the Palomino is Galloping...
// Tommy the Palomino moved 45m.

Explanation:

  1. The first log outputs super.name, this refers to the prototype chain of the object tom, not the object tom self. Because we have added a name property on the Animal.prototype, horseee will be outputted.
  2. The second log outputs this.name, the this keyword refers to the the tom object itself.
  3. The third log is logged using the move method of the Animal base class. This method is called from Horse class move method with the syntax super.move(45);. Using the super keyword in this context will look for a move method on the prototype chain which is found on the Animal prototype.

Remember TS still uses prototypes under the hood and the class and extends keywords are just syntactic sugar over prototypical inheritance.

How to list imported modules?

Stealing from @Lila (couldn't make a comment because of no formatting), this shows the module's /path/, as well:

#!/usr/bin/env python
import sys
from modulefinder import ModuleFinder
finder = ModuleFinder()
# Pass the name of the python file of interest
finder.run_script(sys.argv[1])
# This is what's different from @Lila's script
finder.report()

which produces:

Name                      File
----                      ----

...
m token                     /opt/rh/rh-python35/root/usr/lib64/python3.5/token.py
m tokenize                  /opt/rh/rh-python35/root/usr/lib64/python3.5/tokenize.py
m traceback                 /opt/rh/rh-python35/root/usr/lib64/python3.5/traceback.py
...

.. suitable for grepping or what have you. Be warned, it's long!

How do I convert number to string and pass it as argument to Execute Process Task?

Expression: "Total Count: " + (DT_WSTR, 11)@[User::int32Value]

for Int32 -- (-2,147,483,648 to 2,147,483,647)

Show "Open File" Dialog

I agree John M has best answer to OP's question. Thought not explictly stated, the apparent purpose is to get a selected file name, whereas other answers return either counts or lists. I would add, however, that the msofiledialogfilepicker might be a better option in this case. ie:

Dim f As object
Set f = Application.FileDialog(msoFileDialogFilePicker)
dim varfile as variant 
f.show
with f
    .allowmultiselect = false
     for each varfile in .selecteditems
        msgbox varfile
     next varfile
end with

Note: the value of varfile will remain the same since multiselect is false (only one item is ever selected). I used its value outside the loop with equal success. It's probably better practice to do it as John M did, however. Also, the folder picker can be used to get a selected folder. I always prefer late binding, but I think the object is native to the default access library, so it may not be necessary here

How to get current time with jQuery

The following

function gettzdate(){
    var fd = moment().format('YYYY-MM-DDTHH:MM:ss');
    return fd ; 
}

works for forcing the current date onto a <input type="datetime-local">

Empty brackets '[]' appearing when using .where

A good bet is to utilize Rails' Arel SQL manager, which explicitly supports case-insensitive ActiveRecord queries:

t = Guide.arel_table Guide.where(t[:title].matches('%attack')) 

Here's an interesting blog post regarding the portability of case-insensitive queries using Arel. It's worth a read to understand the implications of utilizing Arel across databases.

No notification sound when sending notification from firebase in android

With HTTP v1 API it is different

Documentation

Example:

{
 "message":{
    "topic":"news",
    "notification":{
       "body":"Very good news",
       "title":"Good news"
    },
    "android":{
       "notification":{
          "body":"Very good news",
          "title":"Good news",
          "sound":"default"
       }
    }
  }
}

Comparison of C++ unit test frameworks

Wikipedia has a comprehensive list of unit testing frameworks, with tables that identify features supported or not.

Search a text file and print related lines in Python?

with open('file.txt', 'r') as searchfile:
    for line in searchfile:
        if 'searchphrase' in line:
            print line

With apologies to senderle who I blatantly copied.

lexers vs parsers

When is lexing enough, when do you need EBNF?

EBNF really doesn't add much to the power of grammars. It's just a convenience / shortcut notation / "syntactic sugar" over the standard Chomsky's Normal Form (CNF) grammar rules. For example, the EBNF alternative:

S --> A | B

you can achieve in CNF by just listing each alternative production separately:

S --> A      // `S` can be `A`,
S --> B      // or it can be `B`.

The optional element from EBNF:

S --> X?

you can achieve in CNF by using a nullable production, that is, the one which can be replaced by an empty string (denoted by just empty production here; others use epsilon or lambda or crossed circle):

S --> B       // `S` can be `B`,
B --> X       // and `B` can be just `X`,
B -->         // or it can be empty.

A production in a form like the last one B above is called "erasure", because it can erase whatever it stands for in other productions (product an empty string instead of something else).

Zero-or-more repetiton from EBNF:

S --> A*

you can obtan by using recursive production, that is, one which embeds itself somewhere in it. It can be done in two ways. First one is left recursion (which usually should be avoided, because Top-Down Recursive Descent parsers cannot parse it):

S --> S A    // `S` is just itself ended with `A` (which can be done many times),
S -->        // or it can begin with empty-string, which stops the recursion.

Knowing that it generates just an empty string (ultimately) followed by zero or more As, the same string (but not the same language!) can be expressed using right-recursion:

S --> A S    // `S` can be `A` followed by itself (which can be done many times),
S -->        // or it can be just empty-string end, which stops the recursion.

And when it comes to + for one-or-more repetition from EBNF:

S --> A+

it can be done by factoring out one A and using * as before:

S --> A A*

which you can express in CNF as such (I use right recursion here; try to figure out the other one yourself as an exercise):

S --> A S   // `S` can be one `A` followed by `S` (which stands for more `A`s),
S --> A     // or it could be just one single `A`.

Knowing that, you can now probably recognize a grammar for a regular expression (that is, regular grammar) as one which can be expressed in a single EBNF production consisting only from terminal symbols. More generally, you can recognize regular grammars when you see productions similar to these:

A -->        // Empty (nullable) production (AKA erasure).
B --> x      // Single terminal symbol.
C --> y D    // Simple state change from `C` to `D` when seeing input `y`.
E --> F z    // Simple state change from `E` to `F` when seeing input `z`.
G --> G u    // Left recursion.
H --> v H    // Right recursion.

That is, using only empty strings, terminal symbols, simple non-terminals for substitutions and state changes, and using recursion only to achieve repetition (iteration, which is just linear recursion - the one which doesn't branch tree-like). Nothing more advanced above these, then you're sure it's a regular syntax and you can go with just lexer for that.

But when your syntax uses recursion in a non-trivial way, to produce tree-like, self-similar, nested structures, like the following one:

S --> a S b    // `S` can be itself "parenthesized" by `a` and `b` on both sides.
S -->          // or it could be (ultimately) empty, which ends recursion.

then you can easily see that this cannot be done with regular expression, because you cannot resolve it into one single EBNF production in any way; you'll end up with substituting for S indefinitely, which will always add another as and bs on both sides. Lexers (more specifically: Finite State Automata used by lexers) cannot count to arbitrary number (they are finite, remember?), so they don't know how many as were there to match them evenly with so many bs. Grammars like this are called context-free grammars (at the very least), and they require a parser.

Context-free grammars are well-known to parse, so they are widely used for describing programming languages' syntax. But there's more. Sometimes a more general grammar is needed -- when you have more things to count at the same time, independently. For example, when you want to describe a language where one can use round parentheses and square braces interleaved, but they have to be paired up correctly with each other (braces with braces, round with round). This kind of grammar is called context-sensitive. You can recognize it by that it has more than one symbol on the left (before the arrow). For example:

A R B --> A S B

You can think of these additional symbols on the left as a "context" for applying the rule. There could be some preconditions, postconditions etc. For example, the above rule will substitute R into S, but only when it's in between A and B, leaving those A and B themselves unchanged. This kind of syntax is really hard to parse, because it needs a full-blown Turing machine. It's a whole another story, so I'll end here.

Adding a JAR to an Eclipse Java library

In Eclipse Ganymede (3.4.0):

  1. Select the library and click "Edit" (left side of the window)
  2. Click "User Libraries"
  3. Select the library again and click "Add JARs"

Composer update memory limit

If there's enough memory composer would internally consume it and run without any problem. No need to specifically tell the composer to do it.

Have you tried to increase your swap memory, coz it worked for me. I increased the swap memory to 4096Mb (4GB) and now it all looks great to me.

first use "sudo free" to see available memory and swap memory. and configure swap as,

For Debian:

sudo fallocate -l 4G /swapfile
sudo dd if=/dev/zero of=/swapfile bs=4096k count=1048
sudo chmod 600 /swapfile
sudo mkswap /swapfile
sudo swapon /swapfile

to make it permenant add this to /etc/fstab file, /swapfile swap swap defaults 0 0

For CentOS :

[root@myserver]:/# cd /var
[root@myserver]:/var# touch swap.img
[root@myserver]:/var# chmod 600 swap.img
[root@myserver]:/var# mkswap /var/swap.img

[root@myserver]:/var# dd if=/dev/zero of=/var/swap.img bs=4096k count=1000
[root@myserver]:/var# mkswap /var/swap.img 
[root@myserver]:/var# swapon /var/swap.img

you can increase your swap memory by changin bs= 1024k or 2048k or 8096k depending on your physical volume size. use 'swapon' and swapoff commands to see the difference.

check 'swappiness' (60 should do good,)

cat /proc/sys/vm/swappiness

How do I format date and time on ssrs report?

If the date and time is in its own cell (aka textbox), then you should look at applying the format to the entire textbox. This will create cleaner exports to other formats; in particular, the value will export as a datetime value to Excel instead of a string.

Use the properties pane or dialog to set the format for the textbox to "MM/dd/yyyy hh:mm tt"

I would only use Ian's answer if the datetime is being concatenated with another string.

From an array of objects, extract value of a property as array

If you have nested arrays you can make it work like this:

_x000D_
_x000D_
const objArray = [ _x000D_
     { id: 1, items: { foo:4, bar: 2}},_x000D_
     { id: 2, items: { foo:3, bar: 2}},_x000D_
     { id: 3, items: { foo:1, bar: 2}} _x000D_
    ];_x000D_
_x000D_
    let result = objArray.map(({id, items: {foo}}) => ({id, foo}))_x000D_
    _x000D_
    console.log(result)
_x000D_
_x000D_
_x000D_

How to start a Process as administrator mode in C#

You probably need to set your application as an x64 app.

The IIS Snap In only works in 64 bit and doesn't work in 32 bit, and a process spawned from a 32 bit app seems to work to be a 32 bit process and the same goes for 64 bit apps.

Look at: Start process as 64 bit

How to input a regex in string.replace?

replace method of string objects does not accept regular expressions but only fixed strings (see documentation: http://docs.python.org/2/library/stdtypes.html#str.replace).

You have to use re module:

import re
newline= re.sub("<\/?\[[0-9]+>", "", line)

trim left characters in sql server?

select substring( field, 1, 5 ) from sometable

Combining two lists and removing duplicates, without removing duplicates in original list

Based on the recipe :

resulting_list = list(set().union(first_list, second_list))

Angular exception: Can't bind to 'ngForIn' since it isn't a known native property

Try to import import { CommonModule } from '@angular/common'; in angular final as *ngFor ,*ngIf all are present in CommonModule

jQuery Datepicker with text input that doesn't allow user input

$("#my_txtbox").prop('readonly', true)

worked like a charm..

Error - is not marked as serializable

Leaving my specific solution of this for prosperity, as it's a tricky version of this problem:

Type 'System.Linq.Enumerable+WhereSelectArrayIterator[T...] was not marked as serializable

Due to a class with an attribute IEnumerable<int> eg:

[Serializable]
class MySessionData{
    public int ID;
    public IEnumerable<int> RelatedIDs; //This can be an issue
}

Originally the problem instance of MySessionData was set from a non-serializable list:

MySessionData instance = new MySessionData(){ 
    ID = 123,
    RelatedIDs = nonSerizableList.Select<int>(item => item.ID)
};

The cause here is the concrete class that the Select<int>(...) returns, has type data that's not serializable, and you need to copy the id's to a fresh List<int> to resolve it.

RelatedIDs = nonSerizableList.Select<int>(item => item.ID).ToList();

IF/ELSE Stored Procedure

try

set @tmptype

Find the unique values in a column and then sort them

sort sorts inplace so returns nothing:

In [54]:
df = pd.DataFrame({'A':[1,1,3,2,6,2,8]})
a = df['A'].unique()
a.sort()
a

Out[54]:
array([1, 2, 3, 6, 8], dtype=int64)

So you have to call print a again after the call to sort.

Eg.:

In [55]:
df = pd.DataFrame({'A':[1,1,3,2,6,2,8]})
a = df['A'].unique()
a.sort()
print(a)

[1 2 3 6 8]

Find the greatest number in a list of numbers

max is a builtin function in python, which is used to get max value from a sequence, i.e (list, tuple, set, etc..)

print(max([9, 7, 12, 5]))

# prints 12 

How can I check whether a numpy array is empty or not?

One caveat, though. Note that np.array(None).size returns 1! This is because a.size is equivalent to np.prod(a.shape), np.array(None).shape is (), and an empty product is 1.

>>> import numpy as np
>>> np.array(None).size
1
>>> np.array(None).shape
()
>>> np.prod(())
1.0

Therefore, I use the following to test if a numpy array has elements:

>>> def elements(array):
    ...     return array.ndim and array.size

>>> elements(np.array(None))
0
>>> elements(np.array([]))
0
>>> elements(np.zeros((2,3,4)))
24

Get table name by constraint name

ALL_CONSTRAINTS describes constraint definitions on tables accessible to the current user.

DBA_CONSTRAINTS describes all constraint definitions in the database.

USER_CONSTRAINTS describes constraint definitions on tables in the current user's schema

Select CONSTRAINT_NAME,CONSTRAINT_TYPE ,TABLE_NAME ,STATUS from 
USER_CONSTRAINTS;

'module' has no attribute 'urlencode'

urllib has been split up in Python 3.

The urllib.urlencode() function is now urllib.parse.urlencode(),

the urllib.urlopen() function is now urllib.request.urlopen().

error: Error parsing XML: not well-formed (invalid token) ...?

Problem is that you are doing something wrong in XML layout file

android:text=" <- Go Back" // this creates error
android:text="Go Back" // correct way

java.math.BigInteger cannot be cast to java.lang.Long

It's a very old post, but if it benefits anyone, we can do something like this:

Long max=((BigInteger) Collections.max(dynamics)).longValue(); 

Android Service needs to run always (Never pause or stop)

You don't require broadcast receiver. If one would take some pain copy one of the api(serviceconnection) from above example by Stephen Donecker and paste it in google you would get this, https://www.concretepage.com/android/android-local-bound-service-example-with-binder-and-serviceconnection

CORS - How do 'preflight' an httprequest?

Although this thread dates back to 2014, the issue can still be current to many of us. Here is how I dealt with it in a jQuery 1.12 /PHP 5.6 context:

  • jQuery sent its XHR request using only limited headers; only 'Origin' was sent.
  • No preflight request was needed.
  • The server only had to detect such a request, and add the "Access-Control-Allow-Origin: " . $_SERVER['HTTP_ORIGIN'] header, after detecting that this was a cross-origin XHR.

PHP Code sample:

if (!empty($_SERVER['HTTP_ORIGIN'])) {
    // Uh oh, this XHR comes from outer space...
    // Use this opportunity to filter out referers that shouldn't be allowed to see this request
    if (!preg_match('@\.partner\.domain\.net$@'))
        die("End of the road if you're not my business partner.");

    // otherwise oblige
    header("Access-Control-Allow-Origin: " . $_SERVER['HTTP_ORIGIN']);
}
else {
    // local request, no need to send a specific header for CORS
}

In particular, don't add an exit; as no preflight is needed.

How to fill DataTable with SQL Table

You can make method which return the datatable of given sql query:

public DataTable GetDataTable()
{
SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["BarManConnectionString"].ConnectionString);
conn.Open();
string query = "SELECT * FROM [EventOne] ";

SqlCommand cmd = new SqlCommand(query, conn);

DataTable t1 = new DataTable();
using (SqlDataAdapter a = new SqlDataAdapter(cmd))
{
    a.Fill(t1);
}
return t1;
}

and now can be used like this:

table = GetDataTable();

How to resize the jQuery DatePicker control

Add

div.ui-datepicker, .ui-datepicker td{
 font-size:10px;
}

in a stylesheet loaded after the ui-files. This will also resize the date items.

How to run the sftp command with a password from Bash script?

Combine sshpass with a locked-down credentials file and, in practice, it's as secure as anything - if you've got root on the box to read the credentials file, all bets are off anyway.

What's the difference between align-content and align-items?

Well I have examined them on my browser.

align-content can change a line's height for row direction or width for column when it's value is stretch, or add empty space between or around the lines for space-between, space-around, flex-start, flex-end values.

align-items can change items height or position inside the line's area. When items are not wrapped they have only one line which it's area is always stretched to the flex-box area (even if the items overflow), and align-content has no effect on a single line. So it has no effect on items that are not wrapped and only align-items can change items position or stretch them when all of them are on a single line.

However, if they are wrapped you have multiple lines and items inside each line. And if all items of each line have the same height (for row direction) that line's height will be equal to those items height and you don't see any effect by changing align-items value.

So if you want to affect items by align-items when your items are wrapped and have the same height (for row direction) first you have to use align-content with stretch value in order to expand the lines area.

Remove characters from NSString?

If you want to support more than one space at a time, or support any whitespace, you can do this:

NSString* noSpaces =
    [[myString componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceCharacterSet]]
                           componentsJoinedByString:@""];

Is it worth using Python's re.compile?

FWIW:

$ python -m timeit -s "import re" "re.match('hello', 'hello world')"
100000 loops, best of 3: 3.82 usec per loop

$ python -m timeit -s "import re; h=re.compile('hello')" "h.match('hello world')"
1000000 loops, best of 3: 1.26 usec per loop

so, if you're going to be using the same regex a lot, it may be worth it to do re.compile (especially for more complex regexes).

The standard arguments against premature optimization apply, but I don't think you really lose much clarity/straightforwardness by using re.compile if you suspect that your regexps may become a performance bottleneck.

Update:

Under Python 3.6 (I suspect the above timings were done using Python 2.x) and 2018 hardware (MacBook Pro), I now get the following timings:

% python -m timeit -s "import re" "re.match('hello', 'hello world')"
1000000 loops, best of 3: 0.661 usec per loop

% python -m timeit -s "import re; h=re.compile('hello')" "h.match('hello world')"
1000000 loops, best of 3: 0.285 usec per loop

% python -m timeit -s "import re" "h=re.compile('hello'); h.match('hello world')"
1000000 loops, best of 3: 0.65 usec per loop

% python --version
Python 3.6.5 :: Anaconda, Inc.

I also added a case (notice the quotation mark differences between the last two runs) that shows that re.match(x, ...) is literally [roughly] equivalent to re.compile(x).match(...), i.e. no behind-the-scenes caching of the compiled representation seems to happen.

When should you use 'friend' in C++?

The tree example is a pretty good example : Having an object implemented in a few different class without having an inheritance relationship.

Maybe you could also need it to have a constructor protected and force people to use your "friend" factory.

... Ok, Well frankly you can live without it.

Set custom HTML5 required field validation message

Just need to get the element and use the method setCustomValidity.

Example

var foo = document.getElementById('foo');
foo.setCustomValidity(' An error occurred');

Ubuntu: OpenJDK 8 - Unable to locate package

I was having the same issue and tried all of the solutions on this page but none of them did the trick.

What finally worked was adding the universe repo to my repo list. To do that run the following command

sudo add-apt-repository universe

After running the above command I was able to run

sudo apt install openjdk-8-jre

without an issue and the package was installed.

Hope this helps someone.

Removing duplicates from a SQL query (not just "use distinct")

If I understand you correctly, you want a list of all pictures with the same name (and their different ids) such that their name occurs more than once in the table. I think this will do the trick:

SELECT U.NAME, P.PIC_ID
FROM USERS U, PICTURES P, POSTINGS P1
WHERE U.EMAIL_ID = P1.EMAIL_ID AND P1.PIC_ID = P.PIC_ID AND U.Name IN (
SELECT U.Name 
FROM USERS U, PICTURES P, POSTINGS P1
WHERE U.EMAIL_ID = P1.EMAIL_ID AND P1.PIC_ID = P.PIC_ID AND P.CAPTION LIKE '%car%';
GROUP BY U.Name HAVING COUNT(U.Name) > 1)

I haven't executed it, so there may be a syntax error or two there.

How to auto-reload files in Node.js?

Not necessary to use nodemon or other tools like that. Just use capabilities of your IDE.

Probably best one is IntelliJ WebStorm with hot reload feature (automatic server and browser reload) for node.js.

Select NOT IN multiple columns

I use a way that may look stupid but it works for me. I simply concat the columns I want to compare and use NOT IN:

SELECT *
FROM table1 t1
WHERE CONCAT(t1.first_name,t1.last_name) NOT IN (SELECT CONCAT(t2.first_name,t2.last_name) FROM table2 t2)

Automatically create an Enum based on values in a database lookup table?

Does it have to be an actual enum? How about using a Dictionary<string,int> instead?

for example

Dictionary<string, int> MyEnum = new Dictionary(){{"One", 1}, {"Two", 2}};
Console.WriteLine(MyEnum["One"]);

Inner join of DataTables in C#

I wanted a function that would join tables without requiring you to define the columns using an anonymous type selector, but had a hard time finding any. I ended up having to make my own. Hopefully this will help anyone in the future who searches for this:

private DataTable JoinDataTables(DataTable t1, DataTable t2, params Func<DataRow, DataRow, bool>[] joinOn)
{
    DataTable result = new DataTable();
    foreach (DataColumn col in t1.Columns)
    {
        if (result.Columns[col.ColumnName] == null)
            result.Columns.Add(col.ColumnName, col.DataType);
    }
    foreach (DataColumn col in t2.Columns)
    {
        if (result.Columns[col.ColumnName] == null)
            result.Columns.Add(col.ColumnName, col.DataType);
    }
    foreach (DataRow row1 in t1.Rows)
    {
        var joinRows = t2.AsEnumerable().Where(row2 =>
            {
                foreach (var parameter in joinOn)
                {
                    if (!parameter(row1, row2)) return false;
                }
                return true;
            });
        foreach (DataRow fromRow in joinRows)
        {
            DataRow insertRow = result.NewRow();
            foreach (DataColumn col1 in t1.Columns)
            {
                insertRow[col1.ColumnName] = row1[col1.ColumnName];
            }
            foreach (DataColumn col2 in t2.Columns)
            {
                insertRow[col2.ColumnName] = fromRow[col2.ColumnName];
            }
            result.Rows.Add(insertRow);
        }
    }
    return result;
}

An example of how you might use this:

var test = JoinDataTables(transactionInfo, transactionItems,
               (row1, row2) =>
               row1.Field<int>("TransactionID") == row2.Field<int>("TransactionID"));

One caveat: This is certainly not optimized, so be mindful when getting to row counts above 20k. If you know that one table will be larger than the other, try to put the smaller one first and the larger one second.

How can I loop through a C++ map of maps?

First solution is Use range_based for loop, like:

Note: When range_expression’s type is std::map then a range_declaration’s type is std::pair.

for ( range_declaration : range_expression )      
  //loop_statement

Code 1:

typedef std::map<std::string, std::map<std::string, std::string>> StringToStringMap;

StringToStringMap my_map;

for(const auto &pair1 : my_map) 
{
   // Type of pair1 is std::pair<std::string, std::map<std::string, std::string>>
   // pair1.first point to std::string (first key)
   // pair1.second point to std::map<std::string, std::string> (inner map)
   for(const auto &pair2 : pair1.second) 
   {
       // pair2.first is the second(inner) key
       // pair2.second is the value
   }
}

The Second Solution:

Code 2

typedef std::map<std::string, std::string> StringMap;
typedef std::map<std::string, StringMap> StringToStringMap;

StringToStringMap my_map;

for(StringToStringMap::iterator it1 = my_map.begin(); it1 != my_map.end(); it1++)
{
    // it1->first point to first key
    // it2->second point to inner map
    for(StringMap::iterator it2 = it1->second.begin(); it2 != it1->second.end(); it2++)
     {
        // it2->second point to value
        // it2->first point to second(inner) key 
     }
 }

How to check if PHP array is associative or sequential?

One way to approach this is to piggyback on json_encode, which already has its own internal method of differentiating between an associative array and an indexed array in order to output the correct JSON.

You can do this by checking to see if the first character returned after encoding is a { (associative array) or a [ (indexed array).

// Too short :)
function is_assoc($arr) {
    ksort($arr);
    return json_encode($arr)[0] === '{';
}

Autonumber value of last inserted row - MS Access / VBA

This is an adaptation from my code for you. I was inspired from developpez.com (Look in the page for : "Pour insérer des données, vaut-il mieux passer par un RecordSet ou par une requête de type INSERT ?"). They explain (with a little French). This way is much faster than the one upper. In the example, this way was 37 times faster. Try it.

Const tableName As String = "InvoiceNumbers"
Const columnIdName As String = "??"
Const columnDateName As String = "date"

Dim rsTable As DAO.recordSet
Dim recordId as long

Set rsTable = CurrentDb.OpenRecordset(tableName)
Call rsTable .AddNew
recordId = CLng(rsTable (columnIdName)) ' Save your Id in a variable
rsTable (columnDateName) = Now()        ' Store your data
rsTable .Update

recordSet.Close

LeCygne

How to update std::map after using the find method?

You can update the value like following

   auto itr = m.find('ch'); 
     if (itr != m.end()){
           (*itr).second = 98;
     }

Short rot13 function - Python

Try this:

import codecs
codecs.encode("text to be rot13()'ed", "rot_13")

How do I expire a PHP session after 30 minutes?

Just Store the current time and If it exceeds 30 minutes by comparing then destroy the current session.

How to Call Controller Actions using JQuery in ASP.NET MVC

You can easily call any controller's action using jQuery AJAX method like this:

Note in this example my controller name is Student

Controller Action

 public ActionResult Test()
 {
     return View();
 }

In Any View of this above controller you can call the Test() action like this:

<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.0.3.min.js"></script>
<script>
    $(document).ready(function () {
        $.ajax({
            url: "@Url.Action("Test", "Student")",
            success: function (result, status, xhr) {
                alert("Result: " + status + " " + xhr.status + " " + xhr.statusText)
            },
            error: function (xhr, status, error) {
                alert("Result: " + status + " " + error + " " + xhr.status + " " + xhr.statusText)
            }
        });
    });
</script>

Get first letter of a string from column

.str.get

This is the simplest to specify string methods

# Setup
df = pd.DataFrame({'A': ['xyz', 'abc', 'foobar'], 'B': [123, 456, 789]})
df

        A    B
0     xyz  123
1     abc  456
2  foobar  789

df.dtypes

A    object
B     int64
dtype: object

For string (read:object) type columns, use

df['C'] = df['A'].str[0]
# Similar to,
df['C'] = df['A'].str.get(0)

.str handles NaNs by returning NaN as the output.

For non-numeric columns, an .astype conversion is required beforehand, as shown in @Ed Chum's answer.

# Note that this won't work well if the data has NaNs. 
# It'll return lowercase "n"
df['D'] = df['B'].astype(str).str[0]

df
        A    B  C  D
0     xyz  123  x  1
1     abc  456  a  4
2  foobar  789  f  7

List Comprehension and Indexing

There is enough evidence to suggest a simple list comprehension will work well here and probably be faster.

# For string columns
df['C'] = [x[0] for x in df['A']]

# For numeric columns
df['D'] = [str(x)[0] for x in df['B']]

df
        A    B  C  D
0     xyz  123  x  1
1     abc  456  a  4
2  foobar  789  f  7

If your data has NaNs, then you will need to handle this appropriately with an if/else in the list comprehension,

df2 = pd.DataFrame({'A': ['xyz', np.nan, 'foobar'], 'B': [123, 456, np.nan]})
df2

        A      B
0     xyz  123.0
1     NaN  456.0
2  foobar    NaN

# For string columns
df2['C'] = [x[0] if isinstance(x, str) else np.nan for x in df2['A']]

# For numeric columns
df2['D'] = [str(x)[0] if pd.notna(x) else np.nan for x in df2['B']]

        A      B    C    D
0     xyz  123.0    x    1
1     NaN  456.0  NaN    4
2  foobar    NaN    f  NaN

Let's do some timeit tests on some larger data.

df_ = df.copy()
df = pd.concat([df_] * 5000, ignore_index=True) 

%timeit df.assign(C=df['A'].str[0])
%timeit df.assign(D=df['B'].astype(str).str[0])

%timeit df.assign(C=[x[0] for x in df['A']])
%timeit df.assign(D=[str(x)[0] for x in df['B']])

12 ms ± 253 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
27.1 ms ± 1.38 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

3.77 ms ± 110 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
7.84 ms ± 145 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

List comprehensions are 4x faster.

Immutable array in Java

Another one answer

static class ImmutableArray<T> {
    private final T[] array;

    private ImmutableArray(T[] a){
        array = Arrays.copyOf(a, a.length);
    }

    public static <T> ImmutableArray<T> from(T[] a){
        return new ImmutableArray<T>(a);
    }

    public T get(int index){
        return array[index];
    }
}

{
    final ImmutableArray<String> sample = ImmutableArray.from(new String[]{"a", "b", "c"});
}

Command-line svn for Windows?

cygwin is another option. It has a port of svn.

unsigned APK can not be installed

I cannot install an apk build with "Export Unsigned Application Package" Android SDK feature, but i can install an apk browsing the bin directory of my project after the project buid. I put this apk on my sd on my HTC Wildfire phone, select it and the application install correctly. You need to allow your phone to install unsigned apk. Good Luck.

How to use session in JSP pages to get information?

_x000D_
_x000D_
form action="editinfo" method="post">_x000D_
<table>_x000D_
  <tr>_x000D_
    <td>Username:</td>_x000D_
    <td>_x000D_
      <input type="text" value="<%if( request.getSession().getAttribute(" parameter_whatever_you_passed ") != null_x000D_
{_x000D_
request.getSession().getAttribute("parameter_whatever_you_passed ").toString();_x000D_
}_x000D_
 %>" />_x000D_
    </td>_x000D_
  </tr>_x000D_
</table>_x000D_
</form>
_x000D_
_x000D_
_x000D_

HTTP Range header

Contrary to Mark Novakowski answer, which for some reason has been upvoted by many, yes, it is a valid and satisfiable request.

In fact the standard, as Wrikken pointed out, makes just such an example. In practice, Apache responds to such requests as expected (with a 206 code), and this is exactly what I use to implement progressive download, that is, only get the tail of a long log file which grows in real time with polling.

How to process SIGTERM signal gracefully?

A class based clean to use solution:

import signal
import time

class GracefulKiller:
  kill_now = False
  def __init__(self):
    signal.signal(signal.SIGINT, self.exit_gracefully)
    signal.signal(signal.SIGTERM, self.exit_gracefully)

  def exit_gracefully(self,signum, frame):
    self.kill_now = True

if __name__ == '__main__':
  killer = GracefulKiller()
  while not killer.kill_now:
    time.sleep(1)
    print("doing something in a loop ...")

  print("End of the program. I was killed gracefully :)")

How to get a ListBox ItemTemplate to stretch horizontally the full width of the ListBox?

I'm sure this is a duplicate, but I can't find a question with the same answer.

Add HorizontalContentAlignment="Stretch" to your ListBox. That should do the trick. Just be careful with auto-complete because it is so easy to get HorizontalAlignment by mistake.

Save file Javascript with file name

function saveAs(uri, filename) {
    var link = document.createElement('a');
    if (typeof link.download === 'string') {
        document.body.appendChild(link); // Firefox requires the link to be in the body
        link.download = filename;
        link.href = uri;
        link.click();
        document.body.removeChild(link); // remove the link when done
    } else {
        location.replace(uri);
    }
}

dispatch_after - GCD in Swift?

In Swift 3.0

Dispatch queues

  DispatchQueue(label: "test").async {
        //long running Background Task
        for obj in 0...1000 {
            print("async \(obj)")
        }

        // UI update in main queue
        DispatchQueue.main.async(execute: { 
            print("UI update on main queue")
        })

    }

    DispatchQueue(label: "m").sync {
        //long running Background Task
        for obj in 0...1000 {
            print("sync \(obj)")
        }

        // UI update in main queue
        DispatchQueue.main.sync(execute: {
            print("UI update on main queue")
        })
    }

Dispatch after 5 seconds

    DispatchQueue.main.after(when: DispatchTime.now() + 5) {
        print("Dispatch after 5 sec")
    }

Prevent redirect after form is submitted

You can use as below

e.preventDefault() 

If this method is called, the default action of the event will not be triggered.

Also if I may suggest read this: .prop() vs .attr()

I hope it will help you,

code example:

$('a').click(function(event){
    event.preventDefault();
    //do what you want
  } 

What does a question mark represent in SQL queries?

What you are seeing is a parameterized query. They are frequently used when executing dynamic SQL from a program.

For example, instead of writing this (note: pseudocode):

ODBCCommand cmd = new ODBCCommand("SELECT thingA FROM tableA WHERE thingB = 7")
result = cmd.Execute()

You write this:

ODBCCommand cmd = new ODBCCommand("SELECT thingA FROM tableA WHERE thingB = ?")
cmd.Parameters.Add(7)
result = cmd.Execute()

This has many advantages, as is probably obvious. One of the most important: the library functions which parse your parameters are clever, and ensure that strings are escaped properly. For example, if you write this:

string s = getStudentName()
cmd.CommandText = "SELECT * FROM students WHERE (name = '" + s + "')"
cmd.Execute()

What happens when the user enters this?

Robert'); DROP TABLE students; --

(Answer is here)

Write this instead:

s = getStudentName()
cmd.CommandText = "SELECT * FROM students WHERE name = ?"
cmd.Parameters.Add(s)
cmd.Execute()

Then the library will sanitize the input, producing this:

"SELECT * FROM students where name = 'Robert''); DROP TABLE students; --'"

Not all DBMS's use ?. MS SQL uses named parameters, which I consider a huge improvement:

cmd.Text = "SELECT thingA FROM tableA WHERE thingB = @varname"
cmd.Parameters.AddWithValue("@varname", 7)
result = cmd.Execute()

What is the Windows version of cron?

For the original question, asking about Windows XP (and Windows 7): Windows Task Scheduler

For command-line usage, you can schedule with the AT command.

For newer Microsoft OS versions, Windows Server 2012 / Windows 8, look at the schtasks command line utility.
If using PowerShell, the Scheduled Tasks Cmdlets in Windows PowerShell are made for scripting.

Best way to do multi-row insert in Oracle?

Use SQL*Loader. It takes a little setting up, but if this isn't a one off, its worth it.

Create Table

SQL> create table ldr_test (id number(10) primary key, description varchar2(20));
Table created.
SQL>

Create CSV

oracle-2% cat ldr_test.csv
1,Apple
2,Orange
3,Pear
oracle-2% 

Create Loader Control File

oracle-2% cat ldr_test.ctl 
load data

 infile 'ldr_test.csv'
 into table ldr_test
 fields terminated by "," optionally enclosed by '"'              
 ( id, description )

oracle-2% 

Run SQL*Loader command

oracle-2% sqlldr <username> control=ldr_test.ctl
Password:

SQL*Loader: Release 9.2.0.5.0 - Production on Wed Sep 3 12:26:46 2008

Copyright (c) 1982, 2002, Oracle Corporation.  All rights reserved.

Commit point reached - logical record count 3

Confirm insert

SQL> select * from ldr_test;

        ID DESCRIPTION
---------- --------------------
         1 Apple
         2 Orange
         3 Pear

SQL>

SQL*Loader has alot of options, and can take pretty much any text file as its input. You can even inline the data in your control file if you want.

Here is a page with some more details -> SQL*Loader

Escape a string in SQL Server so that it is safe to use in LIKE expression

Rather than escaping all characters in a string that have particular significance in the pattern syntax given that you are using a leading wildcard in the pattern it is quicker and easier just to do.

SELECT * 
FROM YourTable
WHERE CHARINDEX(@myString , YourColumn) > 0

In cases where you are not using a leading wildcard the approach above should be avoided however as it cannot use an index on YourColumn.

Additionally in cases where the optimum execution plan will vary according to the number of matching rows the estimates may be better when using LIKE with the square bracket escaping syntax when compared to both CHARINDEX and the ESCAPE keyword.

Check if value already exists within list of dictionaries?

Following works out for me.

    #!/usr/bin/env python
    a = [{ 'main_color': 'red', 'second_color':'blue'},
    { 'main_color': 'yellow', 'second_color':'green'},
    { 'main_color': 'yellow', 'second_color':'blue'}]

    found_event = next(
            filter(
                lambda x: x['main_color'] == 'red',
                a
            ),
      #return this dict when not found
            dict(
                name='red',
                value='{}'
            )
        )

    if found_event:
        print(found_event)

    $python  /tmp/x
    {'main_color': 'red', 'second_color': 'blue'}

Requery a subform from another form?

You must use the name of the subform control, not the name of the subform, though these are often the same:

 Forms![MainForm]![subform control name Name].Form.Requery

Or, if you are on the main form:

 Me.[subform control name Name].Form.Requery

More Info: http://www.mvps.org/access/forms/frm0031.htm

"The page you are requesting cannot be served because of the extension configuration." error message

If you are trying to view an extensionless file what worked for me was adding a MIME Type: File name extension: . MIME type: text/plain

This might have some MVC implications, especially if your Static File Handler is above the Extensionless... handlers (under IIS / Handler Mappings) but might be a work around when you only need this temporarily, like activating SSL Certs.

Dark color scheme for Eclipse

I have to say, this is one area where Eclipse is really weak. Specifically, the import/export of preferences applies to ALL preferences. There is no way to import say just the fonts/color preferences (like you can with Visual Studio) without mucking up my key binding preferences.

Also, I have tried several of these preference files referenced above, and they completely break my Eclipse install.

Delete a row in Excel VBA

Better yet, use union to grab all the rows you want to delete, then delete them all at once. The rows need not be continuous.

dim rng as range
dim rDel as range

for each rng in {the range you're searching}
   if {Conditions to be met} = true then
      if not rDel is nothing then
         set rDel = union(rng,rDel)
      else
         set rDel = rng
      end if
   end if
 next
 
 rDel.entirerow.delete

That way you don't have to worry about sorting or things being at the bottom.

Including non-Python files with setup.py

Figured out a workaround: I renamed my lgpl2.1_license.txt to lgpl2.1_license.txt.py, and put some triple quotes around the text. Now I don't need to use the data_files option nor to specify any absolute paths. Making it a Python module is ugly, I know, but I consider it less ugly than specifying absolute paths.

Simulate a specific CURL in PostMan

As per the above answers, it works well.

If we paste curl requests with Authorization data in import, Postman will set all headers automatically. We only just pass row JSON data in the request body if needed or Upload images through form-data in the body.

This is just an example. Your API should be a different one (if your API allows)

curl -X POST 'https://verifyUser.abc.com/api/v1/verification' \
    -H 'secret: secret' \
    -H 'email: [email protected]' \
    -H 'accept: application/json, text/plain, */*' \
    -H 'authorizationtoken: bearer' \
    -F 'referenceFilePath= Add file path' \
    --compressed

Good NumericUpDown equivalent in WPF?

If commercial solutions are ok, you may consider this control set: WPF Elements by Mindscape

It contains such a spin control and alternatively (my personal preference) a spin-decorator, that can decorate various numeric controls (like IntegerTextBox, NumericTextBox, also part of the control set) in XAML like this:

<WpfElements:SpinDecorator>
   <WpfElements:IntegerTextBox Text="{Binding Foo}" />
</WpfElements:SpinDecorator>

Convert datatable to JSON in C#

Convert datatable to JSON using C#.net

 public static object DataTableToJSON(DataTable table)
    {
        var list = new List<Dictionary<string, object>>();

        foreach (DataRow row in table.Rows)
        {
            var dict = new Dictionary<string, object>();

            foreach (DataColumn col in table.Columns)
            {
                dict[col.ColumnName] = (Convert.ToString(row[col]));
            }
            list.Add(dict);
        }
        JavaScriptSerializer serializer = new JavaScriptSerializer();

        return serializer.Serialize(list);
    }

Removing items from a ListBox in VB.net

If you only want to clear the list box, you should use the Clear (winforms | wpf | asp.net) method:

ListBox2.Items.Clear()

Globally catch exceptions in a WPF application?

AppDomain.UnhandledException Event

This event provides notification of uncaught exceptions. It allows the application to log information about the exception before the system default handler reports the exception to the user and terminates the application.

   public App()
   {
      AppDomain currentDomain = AppDomain.CurrentDomain;
      currentDomain.UnhandledException += new UnhandledExceptionEventHandler(MyHandler);    
   }

   static void MyHandler(object sender, UnhandledExceptionEventArgs args) 
   {
      Exception e = (Exception) args.ExceptionObject;
      Console.WriteLine("MyHandler caught : " + e.Message);
      Console.WriteLine("Runtime terminating: {0}", args.IsTerminating);
   }

If the UnhandledException event is handled in the default application domain, it is raised there for any unhandled exception in any thread, no matter what application domain the thread started in. If the thread started in an application domain that has an event handler for UnhandledException, the event is raised in that application domain. If that application domain is not the default application domain, and there is also an event handler in the default application domain, the event is raised in both application domains.

For example, suppose a thread starts in application domain "AD1", calls a method in application domain "AD2", and from there calls a method in application domain "AD3", where it throws an exception. The first application domain in which the UnhandledException event can be raised is "AD1". If that application domain is not the default application domain, the event can also be raised in the default application domain.

How to get a .csv file into R?

As Dirk said, the function you are after is 'read.csv' or one of the other read.table variants. Given your sample data above, I think you will want to do something like this:

setwd("c:/random/directory")

df <- read.csv("myRandomFile.csv", header=TRUE)

All we did in the above was set the directory to where your .csv file is and then read the .csv into a dataframe named df. You can check that the data loaded properly by checking the structure of the object with:

str(df)

Assuming the data loaded properly, you can think go on to perform any number of statistical methods with the data in your data frame. I think summary(df) would be a good place to start. Learning how to use the help in R will be immensely useful, and a quick read through the help on CRAN will save you lots of time in the future: http://cran.r-project.org/

In practice, what are the main uses for the new "yield from" syntax in Python 3.3?

A short example will help you understand one of yield from's use case: get value from another generator

def flatten(sequence):
    """flatten a multi level list or something
    >>> list(flatten([1, [2], 3]))
    [1, 2, 3]
    >>> list(flatten([1, [2], [3, [4]]]))
    [1, 2, 3, 4]
    """
    for element in sequence:
        if hasattr(element, '__iter__'):
            yield from flatten(element)
        else:
            yield element

print(list(flatten([1, [2], [3, [4]]])))

Bash: Syntax error: redirection unexpected

Docker:

I was getting this problem from my Dockerfile as I had:

RUN bash < <(curl -s -S -L https://raw.githubusercontent.com/moovweb/gvm/master/binscripts/gvm-installer)

However, according to this issue, it was solved:

The exec form makes it possible to avoid shell string munging, and to RUN commands using a base image that does not contain /bin/sh.

Note

To use a different shell, other than /bin/sh, use the exec form passing in the desired shell. For example,

RUN ["/bin/bash", "-c", "echo hello"]

Solution:

RUN ["/bin/bash", "-c", "bash < <(curl -s -S -L https://raw.githubusercontent.com/moovweb/gvm/master/binscripts/gvm-installer)"]

Notice the quotes around each parameter.

How to compare strings in C conditional preprocessor-directives

The following worked for me with clang. Allows what appears as symbolic macro value comparison. #error xxx is just to see what compiler really does. Replacing cat definition with #define cat(a,b) a ## b breaks things.

#define cat(a,...) cat_impl(a, __VA_ARGS__)
#define cat_impl(a,...) a ## __VA_ARGS__

#define xUSER_jack 0
#define xUSER_queen 1
#define USER_VAL cat(xUSER_,USER)

#define USER jack // jack or queen

#if USER_VAL==xUSER_jack
  #error USER=jack
  #define USER_VS "queen"
#elif USER_VAL==xUSER_queen
  #error USER=queen
  #define USER_VS "jack"
#endif

Working with TIFFs (import, export) in Python using numpy

In case of image stacks, I find it easier to use scikit-image to read, and matplotlib to show or save. I have handled 16-bit TIFF image stacks with the following code.

from skimage import io
import matplotlib.pyplot as plt

# read the image stack
img = io.imread('a_image.tif')
# show the image
plt.imshow(mol,cmap='gray')
plt.axis('off')
# save the image
plt.savefig('output.tif', transparent=True, dpi=300, bbox_inches="tight", pad_inches=0.0)

How to align a <div> to the middle (horizontally/width) of the page

Add this class to the div you want centered (which should have a set width):

.marginAutoLR
{
    margin-right:auto;
    margin-left:auto;
}

Or, add the margin stuff to your div class, like this:

.divClass
{
    width:300px;
    margin-right:auto;
    margin-left:auto;
}

How can I convert spaces to tabs in Vim or Linux?

:%s/\(^\s*\)\@<=    /\t/g

Translation: Search for every instance of 4 consecutive spaces (after the = character), but only if the entire line up to that point is whitespace (this uses the zero-width look-behind assertion, \@<=). Replace each found instance with a tab character.

javascript regex for password containing at least 8 characters, 1 number, 1 upper and 1 lowercase

Your regex only allows exactly 8 characters. Use {8,} to specify eight or more instead of {8}.

But why would you limit the allowed character range for your passwords? 8-character alphanumeric passwords can be bruteforced by my phone within minutes.

JPA & Criteria API - Select only specific columns

One of the JPA ways for getting only particular columns is to ask for a Tuple object.

In your case you would need to write something like this:

CriteriaQuery<Tuple> cq = builder.createTupleQuery();
// write the Root, Path elements as usual
Root<EntityClazz> root = cq.from(EntityClazz.class);
cq.multiselect(root.get(EntityClazz_.ID), root.get(EntityClazz_.VERSION));  //using metamodel
List<Tuple> tupleResult = em.createQuery(cq).getResultList();
for (Tuple t : tupleResult) {
    Long id = (Long) t.get(0);
    Long version = (Long) t.get(1);
}

Another approach is possible if you have a class representing the result, like T in your case. T doesn't need to be an Entity class. If T has a constructor like:

public T(Long id, Long version)

then you can use T directly in your CriteriaQuery constructor:

CriteriaQuery<T> cq = builder.createQuery(T.class);
// write the Root, Path elements as usual
Root<EntityClazz> root = cq.from(EntityClazz.class);
cq.multiselect(root.get(EntityClazz_.ID), root.get(EntityClazz_.VERSION));  //using metamodel
List<T> result = em.createQuery(cq).getResultList();

See this link for further reference.

jQuery Set Cursor Position in Text Area

Based on this question, the answer will not work perfectly for ie and opera when there is new line in the textarea. The answer explain how to adjust the selectionStart, selectionEnd before calling setSelectionRange.

I have try the adjustOffset from the other question with the solution proposed by @AVProgrammer and it work.

function adjustOffset(el, offset) {
    /* From https://stackoverflow.com/a/8928945/611741 */
    var val = el.value, newOffset = offset;
    if (val.indexOf("\r\n") > -1) {
        var matches = val.replace(/\r\n/g, "\n").slice(0, offset).match(/\n/g);
        newOffset += matches ? matches.length : 0;
    }
    return newOffset;
}

$.fn.setCursorPosition = function(position){
    /* From https://stackoverflow.com/a/7180862/611741 */
    if(this.lengh == 0) return this;
    return $(this).setSelection(position, position);
}

$.fn.setSelection = function(selectionStart, selectionEnd) {
    /* From https://stackoverflow.com/a/7180862/611741 
       modified to fit https://stackoverflow.com/a/8928945/611741 */
    if(this.lengh == 0) return this;
    input = this[0];

    if (input.createTextRange) {
        var range = input.createTextRange();
        range.collapse(true);
        range.moveEnd('character', selectionEnd);
        range.moveStart('character', selectionStart);
        range.select();
    } else if (input.setSelectionRange) {
        input.focus();
        selectionStart = adjustOffset(input, selectionStart);
        selectionEnd = adjustOffset(input, selectionEnd);
        input.setSelectionRange(selectionStart, selectionEnd);
    }

    return this;
}

$.fn.focusEnd = function(){
    /* From https://stackoverflow.com/a/7180862/611741 */
    this.setCursorPosition(this.val().length);
}

Express: How to pass app-instance to routes from a different file?

Node.js supports circular dependencies.
Making use of circular dependencies instead of require('./routes')(app) cleans up a lot of code and makes each module less interdependent on its loading file:


app.js

var app = module.exports = express(); //now app.js can be required to bring app into any file

//some app/middleware setup, etc, including 
app.use(app.router);

require('./routes'); //module.exports must be defined before this line


routes/index.js

var app = require('../app');

app.get('/', function(req, res, next) {
  res.render('index');
});

//require in some other route files...each of which requires app independently
require('./user');
require('./blog');


-----04/2014 update-----
Express 4.0 fixed the usecase for defining routes by adding an express.router() method!
documentation - http://expressjs.com/4x/api.html#router

Example from their new generator:
Writing the route:
https://github.com/expressjs/generator/blob/master/templates/js/routes/index.js
Adding/namespacing it to the app: https://github.com/expressjs/generator/blob/master/templates/js/app.js#L24

There are still usecases for accessing app from other resources, so circular dependencies are still a valid solution.

What is .htaccess file?

.htaccess is a configuration file for use on web servers running the Apache Web Server software.

When a .htaccess file is placed in a directory which is in turn 'loaded via the Apache Web Server', then the .htaccess file is detected and executed by the Apache Web Server software.

These .htaccess files can be used to alter the configuration of the Apache Web Server software to enable/disable additional functionality and features that the Apache Web Server software has to offer.

These facilities include basic redirect functionality, for instance if a 404 file not found error occurs, or for more advanced functions such as content password protection or image hot link prevention.

Whenever any request is sent to the server it always passes through .htaccess file. There are some rules are defined to instruct the working.

Reverse HashMap keys and values in Java

Iterate through the list of keys and values, then add them.

HashMap<String, Character> reversedHashMap = new HashMap<String, Character>();
for (String key : myHashMap.keySet()){
    reversedHashMap.put(myHashMap.get(key), key);
}

FFT in a single C-file

This file works properly as it is: just copy and paste in your computer. Surfing on the web I have found this easy implementation on wikipedia page here. The page is in italian, so I re-wrote the code with some translations. Here there are almost the same informations but in english. ENJOY!

#include <iostream>
#include <complex>
#define MAX 200

using namespace std;

#define M_PI 3.1415926535897932384

int log2(int N)    /*function to calculate the log2(.) of int numbers*/
{
  int k = N, i = 0;
  while(k) {
    k >>= 1;
    i++;
  }
  return i - 1;
}

int check(int n)    //checking if the number of element is a power of 2
{
  return n > 0 && (n & (n - 1)) == 0;
}

int reverse(int N, int n)    //calculating revers number
{
  int j, p = 0;
  for(j = 1; j <= log2(N); j++) {
    if(n & (1 << (log2(N) - j)))
      p |= 1 << (j - 1);
  }
  return p;
}

void ordina(complex<double>* f1, int N) //using the reverse order in the array
{
  complex<double> f2[MAX];
  for(int i = 0; i < N; i++)
    f2[i] = f1[reverse(N, i)];
  for(int j = 0; j < N; j++)
    f1[j] = f2[j];
}

void transform(complex<double>* f, int N) //
{
  ordina(f, N);    //first: reverse order
  complex<double> *W;
  W = (complex<double> *)malloc(N / 2 * sizeof(complex<double>));
  W[1] = polar(1., -2. * M_PI / N);
  W[0] = 1;
  for(int i = 2; i < N / 2; i++)
    W[i] = pow(W[1], i);
  int n = 1;
  int a = N / 2;
  for(int j = 0; j < log2(N); j++) {
    for(int i = 0; i < N; i++) {
      if(!(i & n)) {
        complex<double> temp = f[i];
        complex<double> Temp = W[(i * a) % (n * a)] * f[i + n];
        f[i] = temp + Temp;
        f[i + n] = temp - Temp;
      }
    }
    n *= 2;
    a = a / 2;
  }
  free(W);
}

void FFT(complex<double>* f, int N, double d)
{
  transform(f, N);
  for(int i = 0; i < N; i++)
    f[i] *= d; //multiplying by step
}

int main()
{
  int n;
  do {
    cout << "specify array dimension (MUST be power of 2)" << endl;
    cin >> n;
  } while(!check(n));
  double d;
  cout << "specify sampling step" << endl; //just write 1 in order to have the same results of matlab fft(.)
  cin >> d;
  complex<double> vec[MAX];
  cout << "specify the array" << endl;
  for(int i = 0; i < n; i++) {
    cout << "specify element number: " << i << endl;
    cin >> vec[i];
  }
  FFT(vec, n, d);
  cout << "...printing the FFT of the array specified" << endl;
  for(int j = 0; j < n; j++)
    cout << vec[j] << endl;
  return 0;
}

PHP header() redirect with POST variables

It would be beneficial to verify the form's data before sending it via POST. You should create a JavaScript function to check the form for errors and then send the form. This would prevent the data from being sent over and over again, possibly slowing the browser and using transfer volume on the server.

Edit:

If security is a concern, performing an AJAX request to verify the data would be the best way. The response from the AJAX request would determine whether the form should be submitted.

base_url() function not working in codeigniter

Question -I wanted to load my css file but it was not working even though i autoload and manual laod why ? i found the solution => here is my solution : application>config>config.php $config['base_url'] = 'http://localhost/CodeIgniter/'; //paste the link to base url

question explanation:

" > i had my bootstrap.min.css file inside assets/css folder where assets is root directory which i was created.But it was not working even though when i loaded ? 1. $autoload['helper'] = array('url'); 2. $this->load->helper('url'); in my controllar then i go to my

Run a php app using tomcat?

Yes it is Possible Will Den. we can run PHP code in tomcat server using it's own port number localhost:8080

here I'm writing some step which is so much useful for you.

How to install or run PHP on Tomcat 6 in windows

  1. download and unzip PHP 5 to a directory, c:\php-5.2.6-Win32 - php-5.2.9-2-Win32.zip Download

  2. download PECL 5.2.5 Win32 binaries - PECL 5.2.5 Win32 Download

  3. rename php.ini-dist to php.ini in c:\php-5.2.6-Win32

  4. Uncomment or add the line (remove semi-colon at the beginning) in php.ini: ;extension=php_java.dll

  5. copy php5servlet.dll from PECL 5.2.5 to c:\php-5.2.6-Win32

  6. copy php_java.dll from PECL 5.2.5 to c:\php-5.2.6-Win32\ext

  7. copy php_java.jar from PECL 5.2.5 to tomcat\lib

  8. create a directory named "php" (or what ever u like) in tomcat\webapps directory

  9. copy phpsrvlt.jar from PECL 5.2.5 to tomcat\webapps\php\WEB-INF\lib

  10. Unjar or unzip phpsrvlt.jar for unzip use winrar or winzip for unjar use : jar xfv phpsrvlt.jar

  11. change both net\php\reflect.properties and net\php\servlet.properties to library=php5servlet

  12. Recreate the jar file -> jar cvf php5srvlt.jar net/php/. PS: if the jar file doesnt run you have to add the Path to system variables for me I added C:\Program Files\Java\jdk1.6.0\bin; to System variables/Path

  13. create web.xml in tomcat\webapps\php\WEB-INF with this content:

    <web-app version="2.4" 
      xmlns="http://java.sun.com/xml/ns/j2ee"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance "
      xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee 
      http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd ">
      <servlet>
        <servlet-name>php</servlet-name>
        <servlet-class>net.php.servlet</servlet-class>
      </servlet>
      <servlet>
        <servlet-name>php-formatter</servlet-name>
        <servlet-class>net.php.formatter</servlet-class>
      </servlet>
      <servlet-mapping>
        <servlet-name>php</servlet-name>
        <url-pattern>*.php</url-pattern>
      </servlet-mapping>
      <servlet-mapping>
        <servlet-name>php-formatter</servlet-name>
        <url-pattern>*.phps</url-pattern>
      </servlet-mapping>
    </web-app>
    
  14. Add PHP path( c:\php-5.2.6-Win32) to your System or User Path in Windows enironment (Hint: Right-click and select Properties from My Computer

  15. create test.php for testing under tomcat\webapps\php like

  16. Restart tomcat

  17. browse localhost:8080/php/test.php

R multiple conditions in if statement

Read this thread R - boolean operators && and ||.

Basically, the & is vectorized, i.e. it acts on each element of the comparison returning a logical array with the same dimension as the input. && is not, returning a single logical.

Clearing all cookies with JavaScript

I have some more sophisticated and OOP-oriented cookie control module. It also contains deleteAll method to clear all existing cookie. Make notice that this version of deleteAll method has setting path=/ that causes deleting of all cookies within current domain. If you need to delete cookies only from some scope you will have to upgrade this method my adding dynamic path parameter to this method.

There is main Cookie class:

import {Setter} from './Setter';

export class Cookie {
    /**
     * @param {string} key
     * @return {string|undefined}
     */
    static get(key) {
        key = key.replace(/([\.$?*|{}\(\)\[\]\\\/\+^])/g, '\\$1');

        const regExp = new RegExp('(?:^|; )' + key + '=([^;]*)');
        const matches = document.cookie.match(regExp);

        return matches
            ? decodeURIComponent(matches[1])
            : undefined;
    }

    /**
     * @param {string} name
     */
    static delete(name) {
        this.set(name, '', { expires: -1 });
    }

    static deleteAll() {
        const cookies = document.cookie.split('; ');

        for (let cookie of cookies) {
            const index = cookie.indexOf('=');

            const name = ~index
                ? cookie.substr(0, index)
                : cookie;

            document.cookie = name + '=;expires=Thu, 01 Jan 1970 00:00:00 GMT;path=/';
        }
    }

    /**
     * @param {string} name
     * @param {string|boolean} value
     * @param {{expires?:Date|string|number,path?:string,domain?:string,secure?:boolean}} opts
     */
    static set(name, value, opts = {}) {
        Setter.set(name, value, opts);
    }
}

Cookie setter method (Cookie.set) is rather complex so I decomposed it into other class. There is code of this one:

export class Setter {
    /**
     * @param {string} name
     * @param {string|boolean} value
     * @param {{expires?:Date|string|number,path?:string,domain?:string,secure?:boolean}} opts
     */
    static set(name, value, opts = {}) {
        value = Setter.prepareValue(value);
        opts = Setter.prepareOpts(opts);

        let updatedCookie = name + '=' + value;

        for (let i in opts) {
            if (!opts.hasOwnProperty(i)) continue;

            updatedCookie += '; ' + i;

            const value = opts[i];

            if (value !== true)
                updatedCookie += '=' + value;
        }

        document.cookie = updatedCookie;
    }

    /**
     * @param {string} value
     * @return {string}
     * @private
     */
    static prepareValue(value) {
        return encodeURIComponent(value);
    }

    /**
     * @param {{expires?:Date|string|number,path?:string,domain?:string,secure?:boolean}} opts
     * @private
     */
    static prepareOpts(opts = {}) {
        opts = Object.assign({}, opts);

        let {expires} = opts;

        if (typeof expires == 'number' && expires) {
            const date = new Date();

            date.setTime(date.getTime() + expires * 1000);

            expires = opts.expires = date;
        }

        if (expires && expires.toUTCString)
            opts.expires = expires.toUTCString();

        return opts;
    }
}

matplotlib: colorbars and its text labels

To add to tacaswell's answer, the colorbar() function has an optional cax input you can use to pass an axis on which the colorbar should be drawn. If you are using that input, you can directly set a label using that axis.

import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable

fig, ax = plt.subplots()
heatmap = ax.imshow(data)
divider = make_axes_locatable(ax)
cax = divider.append_axes('bottom', size='10%', pad=0.6)
cb = fig.colorbar(heatmap, cax=cax, orientation='horizontal')

cax.set_xlabel('data label')  # cax == cb.ax

How to run a script as root on Mac OS X?

sudo ./scriptname

sudo bash will basically switch you over to running a shell as root, although it's probably best to stay as su as little as possible.

How do I insert an image in an activity with android studio?

I'll Explain how to add an image using Android studio(2.3.3). First you need to add the image into res/drawable folder in the project. Like below

enter image description here


Now in go to activity_main.xml (or any activity you need to add image) and select the Design view. There you can see your Palette tool box on left side. You need to drag and drop ImageView.

enter image description here

It will prompt you Resources dialog box. In there select Drawable under the project section you can see your image. Like below

enter image description here

Select the image you want press Ok you can see the image on the Design view. If you want it configure using xml it would look like below.

<ImageView
        android:id="@+id/imageView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:srcCompat="@drawable/homepage"
        tools:layout_editor_absoluteX="55dp"
        tools:layout_editor_absoluteY="130dp" />

You need to give image location using

app:srcCompat="@drawable/imagename"

avrdude: stk500v2_ReceiveMessage(): timeout

I've connected to USB port directly in my laptop and timeout issue has been resolved.

Previously tried by port replicator, but it did not even recognized arduino, thus I chosen wrong port - resulting in timeout message.

So make sure that it is visible by your OS.

SimpleDateFormat and locale based format string

SimpleDateFormat dateFormat = new SimpleDateFormat("EEEE dd MMM yyyy", Locale.ENGLISH);
String formatted = dateFormat.format(the_date_you_want_here);

Is SQL syntax case sensitive?

My understanding is that the SQL standard calls for case-insensitivity. I don't believe any databases follow the standard completely, though.

MySQL has a configuration setting as part of its "strict mode" (a grab bag of several settings that make MySQL more standards-compliant) for case sensitive or insensitive table names. Regardless of this setting, column names are still case-insensitive, although I think it affects how the column-names are displayed. I believe this setting is instance-wide, across all databases within the RDBMS instance, although I'm researching today to confirm this (and hoping the answer is no).

I like how Oracle handles this far better. In straight SQL, identifiers like table and column names are case insensitive. However, if for some reason you really desire to get explicit casing, you can enclose the identifier in double-quotes (which are quite different in Oracle SQL from the single-quotes used to enclose string data). So:

SELECT fieldName
FROM tableName;

will query fieldname from tablename, but

SELECT "fieldName"
FROM "tableName";

will query fieldName from tableName.

I'm pretty sure you could even use this mechanism to insert spaces or other non-standard characters into an identifier.

In this situation if for some reason you found explicitly-cased table and column names desirable it was available to you, but it was still something I would highly caution against.

My convention when I used Oracle on a daily basis was that in code I would put all Oracle SQL keywords in uppercase and all identifiers in lowercase. In documentation I would put all table and column names in uppercase. It was very convenient and readable to be able to do this (although sometimes a pain to type so many capitals in code -- I'm sure I could've found an editor feature to help, here).

In my opinion MySQL is particularly bad for differing about this on different platforms. We need to be able to dump databases on Windows and load them into UNIX, and doing so is a disaster if the installer on Windows forgot to put the RDBMS into case-sensitive mode. (To be fair, part of the reason this is a disaster is our coders made the bad decision, long ago, to rely on the case-sensitivity of MySQL on UNIX.) The people who wrote the Windows MySQL installer made it really convenient and Windows-like, and it was great to move toward giving people a checkbox to say "Would you like to turn on strict mode and make MySQL more standards-compliant?" But it is very convenient for MySQL to differ so signficantly from the standard, and then make matters worse by turning around and differing from its own de facto standard on different platforms. I'm sure that on differing Linux distributions this may be further compounded, as packagers for different distros probably have at times incorporated their own preferred MySQL configuration settings.

Here's another SO question that gets into discussing if case-sensitivity is desirable in an RDBMS.

Looping through dictionary object

public class TestModels
{
    public Dictionary<int, dynamic> sp = new Dictionary<int, dynamic>();

    public TestModels()
    {
        sp.Add(0, new {name="Test One", age=5});
        sp.Add(1, new {name="Test Two", age=7});
    }
}

How to set Android camera orientation properly?

check out this solution

 public static void setCameraDisplayOrientation(Activity activity,
                                                   int cameraId, android.hardware.Camera camera) {
        android.hardware.Camera.CameraInfo info =
                new android.hardware.Camera.CameraInfo();
        android.hardware.Camera.getCameraInfo(cameraId, info);
        int rotation = activity.getWindowManager().getDefaultDisplay()
                .getRotation();
        int degrees = 0;
        switch (rotation) {
            case Surface.ROTATION_0: degrees = 0; break;
            case Surface.ROTATION_90: degrees = 90; break;
            case Surface.ROTATION_180: degrees = 180; break;
            case Surface.ROTATION_270: degrees = 270; break;
        }

        int result;
        if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
            result = (info.orientation + degrees) % 360;
            result = (360 - result) % 360;  // compensate the mirror
        } else {  // back-facing
            result = (info.orientation - degrees + 360) % 360;
        }
        camera.setDisplayOrientation(result);
    }

How to move the cursor word by word in the OS X Terminal

Actually it depends on what shell you use, however most shells have similar bindings. The bindings you are referring to (e.g. Ctrl+A and Ctrl+E) are bindings you will find in many other programs and they are used for ages, BTW also work in most UI apps.

Here's a look of default bindings for Bash:

Most Important Bash Keyboard Shortcuts

Please also note that you can customize them. You need to create a file, name as you wish, I named mine .bash_key_bindings and put it into my home directory. There you can set some general bash options and you can also set key bindings. To make sure they are applied, you need to modify a file named ".bashrc" that bash reads in upon start-up (you must create it, if it does not exist) and make the following call there:

bind -f ~/.bash_key_bindings

~ means home directory in bash, as stated above, you can name the file as you like and also place it where you like as long as you feed the right path+name to bind.

Let me show you some excerpts of my .bash_key_bindings file:

set meta-flag on
set input-meta on
set output-meta on
set convert-meta off
set show-all-if-ambiguous on
set bell-style none
set print-completions-horizontally off

These just set a couple of options (e.g. disable the bell; this can be all looked up on the bash webpage).

"A": self-insert
"B": self-insert
"C": self-insert
"D": self-insert
"E": self-insert
"F": self-insert
"G": self-insert
"H": self-insert
"I": self-insert
"J": self-insert

These make sure that the characters alone just do nothing but making sure the character is "typed" (they insert themselves on the shell).

"\C-dW": kill-word
"\C-dL": kill-line
"\C-dw": backward-kill-word
"\C-dl": backward-kill-line
"\C-da": kill-line

This is quite interesting. If I hit Ctrl+D alone (I selected d for delete), nothing happens. But if I then type a lower case w, the word to the left of the cursor is deleted. If I type an upper case, however, the word to the right of the cursor is killed. Same goes for l and L regarding the whole line starting from the cursor. If I type an "a", the whole line is actually deleted (everything before and after the cursor).

I placed jumping one word forward on Ctrl+F and one word backward on Ctrl+B

"\C-f": forward-word
"\C-b": backward-word

As you can see, you can make a shortcut, that leads to an action immediately, or you can make one, that just inits a character sequence and then you have to type one (or more) characters to cause an action to take place as shown in the example further above.

So if you are not happy with the default bindings, feel free to customize them as you like. Here's a link to the bash manual for more information.

ActiveXObject creation error " Automation server can't create object"

Well you can not run code from notepad so that means you are opening up the page from the file system. aka c:/foo/bar/hello.html

When you run the code from the asp.net page, you are running it from localhost. aka http://loalhost:1234/assdf.html

Each of these run in different security zones on IE.

Excel- compare two cell from different sheet, if true copy value from other cell

In your destination field you want to use VLOOKUP like so:

=VLOOKUP(Sheet1!A1:A100,Sheet2!A1:F100,6,FALSE)

VLOOKUP Arguments:

  1. The set fields you want to lookup.
  2. The table range you want to lookup up your value against. The first column of your defined table should be the column you want compared against your lookup field. The table range should also contain the value you want to display (Column F).
  3. This defines what field you want to display upon a match.
  4. FALSE tells VLOOKUP to do an exact match.

How to convert string to date to string in Swift iOS?

Swift 2 and below

let date = NSDate()
var dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "MM-dd-yyyy"
var dateString = dateFormatter.stringFromDate(date)
println(dateString)

And in Swift 3 and higher this would now be written as:

let date = Date()
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MM-dd-yyyy"
var dateString = dateFormatter.string(from: date)

How to run an application as "run as administrator" from the command prompt?

Try this:

runas.exe /savecred /user:administrator "%sysdrive%\testScripts\testscript1.ps1" 

It saves the password the first time and never asks again. Maybe when you change the administrator password you will be prompted again.

jquery UI dialog: how to initialize without a title bar?

Have you tried solution from jQuery UI docs? https://api.jqueryui.com/dialog/#method-open

As it say you can do like this...

In CSS:

.no-titlebar .ui-dialog-titlebar {
  display: none;
}

In JS:

$( "#dialog" ).dialog({
  dialogClass: "no-titlebar"
});

jQuery scroll() detect when user stops scrolling

function scrolled() {
    //do by scroll start
    $(this).off('scroll')[0].setTimeout(function(){
        //do by scroll end
        $(this).on('scroll',scrolled);
    }, 500)
}
$(window).on('scroll',scrolled);

very small Version with start and end ability

Repeat a string in JavaScript a number of times

/**  
 * Repeat a string `n`-times (recursive)
 * @param {String} s - The string you want to repeat.
 * @param {Number} n - The times to repeat the string.
 * @param {String} d - A delimiter between each string.
 */

var repeat = function (s, n, d) {
    return --n ? s + (d || "") + repeat(s, n, d) : "" + s;
};

var foo = "foo";
console.log(
    "%s\n%s\n%s\n%s",

    repeat(foo),        // "foo"
    repeat(foo, 2),     // "foofoo"
    repeat(foo, "2"),   // "foofoo"
    repeat(foo, 2, "-") // "foo-foo"
);

XPath: difference between dot and text()

There is a difference between . and text(), but this difference might not surface because of your input document.

If your input document looked like (the simplest document one can imagine given your XPath expressions)

Example 1

<html>
  <a>Ask Question</a>
</html>

Then //a[text()="Ask Question"] and //a[.="Ask Question"] indeed return exactly the same result. But consider a different input document that looks like

Example 2

<html>
  <a>Ask Question<other/>
  </a>
</html>

where the a element also has a child element other that follows immediately after "Ask Question". Given this second input document, //a[text()="Ask Question"] still returns the a element, while //a[.="Ask Question"] does not return anything!


This is because the meaning of the two predicates (everything between [ and ]) is different. [text()="Ask Question"] actually means: return true if any of the text nodes of an element contains exactly the text "Ask Question". On the other hand, [.="Ask Question"] means: return true if the string value of an element is identical to "Ask Question".

In the XPath model, text inside XML elements can be partitioned into a number of text nodes if other elements interfere with the text, as in Example 2 above. There, the other element is between "Ask Question" and a newline character that also counts as text content.

To make an even clearer example, consider as an input document:

Example 3

<a>Ask Question<other/>more text</a>

Here, the a element actually contains two text nodes, "Ask Question" and "more text", since both are direct children of a. You can test this by running //a/text() on this document, which will return (individual results separated by ----):

Ask Question
-----------------------
more text

So, in such a scenario, text() returns a set of individual nodes, while . in a predicate evaluates to the string concatenation of all text nodes. Again, you can test this claim with the path expression //a[.='Ask Questionmore text'] which will successfully return the a element.


Finally, keep in mind that some XPath functions can only take one single string as an input. As LarsH has pointed out in the comments, if such an XPath function (e.g. contains()) is given a sequence of nodes, it will only process the first node and silently ignore the rest.

Spacing between elements

If you want vertical spacing between elements, use a margin.

Don't add extra elements if you don't need to.

How to make "if not true condition"?

On Unix systems that supports it (not macOS it seems):

if getent passwd "$username" >/dev/null; then
    printf 'User %s exists\n' "$username"
else
    printf 'User %s does not exist\n' "$username"
fi 

This has the advantage that it will query any directory service that may be in use (YP/NIS or LDAP etc.) and the local password database file.


The issue with grep -q "$username" /etc/passwd is that it will give a false positive when there is no such user, but something else matches the pattern. This could happen if there is a partial or exact match somewhere else in the file.

For example, in my passwd file, there is a line saying

build:*:21:21:base and xenocara build:/var/empty:/bin/ksh

This would provoke a valid match on things like cara and enoc etc., even though there are no such users on my system.

For a grep solution to be correct, you will need to properly parse the /etc/passwd file:

if cut -d ':' -f 1 /etc/passwd | grep -qxF "$username"; then
    # found
else
    # not found
fi

... or any other similar test against the first of the :-delimited fields.

How to set thousands separator in Java?

NumberFormat nf = DecimalFormat.getInstance(myLocale);
DecimalFormatSymbols customSymbol = new DecimalFormatSymbols();
customSymbol.setDecimalSeparator(',');
customSymbol.setGroupingSeparator(' ');
((DecimalFormat)nf).setDecimalFormatSymbols(customSymbol);
nf.setGroupingUsed(true);

How to POST the data from a modal form of Bootstrap?

You CAN include a modal within a form. In the Bootstrap documentation it recommends the modal to be a "top level" element, but it still works within a form.

You create a form, and then the modal "save" button will be a button of type="submit" to submit the form from within the modal.

<form asp-action="AddUsersToRole" method="POST" class="mb-3">

    @await Html.PartialAsync("~/Views/Users/_SelectList.cshtml", Model.Users)

    <div class="modal fade" id="role-select-modal" tabindex="-1" role="dialog" aria-labelledby="role-select-modal" aria-hidden="true">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="exampleModalLabel">Select a Role</h5>
                </div>
                <div class="modal-body">
                    ...
                </div>
                <div class="modal-footer">
                    <button type="submit" class="btn btn-primary">Add Users to Role</button>
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
                </div>
            </div>
        </div>
    </div>

</form>

You can post (or GET) your form data to any URL. By default it is the serving page URL, but you can change it by setting the form action. You do not have to use ajax.

Mozilla documentation on form action

How to change legend size with matplotlib.pyplot

This should do

import pylab as plot
params = {'legend.fontsize': 20,
          'legend.handlelength': 2}
plot.rcParams.update(params)

Then do the plot afterwards.

There are a ton of other rcParams, they can also be set in the matplotlibrc file.

Also presumably you can change it passing a matplotlib.font_manager.FontProperties instance but this I don't know how to do. --> see Yann's answer.

Maven home (M2_HOME) not being picked up by IntelliJ IDEA

In case you don't want to use the M2_HOME and want to direct the IntelliJ to the maven installation you can simply set it by:

  • goto File => Setting => Maven => Maven home directory
  • point to your maven build directory e.g. /usr/local/maven/apache-maven-3.0.4

A better way is to have a symlink e.g. 'latest' for the latest version and point your IntelliJ to use that for consistency, given latest points to the latest version of maven installed on your box.

Importing Pandas gives error AttributeError: module 'pandas' has no attribute 'core' in iPython Notebook

I have just solved this problem. Recently, I changed my language setting of my MacBook from English-UK to Chinese. And I suppose that setting will also change the setting in the "locale." Becuase when I switched back, I found that the setting of locale had been changed again, and I am fine to import the pandas again,.

So if you have changed the language setting recently, you may worth to have a try change it back.

Why should I prefer to use member initialization lists?

Apart from the performance reasons mentioned above, if your class stores references to objects passed as constructor parameters or your class has const variables then you don't have any choice except using initializer lists.

Reshaping data.frame from wide to long format

Using reshape package:

#data
x <- read.table(textConnection(
"Code Country        1950    1951    1952    1953    1954
AFG  Afghanistan    20,249  21,352  22,532  23,557  24,555
ALB  Albania        8,097   8,986   10,058  11,123  12,246"), header=TRUE)

library(reshape)

x2 <- melt(x, id = c("Code", "Country"), variable_name = "Year")
x2[,"Year"] <- as.numeric(gsub("X", "" , x2[,"Year"]))

Is it possible to indent JavaScript code in Notepad++?

JSTool is the best for stability.

Steps:

  1. Select menu Plugins>Plugin Manager>Show Plugin Manager
  2. Check to JSTool checkbox > Install > Restart Notepad++
  3. Open js file > Plugins > JSTool > JSFormat
    screenshot

Reference:

JavaScript module pattern with example

Here https://toddmotto.com/mastering-the-module-pattern you can find the pattern thoroughly explained. I would add that the second thing about modular JavaScript is how to structure your code in multiple files. Many folks may advice you here to go with AMD, yet I can say from experience that you will end up on some point with slow page response because of numerous HTTP requests. The way out is pre-compilation of your JavaScript modules (one per file) into a single file following CommonJS standard. Take a look at samples here http://dsheiko.github.io/cjsc/

Get error message if ModelState.IsValid fails?

ModelState.Values.SelectMany(v => v.Errors).ToList().ForEach(x => _logger.Error($"{x.ErrorMessage}\n"));

How to hide a <option> in a <select> menu with CSS?

I would suggest that you do not use the solutions that use a <span> wrapper because it isn't valid HTML, which could cause problems down the road. I think the preferred solution is to actually remove any options that you wish to hide, and restore them as needed. Using jQuery, you'll only need these 3 functions:

The first function will save the original contents of the select. Just to be safe, you may want to call this function when you load the page.

function setOriginalSelect ($select) {
    if ($select.data("originalHTML") == undefined) {
        $select.data("originalHTML", $select.html());
    } // If it's already there, don't re-set it
}

This next function calls the above function to ensure that the original contents have been saved, and then simply removes the options from the DOM.

function removeOptions ($select, $options) {
    setOriginalSelect($select);
    $options.remove();
 }

The last function can be used whenever you want to "reset" back to all the original options.

function restoreOptions ($select) {
    var ogHTML = $select.data("originalHTML");
    if (ogHTML != undefined) {
        $select.html(ogHTML);
    }
}

Note that all these functions expect that you're passing in jQuery elements. For example:

// in your search function...
var $s = $('select.someClass');
var $optionsThatDontMatchYourSearch= $s.find('options.someOtherClass');
restoreOptions($s); // Make sure you're working with a full deck
removeOptions($s, $optionsThatDontMatchYourSearch); // remove options not needed

Here is a working example: http://jsfiddle.net/9CYjy/23/

Installing a pip package from within a Jupyter Notebook not working

! pip install --user <package>

The ! tells the notebook to execute the cell as a shell command.

How to select option in drop down using Capybara

For some reason it didn't work for me. So I had to use something else.

select "option_name_here", :from => "organizationSelect"

worked for me.

jQuery get mouse position within an element

This solution supports all major browsers including IE. It also takes care of scrolling. First, it retrieves the position of the element relative to the page efficiently, and without using a recursive function. Then it gets the x and y of the mouse click relative to the page and does the subtraction to get the answer which is the position relative to the element (the element can be an image or div for example):

function getXY(evt) {
    var element = document.getElementById('elementId');  //replace elementId with your element's Id.
    var rect = element.getBoundingClientRect();
    var scrollTop = document.documentElement.scrollTop?
                    document.documentElement.scrollTop:document.body.scrollTop;
    var scrollLeft = document.documentElement.scrollLeft?                   
                    document.documentElement.scrollLeft:document.body.scrollLeft;
    var elementLeft = rect.left+scrollLeft;  
    var elementTop = rect.top+scrollTop;

        if (document.all){ //detects using IE   
            x = event.clientX+scrollLeft-elementLeft; //event not evt because of IE
            y = event.clientY+scrollTop-elementTop;
        }
        else{
            x = evt.pageX-elementLeft;
            y = evt.pageY-elementTop;
    }

How to implement HorizontalScrollView like Gallery?

Here is a good tutorial with code. Let me know if it works for you! This is also a good tutorial.

EDIT

In This example, all you need to do is add this line:

gallery.setSelection(1);

after setting the adapter to gallery object, that is this line:

gallery.setAdapter(new ImageAdapter(this));

UPDATE1

Alright, I got your problem. This open source library is your solution. I also have used it for one of my projects. Hope this will solve your problem finally.

UPDATE2:

I would suggest you to go through this tutorial. You might get idea. I think I got your problem, you want the horizontal scrollview with snap. Try to search with that keyword on google or out here, you might get your solution.

How to upload files on server folder using jsp

I found the similar problem and found the solution and i have blogged about how to upload the file using JSP , In that example i have used the absolute path. Note that if you want to route to some other URL based location you can put a ESB like WSO2 ESB

Current time in microseconds in java

You can use System.nanoTime():

long start = System.nanoTime();
// do stuff
long end = System.nanoTime();
long microseconds = (end - start) / 1000;

to get time in nanoseconds but it is a strictly relative measure. It has no absolute meaning. It is only useful for comparing to other nano times to measure how long something took to do.

Gradient text color

_x000D_
_x000D_
@import url(https://fonts.googleapis.com/css?family=Roboto+Slab:400);_x000D_
_x000D_
body {_x000D_
  background: #222;_x000D_
}_x000D_
_x000D_
h1 {_x000D_
  display: table;_x000D_
  margin: 0 auto;_x000D_
  font-family: "Roboto Slab";_x000D_
  font-weight: 600;_x000D_
  font-size: 7em;_x000D_
  background: linear-gradient(330deg, #e05252 0%, #99e052 25%, #52e0e0 50%, #9952e0 75%, #e05252 100%);_x000D_
  -webkit-background-clip: text;_x000D_
  -webkit-text-fill-color: transparent;_x000D_
  line-height: 200px;_x000D_
}
_x000D_
<h1>beautiful</h1>
_x000D_
_x000D_
_x000D_

What is TypeScript and why would I use it in place of JavaScript?

"TypeScript Fundamentals" -- a Pluralsight video-course by Dan Wahlin and John Papa is a really good, presently (March 25, 2016) updated to reflect TypeScript 1.8, introduction to Typescript.

For me the really good features, beside the nice possibilities for intellisense, are the classes, interfaces, modules, the ease of implementing AMD, and the possibility to use the Visual Studio Typescript debugger when invoked with IE.

To summarize: If used as intended, Typescript can make JavaScript programming more reliable, and easier. It can increase the productivity of the JavaScript programmer significantly over the full SDLC.

How to center a window on the screen in Tkinter?

CENTERING THE WINDOW IN PYTHON Tkinter This is the most easiest thing in tkinter because all we must know is the dimension of the window as well as the dimensions of the computer screen. I come up with the following code which can help someone somehow and i did add some comments so that they can follow up.

code

    #  create a window first
    root = Tk()
    # define window dimensions width and height
    window_width = 800
    window_height = 500
    # get the screen size of your computer [width and height using the root object as foolows]
    screen_width = root.winfo_screenwidth()
    screen_height = root.winfo_screenheight()
    # Get the window position from the top dynamically as well as position from left or right as follows
    position_top = int(screen_height/2 -window_height/2)
    position_right = int(screen_width / 2 - window_width/2)
    # this is the line that will center your window
    root.geometry(f'{window_width}x{window_height}+{position_right}+{position_top}')
    # initialise the window
    root.mainloop(0)

How to transfer paid android apps from one google account to another google account

You will not be able to do that. You can download apps again to the same userid account on different devices, but you cannot transfer those licenses to other userids.

There is no way to do this programatically - I don't think you can do that practically (except for trying to call customer support at the Play Store).

How to check if a file is a valid image file?

You could use the Python bindings to libmagic, python-magic and then check the mime types. This won't tell you if the files are corrupted or intact but it should be able to determine what type of image it is.

How can I change the thickness of my <hr> tag

For consistency remove any borders and use the height for the <hr> thickness. Adding a background color will style your <hr> with the height and color specified.

In your stylesheet:

hr {
    border: none;
    height: 1px;
    /* Set the hr color */
    color: #333; /* old IE */
    background-color: #333; /* Modern Browsers */
}

Or inline as you have it:

<hr style="height:1px;border:none;color:#333;background-color:#333;" />

Longer explanation here

How to fix Subversion lock error

I spent hours looking for a solution to the "Attempted to lock an already-locked dir" error I was receiving in IBM RAD. Finally, I guessed to type:

unlock <directory path>

in the RAD console and... volia I could finally syncronize my files!!

Calculating the angle between the line defined by two points

Had a need for similar functionality myself, so after much hair pulling I came up with the function below

/**
 * Fetches angle relative to screen centre point
 * where 3 O'Clock is 0 and 12 O'Clock is 270 degrees
 * 
 * @param screenPoint
 * @return angle in degress from 0-360.
 */
public double getAngle(Point screenPoint) {
    double dx = screenPoint.getX() - mCentreX;
    // Minus to correct for coord re-mapping
    double dy = -(screenPoint.getY() - mCentreY);

    double inRads = Math.atan2(dy, dx);

    // We need to map to coord system when 0 degree is at 3 O'clock, 270 at 12 O'clock
    if (inRads < 0)
        inRads = Math.abs(inRads);
    else
        inRads = 2 * Math.PI - inRads;

    return Math.toDegrees(inRads);
}

Python function pointer

I ran into a similar problem while creating a library to handle authentication. I want the app owner using my library to be able to register a callback with the library for checking authorization against LDAP groups the authenticated person is in. The configuration is getting passed in as a config.py file that gets imported and contains a dict with all the config parameters.

I got this to work:

>>> class MyClass(object):
...     def target_func(self):
...         print "made it!"
...    
...     def __init__(self,config):
...         self.config = config
...         self.config['funcname'] = getattr(self,self.config['funcname'])
...         self.config['funcname']()
... 
>>> instance = MyClass({'funcname':'target_func'})
made it!

Is there a pythonic-er way to do this?

How to find the kafka version in linux

When you install Kafka in Centos7 with confluent :

yum install confluent-platform-oss-2.11

You can see the version of Kafka with :

yum deplist confluent-platform-oss-2.11

You can read : confluent-kafka-2.11 >= 0.10.2.1

crudrepository findBy method signature with multiple in operators?

The following signature will do:

List<Email> findByEmailIdInAndPincodeIn(List<String> emails, List<String> pinCodes);

Spring Data JPA supports a large number of keywords to build a query. IN and AND are among them.

Ruby: How to iterate over a range, but in set increments?

rng.step(n=1) {| obj | block } => rng

Iterates over rng, passing each nth element to the block. If the range contains numbers or strings, natural ordering is used. Otherwise step invokes succ to iterate through range elements. The following code uses class Xs, which is defined in the class-level documentation.

range = Xs.new(1)..Xs.new(10)
range.step(2) {|x| puts x}
range.step(3) {|x| puts x}

produces:

1 x
3 xxx
5 xxxxx
7 xxxxxxx
9 xxxxxxxxx
1 x
4 xxxx
7 xxxxxxx
10 xxxxxxxxxx

Reference: http://ruby-doc.org/core/classes/Range.html

......

Bash Shell Script - Check for a flag and grab its value

Try shFlags -- Advanced command-line flag library for Unix shell scripts.

http://code.google.com/p/shflags/

It is very good and very flexible.

FLAG TYPES: This is a list of the DEFINE_*'s that you can do. All flags take a name, default value, help-string, and optional 'short' name (one-letter name). Some flags have other arguments, which are described with the flag.

DEFINE_string: takes any input, and intreprets it as a string.

DEFINE_boolean: typically does not take any argument: say --myflag to set FLAGS_myflag to true, or --nomyflag to set FLAGS_myflag to false. Alternately, you can say --myflag=true or --myflag=t or --myflag=0 or --myflag=false or --myflag=f or --myflag=1 Passing an option has the same affect as passing the option once.

DEFINE_float: takes an input and intreprets it as a floating point number. As shell does not support floats per-se, the input is merely validated as being a valid floating point value.

DEFINE_integer: takes an input and intreprets it as an integer.

SPECIAL FLAGS: There are a few flags that have special meaning: --help (or -?) prints a list of all the flags in a human-readable fashion --flagfile=foo read flags from foo. (not implemented yet) -- as in getopt(), terminates flag-processing

EXAMPLE USAGE:

-- begin hello.sh --
 ! /bin/sh
. ./shflags
DEFINE_string name 'world' "somebody's name" n
FLAGS "$@" || exit $?
eval set -- "${FLAGS_ARGV}"
echo "Hello, ${FLAGS_name}."
-- end hello.sh --

$ ./hello.sh -n Kate
Hello, Kate.

Note: I took this text from shflags documentation

Easy way to write contents of a Java InputStream to an OutputStream

Simple Function

If you only need this for writing an InputStream to a File then you can use this simple function:

private void copyInputStreamToFile( InputStream in, File file ) {
    try {
        OutputStream out = new FileOutputStream(file);
        byte[] buf = new byte[1024];
        int len;
        while((len=in.read(buf))>0){
            out.write(buf,0,len);
        }
        out.close();
        in.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

PHP, MySQL error: Column count doesn't match value count at row 1

Your query has 8 or possibly even 9 variables, ie. Name, Description etc. But the values, these things ---> '', '%s', '%s', '%s', '%s', '%s', '%s', '%s')", only total 7, the number of variables have to be the same as the values.

I had the same problem but I figured it out. Hopefully it will also work for you.

How to increase an array's length

If you don't want or cannot use ArrayList, then there is a utility method:

Arrays.copyOf() 

that will allow you to specify new size, while preserving the elements.

How to load local html file into UIWebView

May be your HTML file doesn't support UTF-8 encoding, because the same code is working for me.

Or u can also these line of code:

NSString *htmlFile = [[NSBundle mainBundle] pathForResource:@"Notes For Apple" ofType:@"htm" inDirectory:nil];
NSString* htmlString = [NSString stringWithContentsOfFile:htmlFile encoding:NSUTF8StringEncoding error:nil];
[WebView loadHTMLString:htmlString baseURL:nil];

How to reverse an animation on mouse out after hover

Using transform in combination with transition works flawlessly for me:

.ani-grow {
    -webkit-transition: all 0.5s ease; 
    -moz-transition: all 0.5s ease; 
    -o-transition: all 0.5s ease; 
    -ms-transition: all 0.5s ease; 
    transition: all 0.5s ease; 
}
.ani-grow:hover {
    transform: scale(1.01);
}

How to fix System.NullReferenceException: Object reference not set to an instance of an object

I was getting this same error, but for me this was due to a method in a base class (in Project A) having the output type changed from a non-void type to void. A child class existed in Project B (which I didn't want used and had marked obsolete) that I missed when performing this update and hence started throwing this error.

1>CSC : error CS8104: An error occurred while writing the output file: System.NullReferenceException: Object reference not set to an instance of an object.

Original Code:

[Obsolete("Calling this method will throw an error")]
public override CompletionStatus Run()
{
    throw new CustomException("Run process not supported.");
}

Revised Code:

[Obsolete("Calling this method will throw an error")]
public override void Run()
{
    throw new CustomException("Run process not supported.");
}

Creating a new ArrayList in Java

You are looking for Java generics

List<MyClass> list = new ArrayList<MyClass>();

Here's a tutorial http://docs.oracle.com/javase/tutorial/java/generics/index.html

Str_replace for multiple items

If you're only replacing single characters, you should use strtr()

Hide options in a select list using jQuery

I found it best to just remove the DOM completely.

$(".form-group #selectId option[value='39']").remove();

Cross browser compatible. Works on IE11 too

How to populate/instantiate a C# array with a single value?

Make a private class inside where you make the array and the have a getter and setter for it. Unless you need each position in the array to be something unique, like random, then use int? as an array and then on get if the position is equal null fill that position and return the new random value.

IsVisibleHandler
{

  private bool[] b = new bool[10000];

  public bool GetIsVisible(int x)
  {
  return !b[x]
  }

  public void SetIsVisibleTrueAt(int x)
  {
  b[x] = false //!true
  }
}

Or use

public void SetIsVisibleAt(int x, bool isTrue)
{
b[x] = !isTrue;
}

As setter.

MaxLength Attribute not generating client-side validation attributes

Try using the [StringLength] attribute:

[Required(ErrorMessage = "Name is required.")]
[StringLength(40, ErrorMessage = "Name cannot be longer than 40 characters.")]
public string Name { get; set; }

That's for validation purposes. If you want to set for example the maxlength attribute on the input you could write a custom data annotations metadata provider as shown in this post and customize the default templates.

What is the { get; set; } syntax in C#?

Get set are access modifiers to property. Get reads the property field. Set sets the property value. Get is like Read-only access. Set is like Write-only access. To use the property as read write both get and set must be used.

Tomcat starts but home page cannot open with url http://localhost:8080

1) Using Terminal (On Linux), go to the apache-tomcat-directory/bin folder.

2) Type ./catalina.sh start

3) To stop Tomcat, type ./catalina.sh stop from the bin folder. For some reason ./startup.sh doesn't work sometimes.

How do you use bcrypt for hashing passwords in PHP?

For OAuth 2 passwords:

$bcrypt = new \Zend\Crypt\Password\Bcrypt;
$bcrypt->create("youpasswordhere", 10)

Counting Line Numbers in Eclipse

For eclipse(Indigo), install (codepro).

After installation: - Right click on your project - Choose codepro tools --> compute metrics - And you will get your answer in a Metrics tab as Number of Lines.

How to get root directory in yii2

If you want to get the root directory of your yii2 project use, assuming that the name of your project is project_app you'll need to use:

echo Yii::getAlias('@app');

on windows you'd see "C:\dir\to\project_app"

on linux you'll get "/var/www/dir/to/your/project_app"

I was formally using:

echo Yii::getAlias('@webroot').'/..';

I hope this helps someone

Chrome ignores autocomplete="off"

Chrome version 34 now ignores the autocomplete=off, see this.

Lots of discussion on whether this is a good thing or a bad thing? Whats your views?

Java string replace and the NUL (NULL, ASCII 0) character?

Does replacing a character in a String with a null character even work in Java? I know that '\0' will terminate a c-string.

That depends on how you define what is working. Does it replace all occurrences of the target character with '\0'? Absolutely!

String s = "food".replace('o', '\0');
System.out.println(s.indexOf('\0')); // "1"
System.out.println(s.indexOf('d')); // "3"
System.out.println(s.length()); // "4"
System.out.println(s.hashCode() == 'f'*31*31*31 + 'd'); // "true"

Everything seems to work fine to me! indexOf can find it, it counts as part of the length, and its value for hash code calculation is 0; everything is as specified by the JLS/API.

It DOESN'T work if you expect replacing a character with the null character would somehow remove that character from the string. Of course it doesn't work like that. A null character is still a character!

String s = Character.toString('\0');
System.out.println(s.length()); // "1"
assert s.charAt(0) == 0;

It also DOESN'T work if you expect the null character to terminate a string. It's evident from the snippets above, but it's also clearly specified in JLS (10.9. An Array of Characters is Not a String):

In the Java programming language, unlike C, an array of char is not a String, and neither a String nor an array of char is terminated by '\u0000' (the NUL character).


Would this be the culprit to the funky characters?

Now we're talking about an entirely different thing, i.e. how the string is rendered on screen. Truth is, even "Hello world!" will look funky if you use dingbats font. A unicode string may look funky in one locale but not the other. Even a properly rendered unicode string containing, say, Chinese characters, may still look funky to someone from, say, Greenland.

That said, the null character probably will look funky regardless; usually it's not a character that you want to display. That said, since null character is not the string terminator, Java is more than capable of handling it one way or another.


Now to address what we assume is the intended effect, i.e. remove all period from a string, the simplest solution is to use the replace(CharSequence, CharSequence) overload.

System.out.println("A.E.I.O.U".replace(".", "")); // AEIOU

The replaceAll solution is mentioned here too, but that works with regular expression, which is why you need to escape the dot meta character, and is likely to be slower.

css overflow - only 1 line of text

the best code for UX and UI is

white-space: nowrap;
text-overflow: ellipsis;
overflow: hidden;
display: inherit;

How to align form at the center of the page in html/css

Wrap the <form> element inside a div container and apply css to the div instead which makes things easier.

_x000D_
_x000D_
#aDiv{width: 300px; height: 300px; margin: 0 auto;}
_x000D_
<html>_x000D_
_x000D_
<head></head>_x000D_
_x000D_
<body>_x000D_
  <div>_x000D_
    <form>_x000D_
      <div id="aDiv">_x000D_
        <table>_x000D_
          <tr>_x000D_
            <td>Name :</td>_x000D_
            <td>_x000D_
              <input type="text" name="name">_x000D_
            </td>_x000D_
            <br>_x000D_
          </tr>_x000D_
          <tr>_x000D_
            <td>Email :</td>_x000D_
            <td>_x000D_
              <input type="text" name="email">_x000D_
            </td>_x000D_
            <br>_x000D_
          </tr>_x000D_
          <tr>_x000D_
            <td>Password :</td>_x000D_
            <td>_x000D_
              <input type="password" name="pwd">_x000D_
            </td>_x000D_
            <br>_x000D_
          </tr>_x000D_
          <tr>_x000D_
            <td>Confirm Password :</td>_x000D_
            <td>_x000D_
              <input type="password" name="cpwd">_x000D_
              <br>_x000D_
          </tr>_x000D_
          <tr>_x000D_
            <td>_x000D_
              <input type="submit" value="Submit">_x000D_
            </td>_x000D_
          </tr>_x000D_
        </table>_x000D_
      </div>_x000D_
    </form>_x000D_
  </div>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_

php - insert a variable in an echo string

Use double quotes:

$i = 1;
echo "
<p class=\"paragraph$i\">
</p>
";
++i;

Using Html.ActionLink to call action on different controller

An alternative solution would be to use the Url helper object to set the href attribute of an <a> tag like:

<a href="@Url.Action("Details", "Product",new { id=item.ID }) )">Details</a>

npm check and update package if needed

To really update just one package install NCU and then run it just for that package. This will bump to the real latest.

npm install -g npm-check-updates

ncu -f your-intended-package-name -u

Reading Space separated input in python

Assuming you are on Python 3, you can use this syntax

inputs = list(map(str,input().split()))

if you want to access individual element you can do it like that

m, n = map(str,input().split())