Programs & Examples On #Catch block

The `catch-block` in a program is used to handle an `exception` thrown by a block of code.

Java 8: Lambda-Streams, Filter by Method with Exception

This does not directly answer the question (there are many other answers that do) but tries to avoid the problem in the first place:

In my experience the need to handle exceptions in a Stream (or other lambda expression) often comes from the fact that the exceptions are declared to be thrown from methods where they should not be thrown. This often comes from mixing business logic with in- and output. Your Account interface is a perfect example:

interface Account {
    boolean isActive() throws IOException;
    String getNumber() throws IOException;
}

Instead of throwing an IOException on each getter, consider this design:

interface AccountReader {
    Account readAccount(…) throws IOException;
}

interface Account {
    boolean isActive();
    String getNumber();
}

The method AccountReader.readAccount(…) could read an account from a database or a file or whatever and throw an exception if it does not succeed. It constructs an Account object that already contains all values, ready to be used. As the values have already been loaded by readAccount(…), the getters would not throw an exception. Thus you can use them freely in lambdas without the need of wrapping, masking or hiding the exceptions.

Of course it is not always possible to do it the way I described, but often it is and it leads to cleaner code altogether (IMHO):

  • Better separation of concerns and following single responsibility principle
  • Less boilerplate: You don't have to clutter your code with throws IOException for no use but to satisfy the compiler
  • Error handling: You handle the errors where they happen - when reading from a file or database - instead of somewhere in the middle of your business logic only because you want to get a fields value
  • You may be able to make Account immutable and profit from the advantages thereof (e.g. thread safety)
  • You don't need "dirty tricks" or workarounds to use Account in lambdas (e.g. in a Stream)

utf-8 special characters not displaying

I solve my issue by using utf8_encode();

$str = "kamé";

echo utf8_encode($str);

Hope this help someone.

Java JDBC connection status

You also can use

public boolean isDbConnected(Connection con) {
    try {
        return con != null && !con.isClosed();
    } catch (SQLException ignored) {}

    return false;
}

Correct way to handle conditional styling in React

The best way to handle styling is by using classes with set of css properties.

example:

<Component className={this.getColor()} />

getColor() {
    let class = "badge m2";
    class += this.state.count===0 ? "warning" : danger;
    return class;
}

How to install a specific JDK on Mac OS X?

There are various tricky issues with having multiple versions of Java (Apple's own Java 6 and Oracle JDK 7 or even 8) on one's Mac OS X system, and using different versions for different applications. I spent some time writing up my experience of my experience of installing and configuring various versions of JDK on Mac OS X 10.9.2.

How to unpack an .asar file?

From the asar documentation

(the use of npx here is to avoid to install the asar tool globally with npm install -g asar)

Extract the whole archive:

npx asar extract app.asar destfolder 

Extract a particular file:

npx asar extract-file app.asar main.js

Can't access RabbitMQ web management interface after fresh install

If on Windows and installed using chocolatey make sure firewall is allowing the default ports for it:

netsh advfirewall firewall add rule name="RabbitMQ Management" dir=in action=allow protocol=TCP localport=15672
netsh advfirewall firewall add rule name="RabbitMQ" dir=in action=allow protocol=TCP localport=5672

for the remote access.

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>

How to declare Global Variables in Excel VBA to be visible across the Workbook

Your question is: are these not modules capable of declaring variables at global scope?

Answer: YES, they are "capable"

The only point is that references to global variables in ThisWorkbook or a Sheet module have to be fully qualified (i.e., referred to as ThisWorkbook.Global1, e.g.) References to global variables in a standard module have to be fully qualified only in case of ambiguity (e.g., if there is more than one standard module defining a variable with name Global1, and you mean to use it in a third module).

For instance, place in Sheet1 code

Public glob_sh1 As String

Sub test_sh1()
    Debug.Print (glob_mod)
    Debug.Print (ThisWorkbook.glob_this)
    Debug.Print (Sheet1.glob_sh1)
End Sub

place in ThisWorkbook code

Public glob_this As String

Sub test_this()
    Debug.Print (glob_mod)
    Debug.Print (ThisWorkbook.glob_this)
    Debug.Print (Sheet1.glob_sh1)
End Sub

and in a Standard Module code

Public glob_mod As String

Sub test_mod()
    glob_mod = "glob_mod"
    ThisWorkbook.glob_this = "glob_this"
    Sheet1.glob_sh1 = "glob_sh1"
    Debug.Print (glob_mod)
    Debug.Print (ThisWorkbook.glob_this)
    Debug.Print (Sheet1.glob_sh1)
End Sub

All three subs work fine.

PS1: This answer is based essentially on info from here. It is much worth reading (from the great Chip Pearson).

PS2: Your line Debug.Print ("Hello") will give you the compile error Invalid outside procedure.

PS3: You could (partly) check your code with Debug -> Compile VBAProject in the VB editor. All compile errors will pop.

PS4: Check also Put Excel-VBA code in module or sheet?.

PS5: You might be not able to declare a global variable in, say, Sheet1, and use it in code from other workbook (reading http://msdn.microsoft.com/en-us/library/office/gg264241%28v=office.15%29.aspx#sectionSection0; I did not test this point, so this issue is yet to be confirmed as such). But you do not mean to do that in your example, anyway.

PS6: There are several cases that lead to ambiguity in case of not fully qualifying global variables. You may tinker a little to find them. They are compile errors.

How to count check-boxes using jQuery?

The following code worked for me.

$('input[name="chkGender[]"]:checked').length;

Angularjs loading screen on ajax request

Here's an example. It uses the simple ng-show method with a bool.

HTML

<div ng-show="loading" class="loading"><img src="...">LOADING...</div>
<div ng-repeat="car in cars">
  <li>{{car.name}}</li>
</div>
<button ng-click="clickMe()" class="btn btn-primary">CLICK ME</button>

ANGULARJS

  $scope.clickMe = function() {
    $scope.loading = true;
    $http.get('test.json')
      .success(function(data) {
        $scope.cars = data[0].cars;
        $scope.loading = false;
    });
  }

Of course you can move the loading box html code into a directive, then use $watch on $scope.loading. In which case:

HTML:

<loading></loading>

ANGULARJS DIRECTIVE:

  .directive('loading', function () {
      return {
        restrict: 'E',
        replace:true,
        template: '<div class="loading"><img src="..."/>LOADING...</div>',
        link: function (scope, element, attr) {
              scope.$watch('loading', function (val) {
                  if (val)
                      $(element).show();
                  else
                      $(element).hide();
              });
        }
      }
  })

PLUNK: http://plnkr.co/edit/AI1z21?p=preview

Counting words in string

Here's my approach, which simply splits a string by spaces, then for loops the array and increases the count if the array[i] matches a given regex pattern.

    function wordCount(str) {
        var stringArray = str.split(' ');
        var count = 0;
        for (var i = 0; i < stringArray.length; i++) {
            var word = stringArray[i];
            if (/[A-Za-z]/.test(word)) {
                count++
            }
        }
        return count
    }

Invoked like so:

var str = "testing strings here's a string --..  ? // ... random characters ,,, end of string";
wordCount(str)

(added extra characters & spaces to show accuracy of function)

The str above returns 10, which is correct!

Change the jquery show()/hide() animation?

Use slidedown():

$("test").slideDown("slow");

How to disable a link using only CSS?

You can also size another element so that it covers the links (using the right z-index): That will "eat" the clicks.

(We discovered this by accident because we had an issue with suddenly inactive links due to "responsive" design causing a H2 to cover them when the browser window was mobile-sized.)

Max size of an iOS application

Please be aware that the warning on iTunes Connect does not say anything about the limit being only for over-the-air delivery. It would be preferable if the warning mentioned this.

enter image description here

How do I find the maximum of 2 numbers?

(num1>=num2)*num1+(num2>num1)*num2 will return the maximum of two values.

Are PHP Variables passed by value or by reference?

In PHP, by default, objects are passed as reference to a new object.

See this example:

class X {
  var $abc = 10; 
}

class Y {

  var $abc = 20; 
  function changeValue($obj)
  {
   $obj->abc = 30;
  }
}

$x = new X();
$y = new Y();

echo $x->abc; //outputs 10
$y->changeValue($x);
echo $x->abc; //outputs 30

Now see this:

class X {
  var $abc = 10; 
}

class Y {

  var $abc = 20; 
  function changeValue($obj)
  {
    $obj = new Y();
  }
}

$x = new X();
$y = new Y();

echo $x->abc; //outputs 10
$y->changeValue($x);
echo $x->abc; //outputs 10 not 20 same as java does.

Now see this:

class X {
  var $abc = 10; 
}

class Y {

  var $abc = 20; 
  function changeValue(&$obj)
  {
    $obj = new Y();
  }
}

$x = new X();
$y = new Y();

echo $x->abc; //outputs 10
$y->changeValue($x);
echo $x->abc; //outputs 20 not possible in java.

I hope you can understand this.

How to deselect all selected rows in a DataGridView control?

i have ran into the same problem and found a solution (not totally by myself, but there is the internet for)

Color blue  = ColorTranslator.FromHtml("#CCFFFF");
Color red = ColorTranslator.FromHtml("#FFCCFF");
Color letters = Color.Black;

foreach (DataGridViewRow r in datagridIncome.Rows)
{
    if (r.Cells[5].Value.ToString().Contains("1")) { 
        r.DefaultCellStyle.BackColor = blue;
        r.DefaultCellStyle.SelectionBackColor = blue;
        r.DefaultCellStyle.SelectionForeColor = letters;
    }
    else { 
        r.DefaultCellStyle.BackColor = red;
        r.DefaultCellStyle.SelectionBackColor = red;
        r.DefaultCellStyle.SelectionForeColor = letters;
    }
}

This is a small trick, the only way you can see a row is selected, is by the very first column (not column[0], but the one therefore). When you click another row, you will not see the blue selection anymore, only the arrow indicates which row have selected. As you understand, I use rowSelection in my gridview.

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

Ya its possible to do without support of javascript..
We can use html5 auto focus attribute
For Example:

<input type="text" name="name" autofocus="autofocus" id="xax" />

If use it (autofocus="autofocus") in text field means that text field get focused when page gets loaded.. For more details:
http://www.hscripts.com/tutorials/html5/autofocus-attribute.html

Viewing localhost website from mobile device

First of all open applicationhost.config file in visual studio. address>>C:\Users\Your User Name\Documents\IISExpress\config\applicationhost.config

Then find this codes:

<site name="Your Site_Name" id="24">
        <application path="/" applicationPool="Clr4IntegratedAppPool"
        <virtualDirectory path="/" physicalPath="C:\Users\Your User         Name\Documents\Visual Studio 2013\Projects\Your Site Name" />
        </application>
         <bindings>      
           <binding protocol="http" bindingInformation="*:Port_Number:*" />
         </bindings>
   </site>

*)Port_Number:While your site running in IIS express on your computer, port number will visible in address bar of your browser like this: localhost:port_number/... When edit this file save it.

In the Second step you must run cmd as administrator and type this code: netsh http add urlacl url=http://*:port_Number/ user=everyone and press enter

In Third step you must Enable port on firewall

Go to the “Control Panel\System and Security\Windows Firewall”

Click “Advanced settings”

Select “Inbound Rules”

Click on “New Rule …” button

Select “Port”, click “Next”

Fill your IIS Express listening port number, click “Next”

Select “Allow the connection”, click “Next”

Check where you would like allow connection to IIS Express (Domain,Private, Public), click “Next”

Fill rule name (e.g “IIS Express), click “Finish”

I hopeful this answer be useful for you

Update for Visual Studio 2015 in this link: https://johan.driessen.se/posts/Accessing-an-IIS-Express-site-from-a-remote-computer

Entity Framework - Include Multiple Levels of Properties

I figured out a simplest way. You don't need to install package ThenInclude.EF or you don't need to use ThenInclude for all nested navigation properties. Just do like as shown below, EF will take care rest for you. example:

var thenInclude = context.One.Include(x => x.Twoes.Threes.Fours.Fives.Sixes)
.Include(x=> x.Other)
.ToList();

compare differences between two tables in mysql

INTERSECT needs to be emulated in MySQL:

SELECT  'robot' AS `set`, r.*
FROM    robot r
WHERE   ROW(r.col1, r.col2, …) NOT IN
        (
        SELECT  col1, col2, ...
        FROM    tbd_robot
        )
UNION ALL
SELECT  'tbd_robot' AS `set`, t.*
FROM    tbd_robot t
WHERE   ROW(t.col1, t.col2, …) NOT IN
        (
        SELECT  col1, col2, ...
        FROM    robot
        )

How to delete the contents of a folder?

Notes: in case someone down voted my answer, I have something to explain here.

  1. Everyone likes short 'n' simple answers. However, sometimes the reality is not so simple.
  2. Back to my answer. I know shutil.rmtree() could be used to delete a directory tree. I've used it many times in my own projects. But you must realize that the directory itself will also be deleted by shutil.rmtree(). While this might be acceptable for some, it's not a valid answer for deleting the contents of a folder (without side effects).
  3. I'll show you an example of the side effects. Suppose that you have a directory with customized owner and mode bits, where there are a lot of contents. Then you delete it with shutil.rmtree() and rebuild it with os.mkdir(). And you'll get an empty directory with default (inherited) owner and mode bits instead. While you might have the privilege to delete the contents and even the directory, you might not be able to set back the original owner and mode bits on the directory (e.g. you're not a superuser).
  4. Finally, be patient and read the code. It's long and ugly (in sight), but proven to be reliable and efficient (in use).

Here's a long and ugly, but reliable and efficient solution.

It resolves a few problems which are not addressed by the other answerers:

  • It correctly handles symbolic links, including not calling shutil.rmtree() on a symbolic link (which will pass the os.path.isdir() test if it links to a directory; even the result of os.walk() contains symbolic linked directories as well).
  • It handles read-only files nicely.

Here's the code (the only useful function is clear_dir()):

import os
import stat
import shutil


# http://stackoverflow.com/questions/1889597/deleting-directory-in-python
def _remove_readonly(fn, path_, excinfo):
    # Handle read-only files and directories
    if fn is os.rmdir:
        os.chmod(path_, stat.S_IWRITE)
        os.rmdir(path_)
    elif fn is os.remove:
        os.lchmod(path_, stat.S_IWRITE)
        os.remove(path_)


def force_remove_file_or_symlink(path_):
    try:
        os.remove(path_)
    except OSError:
        os.lchmod(path_, stat.S_IWRITE)
        os.remove(path_)


# Code from shutil.rmtree()
def is_regular_dir(path_):
    try:
        mode = os.lstat(path_).st_mode
    except os.error:
        mode = 0
    return stat.S_ISDIR(mode)


def clear_dir(path_):
    if is_regular_dir(path_):
        # Given path is a directory, clear its content
        for name in os.listdir(path_):
            fullpath = os.path.join(path_, name)
            if is_regular_dir(fullpath):
                shutil.rmtree(fullpath, onerror=_remove_readonly)
            else:
                force_remove_file_or_symlink(fullpath)
    else:
        # Given path is a file or a symlink.
        # Raise an exception here to avoid accidentally clearing the content
        # of a symbolic linked directory.
        raise OSError("Cannot call clear_dir() on a symbolic link")

How to create a video from images with FFmpeg?

See the Create a video slideshow from images – FFmpeg

If your video does not show the frames correctly If you encounter problems, such as the first image is skipped or only shows for one frame, then use the fps video filter instead of -r for the output framerate

ffmpeg -r 1/5 -i img%03d.png -c:v libx264 -vf fps=25 -pix_fmt yuv420p out.mp4

Alternatively the format video filter can be added to the filter chain to replace -pix_fmt yuv420p like "fps=25,format=yuv420p". The advantage of this method is that you can control which filter goes first

ffmpeg -r 1/5 -i img%03d.png -c:v libx264 -vf "fps=25,format=yuv420p" out.mp4

I tested below parameters, it worked for me

"e:\ffmpeg\ffmpeg.exe" -r 1/5 -start_number 0 -i "E:\images\01\padlock%3d.png" -c:v libx264 -vf "fps=25,format=yuv420p" e:\out.mp4

below parameters also worked but it always skips the first image

"e:\ffmpeg\ffmpeg.exe" -r 1/5 -start_number 0 -i "E:\images\01\padlock%3d.png" -c:v libx264 -r 30 -pix_fmt yuv420p e:\out.mp4

making a video from images placed in different folders

First, add image paths to imagepaths.txt like below.

# this is a comment details https://trac.ffmpeg.org/wiki/Concatenate

file 'E:\images\png\images__%3d.jpg'
file 'E:\images\jpg\images__%3d.jpg'

Sample usage as follows;

"h:\ffmpeg\ffmpeg.exe" -y -r 1/5 -f concat -safe 0 -i "E:\images\imagepaths.txt" -c:v libx264 -vf "fps=25,format=yuv420p" "e:\out.mp4"

-safe 0 parameter prevents Unsafe file name error

Related links

FFmpeg making a video from images placed in different folders

FFMPEG An Intermediate Guide/image sequence

Concatenate – FFmpeg

Why is json_encode adding backslashes?

json_encode will always add slashes.

Check some examples on the manual HERE

This is because if there are some characters which needs to escaped then they will create problem.

To use the json please Parse your json to ensure that the slashes are removed

Well whether or not you remove slashesthe json will be parsed without any problem by eval.

<?php
$array = array('url'=>'http://mysite.com/uploads/gallery/7f/3b/f65ab8165d_logo.jpeg','id'=>54);
?>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript">
var x = jQuery.parseJSON('<?php echo json_encode($array);?>');
alert(x);
</script>

This is my code and i m able to parse the JSON.

Check your code May be you are missing something while parsing the JSON

How to replace item in array?

The immutable way to replace the element in the list using ES6 spread operators and .slice method.

const arr = ['fir', 'next', 'third'], item = 'next'

const nextArr = [
  ...arr.slice(0, arr.indexOf(item)), 
  'second',
  ...arr.slice(arr.indexOf(item) + 1)
]

Verify that works

console.log(arr)     // [ 'fir', 'next', 'third' ]
console.log(nextArr) // ['fir', 'second', 'third']

How to run a shell script on a Unix console or Mac terminal?

The file extension .command is assigned to Terminal.app. Double-clicking on any .command file will execute it.

Can you issue pull requests from the command line on GitHub?

In addition of github/hub, which acts as a proxy to Git, you now (February 2020) have cli/cli:

See "Supercharge your command line experience: GitHub CLI is now in beta"

Create a pull request

Create a branch, make several commits to fix the bug described in the issue, and use gh to create a pull request to share your contribution.

cli/cli pr creation  -- https://i1.wp.com/user-images.githubusercontent.com/10404068/74261506-35df4080-4cb0-11ea-9285-c41583009e6c.png?ssl=1

By using GitHub CLI to create pull requests, it also automatically creates a fork when you don’t already have one, and it pushes your branch and creates your pull request to get your change merged.


And in April 2020: "GitHub CLI now supports autofilling pull requests and custom configuration"

GitHub CLI 0.7 is out with several of the most highly requested enhancements from the feedback our beta users have provided.
Since the last minor release, 0.6, there are three main features:

  • Configure gh to use your preferred editor with gh config set editor [editor].
  • Configure gh to default to SSH with gh config set git_protocol ssh.
    The default Git protocol is HTTPS.
  • Autofill the title and body of a pull request from your commits with gh pr create --fill.

So:

gh pr create --fill

Maven version with a property

With a Maven version of 3.5 or higher, you should be able to use a placeholder (e.g. ${revision}) in the parent section and inside the rest of the pom, you can use ${project.version}.

Actually, you can also omit project properties outside of parent which are the same, as they will be inherited. The result would look something like this:

<project>
    <parent>
    <artifactId>build.parent</artifactId>
    <groupId>company</groupId>
    <relativePath>../build.parent/pom.xml</relativePath>
    <version>${revision}</version>  <!-- use placeholder -->
    </parent>

    <modelVersion>4.0.0</modelVersion>
    <artifactId>artifact</artifactId>
    <!-- no 'version', no 'groupId'; inherited from parent -->
    <packaging>eclipse-plugin</packaging>

    ...
</project>

For more information, especially on how to resolve the placeholder during publishing, see Maven CI Friendly Versions | Multi Module Setup.

How to change onClick handler dynamically?

jQuery:

$('#foo').click(function() { alert('foo'); });

Or if you don't want it to follow the link href:

$('#foo').click(function() { alert('foo'); return false; });

When does Java's Thread.sleep throw InterruptedException?

A solid and easy way to handle it in single threaded code would be to catch it and retrow it in a RuntimeException, to avoid the need to declare it for every method.

Setting transparent images background in IrfanView

If you are using the batch conversion, in the window click "options" in the "Batch conversion settings-output format" and tick the two boxes "save transparent color" (one under "PNG" and the other under "ICO").

How do I verify that a string only contains letters, numbers, underscores and dashes?

If it were not for the dashes and underscores, the easiest solution would be

my_little_string.isalnum()

(Section 3.6.1 of the Python Library Reference)

ERROR 2003 (HY000): Can't connect to MySQL server (111)

I had the same problem trying to connect to a remote mysql db.

I fixed it by opening the firewall on the db server to allow traffic through:

sudo ufw allow mysql

eloquent laravel: How to get a row count from a ->get()

Answer has been updated

count is a Collection method. The query builder returns an array. So in order to get the count, you would just count it like you normally would with an array:

$wordCount = count($wordlist);

If you have a wordlist model, then you can use Eloquent to get a Collection and then use the Collection's count method. Example:

$wordlist = Wordlist::where('id', '<=', $correctedComparisons)->get();
$wordCount = $wordlist->count();

There is/was a discussion on having the query builder return a collection here: https://github.com/laravel/framework/issues/10478

However as of now, the query builder always returns an array.

Edit: As linked above, the query builder now returns a collection (not an array). As a result, what JP Foster was trying to do initially will work:

$wordlist = \DB::table('wordlist')->where('id', '<=', $correctedComparisons)
            ->get();
$wordCount = $wordlist->count();

However, as indicated by Leon in the comments, if all you want is the count, then querying for it directly is much faster than fetching an entire collection and then getting the count. In other words, you can do this:

// Query builder
$wordCount = \DB::table('wordlist')->where('id', '<=', $correctedComparisons)
            ->count();

// Eloquent
$wordCount = Wordlist::where('id', '<=', $correctedComparisons)->count();

Remove a cookie

You May Try this

if (isset($_COOKIE['remember_user'])) {
    unset($_COOKIE['remember_user']); 
    setcookie('remember_user', null, -1, '/'); 
    return true;
} else {
    return false;
}

force client disconnect from server with socket.io and nodejs

Add new socket connections to an array and then when you want to close all - loop through them and disconnect. (server side)

var socketlist = [];

   io.sockets.on('connection', function (socket) {
        socketlist.push(socket);  
        //...other code for connection here..
   });


    //close remote sockets
    socketlist.forEach(function(socket) {        
        socket.disconnect();                      
    });    

How do I create a unique constraint that also allows nulls?

CREATE UNIQUE NONCLUSTERED INDEX [UIX_COLUMN_NAME]
ON [dbo].[Employee]([Username] ASC) WHERE ([Username] IS NOT NULL) 
WITH (ALLOW_PAGE_LOCKS = ON, ALLOW_ROW_LOCKS = ON, PAD_INDEX = OFF, SORT_IN_TEMPDB = OFF, 
DROP_EXISTING = OFF, IGNORE_DUP_KEY = OFF, STATISTICS_NORECOMPUTE = OFF, ONLINE = OFF, 
MAXDOP = 0) ON [PRIMARY];

How to use QueryPerformanceCounter?

Assuming you're on Windows (if so you should tag your question as such!), on this MSDN page you can find the source for a simple, useful HRTimer C++ class that wraps the needed system calls to do something very close to what you require (it would be easy to add a GetTicks() method to it, in particular, to do exactly what you require).

On non-Windows platforms, there's no QueryPerformanceCounter function, so the solution won't be directly portable. However, if you do wrap it in a class such as the above-mentioned HRTimer, it will be easier to change the class's implementation to use what the current platform is indeed able to offer (maybe via Boost or whatever!).

What's the difference between commit() and apply() in SharedPreferences

apply() was added in 2.3, it commits without returning a boolean indicating success or failure.

commit() returns true if the save works, false otherwise.

apply() was added as the Android dev team noticed that almost no one took notice of the return value, so apply is faster as it is asynchronous.

http://developer.android.com/reference/android/content/SharedPreferences.Editor.html#apply()

How to read existing text files without defining path

You need to decide which directory you want the file to be relative to. Once you have done that, you construct the full path like this:

string fullPathToFile = Path.Combine(dir, fileName);

If you don't supply the base directory dir then you will be at the total mercy of whatever happens to the working directory of your process. That is something that can be out of your control. For example, shortcuts to your application may specify it. Using file dialogs can change it.

For a console application it is reasonable to use relative files directly because console applications are designed so that the working directory is a critical input and is a well-defined part of the execution environment. However, for a GUI app that is not the case which is why I recommend you explicitly convert your relative file name to a full absolute path using some well-defined base directory.

Now, since you have a console application, it is reasonable for you to use a relative path, provided that the expectation is that the files in question will be located in the working directory. But it would be very common for that not to be the case. Normally the working directory is used to specify where the user's input and output files are to be stored. It does not typically point to the location where the program's files are.

One final option is that you don't attempt to deploy these program files as external text files. Perhaps a better option is to link them to the executable as resources. That way they are bound up with the executable and you can completely side-step this issue.

How to remove the arrows from input[type="number"] in Opera

Those arrows are part of the Shadow DOM, which are basically DOM elements on your page which are hidden from you. If you're new to the idea, a good introductory read can be found here.

For the most part, the Shadow DOM saves us time and is good. But there are instances, like this question, where you want to modify it.

You can modify these in Webkit now with the right selectors, but this is still in the early stages of development. The Shadow DOM itself has no unified selectors yet, so the webkit selectors are proprietary (and it isn't just a matter of appending -webkit, like in other cases).

Because of this, it seems likely that Opera just hasn't gotten around to adding this yet. Finding resources about Opera Shadow DOM modifications is tough, though. A few unreliable internet sources I've found all say or suggest that Opera doesn't currently support Shadow DOM manipulation.

I spent a bit of time looking through the Opera website to see if there'd be any mention of it, along with trying to find them in Dragonfly...neither search had any luck. Because of the silence on this issue, and the developing nature of the Shadow DOM + Shadow DOM manipulation, it seems to be a safe conclusion that you just can't do it in Opera, at least for now.

How to change indentation in Visual Studio Code?

Code Formatting Shortcut:

VSCode on Windows - Shift + Alt + F

VSCode on MacOS - Shift + Option + F

VSCode on Ubuntu - Ctrl + Shift + I

You can also customize this shortcut using preference setting if needed.

column selection with keyboard Ctrl + Shift + Alt + Arrow

Handling very large numbers in Python

python supports arbitrarily large integers naturally:

example:

>>> 10**1000
10000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000

You could even get, for example of a huge integer value, fib(4000000).

But still it does not (for now) supports an arbitrarily large float !!

If you need one big, large, float then check up on the decimal Module. There are examples of use on these foruns: OverflowError: (34, 'Result too large')

Another reference: http://docs.python.org/2/library/decimal.html

You can even using the gmpy module if you need a speed-up (which is likely to be of your interest): Handling big numbers in code

Another reference: https://code.google.com/p/gmpy/

How do I set headers using python's urllib?

For both Python 3 and Python 2, this works:

try:
    from urllib.request import Request, urlopen  # Python 3
except ImportError:
    from urllib2 import Request, urlopen  # Python 2

req = Request('http://api.company.com/items/details?country=US&language=en')
req.add_header('apikey', 'xxx')
content = urlopen(req).read()

print(content)

Calculating width from percent to pixel then minus by pixel in LESS CSS

I think width: -moz-calc(25% - 1em); is what you are looking for. And you may want to give this Link a look for any further assistance

If else on WHERE clause

try this ,hope it helps

select user_display_image as user_image,
user_display_name as user_name,
invitee_phone,
(
 CASE 
    WHEN invitee_status=1 THEN "attending" 
    WHEN invitee_status=2 THEN "unsure" 
    WHEN invitee_status=3 THEN "declined" 
    WHEN invitee_status=0 THEN "notreviwed" END
) AS  invitee_status
 FROM your_tbl

What's the yield keyword in JavaScript?

Dependency between async javascript calls.

Another good example of how yield can be used.

_x000D_
_x000D_
function request(url) {_x000D_
  axios.get(url).then((reponse) => {_x000D_
    it.next(response);_x000D_
  })_x000D_
}_x000D_
_x000D_
function* main() {_x000D_
  const result1 = yield request('http://some.api.com' );_x000D_
  const result2 = yield request('http://some.otherapi?id=' + result1.id );_x000D_
  console.log('Your response is: ' + result2.value);_x000D_
}_x000D_
_x000D_
var it = main();_x000D_
it.next()
_x000D_
_x000D_
_x000D_

Java: print contents of text file to screen

For those new to Java and wondering why Jiri's answer doesn't work, make sure you do what he says and handle the exception or else it won't compile. Here's the bare minimum:

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class ReadFile {

    public static void main(String args[]) throws IOException {
        BufferedReader br = new BufferedReader(new FileReader("test.txt"));
        for (String line; (line = br.readLine()) != null;) {
            System.out.print(line);
        }
        br.close()
    }
}

Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock' (2)

Are you connecting to "localhost" or "127.0.0.1" ? I noticed that when you connect to "localhost" the socket connector is used, but when you connect to "127.0.0.1" the TCP/IP connector is used. You could try using "127.0.0.1" if the socket connector is not enabled/working.

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

i found Cody Gray 's answer partially helpful, in that it did direct me to the real source of my problem which some of you may also be experiencing: visual studio's test execution stays open by default and maintains a lock on the files.

To stop that predominantly useless behaviour, follow the instructions from https://connect.microsoft.com/VisualStudio/feedback/details/771994/vstest-executionengine-x86-exe-32-bit-not-closing-vs2012-11-0-50727-1-rtmrel

Uncheck Test menu -> Test Settings -> "Keep Test Execution Engine Running"

How do you round UP a number in Python?

You might also like numpy:

>>> import numpy as np
>>> np.ceil(2.3)
3.0

I'm not saying it's better than math, but if you were already using numpy for other purposes, you can keep your code consistent.

Anyway, just a detail I came across. I use numpy a lot and was surprised it didn't get mentioned, but of course the accepted answer works perfectly fine.

"Unable to acquire application service" error while launching Eclipse

I've been downloaded the "SDK ADT Bundle for Windows" adt-bundle-windows-x86.zip to "Documents and settings\myusername\My Documents\Downloads" and tried to unzip to a folder c:\Android

When all seems to be decompressed I saw some files where missing in the destination folder including the eclipse.ini.

I solved this by renaming adt-bundle-windows-x86.zip to a short name adt.zip, moving it to c:\ and repeating the decompression.

All is due to bad treatment of long file-names in windows

How to change colors of a Drawable in Android?

In your Activity you can tint your PNG image resources with a single colour:

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    myColorTint();
    setContentView(R.layout.activity_main);
}

private void myColorTint() {
    int tint = Color.parseColor("#0000FF"); // R.color.blue;
    PorterDuff.Mode mode = PorterDuff.Mode.SRC_ATOP;
    // add your drawable resources you wish to tint to the drawables array...
    int drawables[] = { R.drawable.ic_action_edit, R.drawable.ic_action_refresh };
    for (int id : drawables) {
        Drawable icon = getResources().getDrawable(id);
        icon.setColorFilter(tint,mode);
    }
}

Now when you use the R.drawable.* it should be coloured with the desired tint. If you need additional colours then you should be able to .mutate() the drawable.

ng-if, not equal to?

Here is a nifty solution with a filter:

app.filter('status', function() {

  var statusDict = {
    0: "No payment",
    1: "Late",
    2: "Late",
    3: "Some payment made",
    4: "Some payment made",
    5: "Some payment made",
    6: "Late and further taken out"
  };

  return function(status) {
    return statusDict[status] || 'Error';
  };
});

Markup:

<div ng-repeat="details in myDataSet">
  <p>{{ details.Name }}</p>
  <p>{{ details.DOB  }}</p>
  <p>{{ details.Payment[0].Status | status }}</p>
  <p>{{ details.Gender}}</p>
</div>

How to view .img files?

If you use Linux or WSL you can use the forensic application binwalk to extract .img files (which are usually disk images) like this:

  1. Use your distribution package manager or follow the manual instructions to install binwalk.

  2. Use the command binwalk -e FILENAME.img to extract recognized content into a automatically generated directory.

PHP: Return all dates between two dates in an array

// will return dates array
function returnBetweenDates( $startDate, $endDate ){
    $startStamp = strtotime(  $startDate );
    $endStamp   = strtotime(  $endDate );

    if( $endStamp > $startStamp ){
        while( $endStamp >= $startStamp ){

            $dateArr[] = date( 'Y-m-d', $startStamp );

            $startStamp = strtotime( ' +1 day ', $startStamp );

        }
        return $dateArr;    
    }else{
        return $startDate;
    }

}

returnBetweenDates( '2014-09-16', '2014-09-26' );

// print_r( returnBetweenDates( '2014-09-16', '2014-09-26' ) );

it will return array like below:

Array
(
    [0] => 2014-09-16
    [1] => 2014-09-17
    [2] => 2014-09-18
    [3] => 2014-09-19
    [4] => 2014-09-20
    [5] => 2014-09-21
    [6] => 2014-09-22
    [7] => 2014-09-23
    [8] => 2014-09-24
    [9] => 2014-09-25
    [10] => 2014-09-26
)

How to track down access violation "at address 00000000"

Here is a real quick temporary fix, at least until you reboot again but it will get rid of a persistent access. I had installed a program that works fine but for some reason, there is a point that did not install correctly in the right file. So when it cannot access the file, it pops up the access denied but instead of just one, it keeps trying to start it up so even searching for the location to stop it permanently, it will continue to pop up more and more and more every 3 seconds. To stop that from happening at least temporarily, do the following...

  1. Ctl+Alt+Del
  2. Open your Task Manager
  3. Note down the name of the program that's requesting access (you may see it in your application's tab)
  4. Click on your Processes tab
  5. Scroll through until you find the Process matching the program name and click on it
  6. Click End Process

That will prevent the window from persistently popping up, at least until you reboot. I know that does not solve the problem but like anything, there is a process of elimination and this step here will at least make it a little less annoying.

Cannot set content-type to 'application/json' in jQuery.ajax

I recognized those screens, I'm using CodeFluentEntities, and I've got solution that worked for me as well.

I'm using that construction:

$.ajax({
   url: path,
   type: "POST",
   contentType: "text/plain",
   data: {"some":"some"}
}

as you can see, if I use

contentType: "",

or

contentType: "text/plain", //chrome

Everything works fine.

I'm not 100% sure that it's all that you need, cause I've also changed headers.

Populating Spring @Value during Unit Test

Spring Boot do a lot of automatically things to us but when we use the annotation @SpringBootTest we think that everything will be automatically solved by Spring boot.

There are a lot of documentation, but the minimal is to choose one engine (@RunWith(SpringRunner.class)) and indicate the class that will be used create the context to load the configuration (resources/applicationl.properties).

In a simple way you need the engine and the context:

@RunWith(SpringRunner.class)
@SpringBootTest(classes = MyClassTest .class)
public class MyClassTest {

    @Value("${my.property}")
    private String myProperty;

    @Test
    public void checkMyProperty(){
        Assert.assertNotNull(my.property);
    }
}

Of course, if you look the Spring Boot documentation you will find thousands os ways to do that.

I can't install pyaudio on Windows? How to solve "error: Microsoft Visual C++ 14.0 is required."?

You should just install python 3.6. I tried it and it worked. Just install that version of python and just do the normal download process (pip install pyaudio).

How do you 'redo' changes after 'undo' with Emacs?

By default, redo in Emacs requires pressing C-g, then undo.

However it's possible use Emacs built-in undo to implement a redo command too.

The package undo-fu, uses Emacs built-in undo functionality to expose both undo and redo.

how to pass parameters to query in SQL (Excel)

It depends on the database to which you're trying to connect, the method by which you created the connection, and the version of Excel that you're using. (Also, most probably, the version of the relevant ODBC driver on your computer.)

The following examples are using SQL Server 2008 and Excel 2007, both on my local machine.

When I used the Data Connection Wizard (on the Data tab of the ribbon, in the Get External Data section, under From Other Sources), I saw the same thing that you did: the Parameters button was disabled, and adding a parameter to the query, something like select field from table where field2 = ?, caused Excel to complain that the value for the parameter had not been specified, and the changes were not saved.

When I used Microsoft Query (same place as the Data Connection Wizard), I was able to create parameters, specify a display name for them, and enter values each time the query was run. Bringing up the Connection Properties for that connection, the Parameters... button is enabled, and the parameters can be modified and used as I think you want.

I was also able to do this with an Access database. It seems reasonable that Microsoft Query could be used to create parameterized queries hitting other types of databases, but I can't easily test that right now.

Simplest PHP example for retrieving user_timeline with Twitter API version 1.1

You'll need a to create an "app" on Twitter (and you need a Twitter account to do this).

Then, you need to use OAuth to make an authorized request to Twitter.

You can use the GET statuses/user_timeline resource to get a list of recent tweets.

Compiling C++ on remote Linux machine - "clock skew detected" warning

That message is usually an indication that some of your files have modification times later than the current system time. Since make decides which files to compile when performing an incremental build by checking if a source files has been modified more recently than its object file, this situation can cause unnecessary files to be built, or worse, necessary files to not be built.

However, if you are building from scratch (not doing an incremental build) you can likely ignore this warning without consequence.

What linux shell command returns a part of a string?

expr(1) has a substr subcommand:

expr substr <string> <start-index> <length>

This may be useful if you don't have bash (perhaps embedded Linux) and you don't want the extra "echo" process you need to use cut(1).

Replacing H1 text with a logo image: best method for SEO and accessibility?

I think you'd be interested in the H1 debate. It's a debate about whether to use the h1 element for the page's title or for the logo.

Personally I'd go with your first suggestion, something along these lines:

<div id="header">
    <a href="http://example.com/"><img src="images/logo.png" id="site-logo" alt="MyCorp" /></a>
</div>

<!-- or alternatively (with css in a stylesheet ofc-->
<div id="header">
    <div id="logo" style="background: url('logo.png'); display: block; 
        float: left; width: 100px; height: 50px;">
        <a href="#" style="display: block; height: 50px; width: 100px;">
            <span style="visibility: hidden;">Homepage</span>
        </a>
    </div>
    <!-- with css in a stylesheet: -->
    <div id="logo"><a href="#"><span>Homepage</span></a></div>
</div>


<div id="body">
    <h1>About Us</h1>
    <p>MyCorp has been dealing in narcotics for over nine-thousand years...</p>
</div>

Of course this depends on whether your design uses page titles but this is my stance on this issue.

Optional Parameters in Go?

Go does not have optional parameters nor does it support method overloading:

Method dispatch is simplified if it doesn't need to do type matching as well. Experience with other languages told us that having a variety of methods with the same name but different signatures was occasionally useful but that it could also be confusing and fragile in practice. Matching only by name and requiring consistency in the types was a major simplifying decision in Go's type system.

What is the easiest way to remove the first character from a string?

class String
  def bye_felicia()
    felicia = self.strip[0] #first char, not first space.
    self.sub(felicia, '')
  end
end

Storing and displaying unicode string (??????) using PHP and MySQL

For Those who are facing difficulty just got to php admin and change collation to utf8_general_ci Select Table go to Operations>> table options>> collations should be there

Unbalanced calls to begin/end appearance transitions for <UITabBarController: 0x197870>

I encountered this error when I hooked a UIButton to a storyboard segue action (in IB) but later decided to have the button programatically call performSegueWithIdentifier forgetting to remove the first one from IB.

In essence it performed the segue call twice, gave this error and actually pushed my view twice. The fix was to remove one of the segue calls.

Hope this helps someone as tired as me!

Send values from one form to another form

There are several solutions to this but this is the pattern I tend to use.

// Form 1
// inside the button click event
using(Form2 form2 = new Form2()) 
{
    if(form2.ShowDialog() == DialogResult.OK) 
    {
        someControlOnForm1.Text = form2.TheValue;
    }
}

And...

// Inside Form2
// Create a public property to serve the value
public string TheValue 
{
    get { return someTextBoxOnForm2.Text; }
}

How to fix "set SameSite cookie to none" warning?

As the new feature comes, SameSite=None cookies must also be marked as Secure or they will be rejected.

One can find more information about the change on chromium updates and on this blog post

Note: not quite related directly to the question, but might be useful for others who landed here as it was my concern at first during development of my website:

if you are seeing the warning from question that lists some 3rd party sites (in my case it was google.com, huh) - that means they need to fix it and it's nothing to do with your site. Of course unless the warning mentions your site, in which case adding Secure should fix it.

Sample database for exercise

This is an online database but you can try with the stackoverflow database: https://data.stackexchange.com/stackoverflow/query/new

You also can download its dumps here:

https://archive.org/download/stackexchange

Merge two rows in SQL

There are a few ways depending on some data rules that you have not included, but here is one way using what you gave.

SELECT
    t1.Field1,
    t2.Field2
FROM Table1 t1
    LEFT JOIN Table1 t2 ON t1.FK = t2.FK AND t2.Field1 IS NULL

Another way:

SELECT
    t1.Field1,
    (SELECT Field2 FROM Table2 t2 WHERE t2.FK = t1.FK AND Field1 IS NULL) AS Field2
FROM Table1 t1

jQuery - Getting form values for ajax POST

Use the serialize method:

$.ajax({
    ...
    data: $("#registerSubmit").serialize(),
    ...
})

Docs: serialize()

Print text instead of value from C enum

I like this to have enum in the dayNames. To reduce typing, we can do the following:

#define EP(x) [x] = #x  /* ENUM PRINT */

const char* dayNames[] = { EP(Sunday), EP(Monday)};

MySQL create stored procedure syntax with delimiter

Getting started with stored procedure syntax in MySQL (using the terminal):

1. Open a terminal and login to mysql like this:

el@apollo:~$ mysql -u root -p
Enter password: 
Welcome to the MySQL monitor.  Commands end with ; or \g.
mysql> 

2. Take a look to see if you have any procedures:

mysql> show procedure status;
+-----------+---------------+-----------+---------+---------------------+---------------------+---------------+---------+----------------------+----------------------+--------------------+
| Db        | Name          | Type      | Definer | Modified            | Created             | Security_type | Comment | character_set_client | collation_connection | Database Collation |
+-----------+---------------+-----------+---------+---------------------+---------------------+---------------+---------+----------------------+----------------------+--------------------+
|   yourdb  | sp_user_login | PROCEDURE | root@%  | 2013-12-06 14:10:25 | 2013-12-06 14:10:25 | DEFINER       |         | utf8                 | utf8_general_ci      | latin1_swedish_ci  |
+-----------+---------------+-----------+---------+---------------------+---------------------+---------------+---------+----------------------+----------------------+--------------------+
1 row in set (0.01 sec)

I have one defined, you probably have none to start out.

3. Change to the database, delete it.

mysql> use yourdb;
Database changed

mysql> drop procedure if exists sp_user_login;
Query OK, 0 rows affected (0.01 sec)
    
mysql> show procedure status;
Empty set (0.00 sec)
    

4. Ok so now I have no stored procedures defined. Make the simplest one:

mysql> delimiter //
mysql> create procedure foobar()
    -> begin select 'hello'; end//
Query OK, 0 rows affected (0.00 sec)

The // will communicate to the terminal when you are done entering commands for the stored procedure. the stored procedure name is foobar. it takes no parameters and should return "hello".

5. See if it's there, remember to set back your delimiter!:

 mysql> show procedure status;
 -> 
 -> 

Gotcha! Why didn't this work? You set the delimiter to // remember? Set it back to ;

6. Set the delimiter back and look at the procedure:

mysql> delimiter ;
mysql> show procedure status;
+-----------+--------+-----------+----------------+---------------------+---------------------+---------------+---------+----------------------+----------------------+--------------------+
| Db        | Name   | Type      | Definer        | Modified            | Created             | Security_type | Comment | character_set_client | collation_connection | Database Collation |
+-----------+--------+-----------+----------------+---------------------+---------------------+---------------+---------+----------------------+----------------------+--------------------+
| yourdb    | foobar | PROCEDURE | root@localhost | 2013-12-06 14:27:23 | 2013-12-06 14:27:23 | DEFINER       |         | utf8                 | utf8_general_ci      | latin1_swedish_ci  |
+-----------+--------+-----------+----------------+---------------------+---------------------+---------------+---------+----------------------+----------------------+--------------------+
1 row in set (0.00 sec)

   

7. Run it:

mysql> call foobar();
+-------+
| hello |
+-------+
| hello |
+-------+
1 row in set (0.00 sec)
Query OK, 0 rows affected (0.00 sec)

Hello world complete, lets overwrite it with something better.

8. Drop foobar, redefine it to accept a parameter, and re run it:

mysql> drop procedure foobar;
Query OK, 0 rows affected (0.00 sec)

mysql> show procedure status;
Empty set (0.00 sec)

mysql> delimiter //
mysql> create procedure foobar (in var1 int)
    -> begin select var1 + 2 as result;
    -> end//
Query OK, 0 rows affected (0.00 sec)

mysql> delimiter ;
mysql> call foobar(5);
+--------+
| result |
+--------+
|      7 |
+--------+
1 row in set (0.00 sec)
Query OK, 0 rows affected (0.00 sec)

Nice! We made a procedure that takes input, modifies it, and does output. Now lets do an out variable.

9. Remove foobar, Make an out variable, run it:

mysql> delimiter ;
mysql> drop procedure foobar;
Query OK, 0 rows affected (0.00 sec)

mysql> delimiter //
mysql> create procedure foobar(out var1 varchar(100))
    -> begin set var1="kowalski, what's the status of the nuclear reactor?";
    -> end//
Query OK, 0 rows affected (0.00 sec)


mysql> delimiter ;
mysql> call foobar(@kowalski_status);
Query OK, 0 rows affected (0.00 sec)

mysql> select @kowalski_status;
+-----------------------------------------------------+
| @kowalski_status                                    |
+-----------------------------------------------------+
| kowalski, what's the status of the nuclear reactor? |
+-----------------------------------------------------+
1 row in set (0.00 sec)

10. Example of INOUT usage in MySQL:

mysql> select 'ricksays' into @msg;
Query OK, 1 row affected (0.00 sec)


mysql> delimiter //
mysql> create procedure foobar (inout msg varchar(100))
-> begin
-> set msg = concat(@msg, " never gonna let you down");
-> end//


mysql> delimiter ;


mysql> call foobar(@msg);
Query OK, 0 rows affected (0.00 sec)


mysql> select @msg;
+-----------------------------------+
| @msg                              |
+-----------------------------------+
| ricksays never gonna let you down |
+-----------------------------------+
1 row in set (0.00 sec)

Ok it worked, it joined the strings together. So you defined a variable msg, passed in that variable into stored procedure called foobar, and @msg was written to by foobar.

Now you know how to make stored procedures with delimiters. Continue this tutorial here, start in on variables within stored procedures: http://net.tutsplus.com/tutorials/an-introduction-to-stored-procedures/

How do I replace part of a string in PHP?

You can try

$string = "this is the test for string." ;
$string = str_replace(' ', '_', $string);
$string = substr($string,0,10);

var_dump($string);

Output

this_is_th

Using a PHP variable in a text input value = statement

If you want to read any created function, this how we do it:

<input type="button" value="sports" onClick="window.open('<?php sports();?>', '_self');">

Pass entire form as data in jQuery Ajax function

You just have to post the data. and Using jquery ajax function set parameters. Here is an example.

<script>
        $(function () {

            $('form').on('submit', function (e) {

                e.preventDefault();

                $.ajax({
                    type: 'post',
                    url: 'your_complete url',
                    data: $('form').serialize(),
                    success: function (response) {
                        //$('form')[0].reset();
                       // $("#feedback").text(response);
                        if(response=="True") {
                            $('form')[0].reset();
                            $("#feedback").text("Your information has been stored.");
                        }
                        else
                            $("#feedback").text(" Some Error has occured Errror !!! ID duplicate");
                    }
                });

            });

        });
    </script>

CodeIgniter PHP Model Access "Unable to locate the model you have specified"

I experienced the same problem, but I fixed it by altering my application/config/routes.php file.

I made some restructuring to my controller directories and forget to effect it on the routes file.

Earlier:

$route['application/apply'] = 'ex/application/account/create';

and now:

$route['application/apply'] = 'application/account/create';

Jquery - Uncaught TypeError: Cannot use 'in' operator to search for '324' in

You have a JSON string, not an object. Tell jQuery that you expect a JSON response and it will parse it for you. Either use $.getJSON instead of $.get, or pass the dataType argument to $.get:

$.get(
    'index.php?r=admin/post/ajax',
    {"parentCatId":parentCatId},
    function(data){                     
        $.each(data, function(key, value){
            console.log(key + ":" + value)
        })
    },
    'json'
);

How do I create a file and write to it?

If you for some reason want to separate the act of creating and writing, the Java equivalent of touch is

try {
   //create a file named "testfile.txt" in the current working directory
   File myFile = new File("testfile.txt");
   if ( myFile.createNewFile() ) {
      System.out.println("Success!");
   } else {
      System.out.println("Failure!");
   }
} catch ( IOException ioe ) { ioe.printStackTrace(); }

createNewFile() does an existence check and file create atomically. This can be useful if you want to ensure you were the creator of the file before writing to it, for example.

Change color of bootstrap navbar on hover link?

Updated 2018

You can change the Navbar link colors with CSS to override Bootstrap colors...

Bootstrap 4

.navbar-nav .nav-item .nav-link {
    color: red;
}
.navbar-nav .nav-item.active .nav-link,
.navbar-nav .nav-item:hover .nav-link {
    color: pink;
}

Bootstrap 4 navbar link color demo

Bootstrap 3

.navbar .navbar-nav > li > a,
.navbar .navbar-nav > .active > a{
    color: orange;
}

.navbar .navbar-nav > li > a:hover,
.navbar .navbar-nav > li > a:focus,
.navbar .navbar-nav > .active > a:hover,
.navbar .navbar-nav > .active > a:focus {
    color: red;
}

Bootstrap 3 navbar link color demo


The change or customize the entire Navbar color, see: https://stackoverflow.com/a/18530995/171456

React Router v4 - How to get current route?

In react router 4 the current route is in - this.props.location.pathname. Just get this.props and verify. If you still do not see location.pathname then you should use the decorator withRouter.

This might look something like this:

import {withRouter} from 'react-router-dom';

const SomeComponent = withRouter(props => <MyComponent {...props}/>);

class MyComponent extends React.Component {
  SomeMethod () {
    const {pathname} = this.props.location;
  }
}

How to retrieve Jenkins build parameters using the Groovy API?

Update: Jenkins 2.x solution:

With Jenkins 2 pipeline dsl, you can directly access any parameter with the trivial syntax based on the params (Map) built-in:

echo " FOOBAR value: ${params.'FOOBAR'}"

The returned value will be a String or a boolean depending on the Parameter type itself. The syntax is the same for scripted or declarative syntax. More info at: https://jenkins.io/doc/book/pipeline/jenkinsfile/#handling-parameters

Original Answer for Jenkins 1.x:

For Jenkins 1.x, the syntax is based on the build.buildVariableResolver built-ins:

// ... or if you want the parameter by name ...
def hardcoded_param = "FOOBAR"
def resolver = build.buildVariableResolver
def hardcoded_param_value = resolver.resolve(hardcoded_param)

Please note the official Jenkins Wiki page covers this in more details as well, especially how to iterate upon the build parameters: https://wiki.jenkins-ci.org/display/JENKINS/Parameterized+System+Groovy+script

The salient part is reproduced below:

// get parameters
def parameters = build?.actions.find{ it instanceof ParametersAction }?.parameters
parameters.each {
   println "parameter ${it.name}:"
   println it.dump()
}

Set Google Maps Container DIV width and height 100%

Better late than never! I made mine a class:

.map
{
    position:absolute;
    top:64px;
    width:1100px;
    height:735px;
    overflow:hidden;
    border:1px solid rgb(211,211,211);
    border-radius:3px;
}

and then

<div id="map" class="map"></div>

How do I sort a VARCHAR column in SQL server that contains numbers?

you can always convert your varchar-column to bigint as integer might be too short...

select cast([yourvarchar] as BIGINT)

but you should always care for alpha characters

where ISNUMERIC([yourvarchar] +'e0') = 1

the +'e0' comes from http://blogs.lessthandot.com/index.php/DataMgmt/DataDesign/isnumeric-isint-isnumber

this would lead to your statement

SELECT
  *
FROM
  Table
ORDER BY
   ISNUMERIC([yourvarchar] +'e0') DESC
 , LEN([yourvarchar]) ASC

the first sorting column will put numeric on top. the second sorts by length, so 10 will preceed 0001 (which is stupid?!)

this leads to the second version:

SELECT
      *
    FROM
      Table
    ORDER BY
       ISNUMERIC([yourvarchar] +'e0') DESC
     , RIGHT('00000000000000000000'+[yourvarchar], 20) ASC

the second column now gets right padded with '0', so natural sorting puts integers with leading zeros (0,01,10,0100...) in correct order (correct!) - but all alphas would be enhanced with '0'-chars (performance)

so third version:

 SELECT
          *
        FROM
          Table
        ORDER BY
           ISNUMERIC([yourvarchar] +'e0') DESC
         , CASE WHEN ISNUMERIC([yourvarchar] +'e0') = 1
                THEN RIGHT('00000000000000000000' + [yourvarchar], 20) ASC
                ELSE LTRIM(RTRIM([yourvarchar]))
           END ASC

now numbers first get padded with '0'-chars (of course, the length 20 could be enhanced) - which sorts numbers right - and alphas only get trimmed

PHP errors NOT being displayed in the browser [Ubuntu 10.10]

After you edit /etc/php5/apache2/php.ini be sure to restart apache.

You can do so by running:

sudo service apache2 restart

Bind service to activity in Android

If the user backs out, the onDestroy() method will be called. This method is to stop any service that is used in the application. So if you want to continue the service even if the user backs out of the application, just erase onDestroy(). Hope this help.

How do I get the browser scroll position in jQuery?

Since it appears you are using jQuery, here is a jQuery solution.

$(function() {
    $('#Eframe').on("mousewheel", function() {
        alert($(document).scrollTop());
    });
});

Not much to explain here. If you want, here is the jQuery documentation.

Passing 'this' to an onclick event

Yeah first method will work on any element called from elsewhere since it will always take the target element irrespective of id.

check this fiddle

http://jsfiddle.net/8cvBM/

Using GregorianCalendar with SimpleDateFormat

SimpleDateFormat.format() method takes a Date as a parameter. You can get a Date from a Calendar by calling its getTime() method:

public static String format(GregorianCalendar calendar) {
    SimpleDateFormat fmt = new SimpleDateFormat("dd-MMM-yyyy");
    fmt.setCalendar(calendar);
    String dateFormatted = fmt.format(calendar.getTime());

    return dateFormatted;
}

Also note that the months start at 0, so you probably meant:

int month = Integer.parseInt(splitDate[1]) - 1;

Getting strings recognized as variable names in R

Without any example data, it really is difficult to know exactly what you are wanting. For instance, I can't at all divine what your object set (or is it sets) looks like.

That said, does the following help at all?

set1 <- data.frame(x = 4:6, y = 6:4, z = c(1, 3, 5))

plot(1:10, type="n")
XX <- "set1"
with(eval(as.symbol(XX)), symbols(x, y, circles = z, add=TRUE))

EDIT:

Now that I see your real task, here is a one-liner that'll do everything you want without requiring any for() loops:

with(dat, symbols(sq, cu, circles = num,
                  bg = c("red", "blue")[(num>5) + 1]))

The one bit of code that may feel odd is the bit specifying the background color. Try out these two lines to see how it works:

c(TRUE, FALSE) + 1
# [1] 2 1
c("red", "blue")[c(F, F, T, T) + 1]
# [1] "red"  "red"  "blue" "blue"

What is an OS kernel ? How does it differ from an operating system?

The technical definition of an operating system is "a platform that consists of specific set of libraries and infrastructure for applications to be built upon and interact with each other". A kernel is an operating system in that sense.

The end-user definition is usually something around "a software package that provides a desktop, shortcuts to applications, a web browser and a media player". A kernel doesn't match that definition.

So for an end-user a Linux distribution (say Ubuntu) is an Operating System while for a programmer the Linux kernel itself is a perfectly valid OS depending on what you're trying to achieve. For instance embedded systems are mostly just kernel with very small number of specialized processes running on top of them. In that case the kernel itself becomes the OS itself.

I think you can draw the line at what the majority of the applications running on top of that OS do require. If most of them require only kernel, the kernel is the OS, if most of them require X Window System running, then your OS becomes X + kernel.

WITH CHECK ADD CONSTRAINT followed by CHECK CONSTRAINT vs. ADD CONSTRAINT

The first syntax is redundant - the WITH CHECK is default for new constraints, and the constraint is turned on by default as well.

This syntax is generated by the SQL management studio when generating sql scripts -- I'm assuming it's some sort of extra redundancy, possibly to ensure the constraint is enabled even if the default constraint behavior for a table is changed.

How to execute .sql file using powershell?

Here is a function that I have in my PowerShell profile for loading SQL snapins:

function Load-SQL-Server-Snap-Ins
{
    try 
    {
        $sqlpsreg="HKLM:\SOFTWARE\Microsoft\PowerShell\1\ShellIds\Microsoft.SqlServer.Management.PowerShell.sqlps"

        if (!(Test-Path $sqlpsreg -ErrorAction "SilentlyContinue"))
        {
            throw "SQL Server Powershell is not installed yet (part of SQLServer installation)."
        }

        $item = Get-ItemProperty $sqlpsreg
        $sqlpsPath = [System.IO.Path]::GetDirectoryName($item.Path)

        $assemblyList = @(
            "Microsoft.SqlServer.Smo",
            "Microsoft.SqlServer.SmoExtended",
            "Microsoft.SqlServer.Dmf",
            "Microsoft.SqlServer.WmiEnum",
            "Microsoft.SqlServer.SqlWmiManagement",
            "Microsoft.SqlServer.ConnectionInfo ",
            "Microsoft.SqlServer.Management.RegisteredServers",
            "Microsoft.SqlServer.Management.Sdk.Sfc",
            "Microsoft.SqlServer.SqlEnum",
            "Microsoft.SqlServer.RegSvrEnum",
            "Microsoft.SqlServer.ServiceBrokerEnum",
            "Microsoft.SqlServer.ConnectionInfoExtended",
            "Microsoft.SqlServer.Management.Collector",
            "Microsoft.SqlServer.Management.CollectorEnum"
        )

        foreach ($assembly in $assemblyList)
        { 
            $assembly = [System.Reflection.Assembly]::LoadWithPartialName($assembly) 
            if ($assembly -eq $null)
                { Write-Host "`t`t($MyInvocation.InvocationName): Could not load $assembly" }
        }

        Set-Variable -scope Global -name SqlServerMaximumChildItems -Value 0
        Set-Variable -scope Global -name SqlServerConnectionTimeout -Value 30
        Set-Variable -scope Global -name SqlServerIncludeSystemObjects -Value $false
        Set-Variable -scope Global -name SqlServerMaximumTabCompletion -Value 1000

        Push-Location

         if ((Get-PSSnapin -Name SqlServerProviderSnapin100 -ErrorAction SilentlyContinue) -eq $null) 
        { 
            cd $sqlpsPath

            Add-PsSnapin SqlServerProviderSnapin100 -ErrorAction Stop
            Add-PsSnapin SqlServerCmdletSnapin100 -ErrorAction Stop
            Update-TypeData -PrependPath SQLProvider.Types.ps1xml
            Update-FormatData -PrependPath SQLProvider.Format.ps1xml
        }
    } 

    catch 
    {
        Write-Host "`t`t$($MyInvocation.InvocationName): $_" 
    }

    finally
    {
        Pop-Location
    }
}

Detect click outside element

Complete case for vue 3

This is a complete solution based on MadisonTrash answer, and benrwb and fredrivett tweaks for safari compatibility and vue 3 api changes.

Edit:

The solution proposed below is still useful, and the how to use is still valid, but I changed it to use document.elementsFromPoint instead of event.contains because it doesn't recognise as children some elements like the <path> tags inside svgs. So the right directive is this one:

export default {
    beforeMount: (el, binding) => {
        el.eventSetDrag = () => {
            el.setAttribute("data-dragging", "yes");
        };
        el.eventClearDrag = () => {
            el.removeAttribute("data-dragging");
        };
        el.eventOnClick = event => {
            const dragging = el.getAttribute("data-dragging");
            // Check that the click was outside the el and its children, and wasn't a drag
            console.log(document.elementsFromPoint(event.clientX, event.clientY))
            if (!document.elementsFromPoint(event.clientX, event.clientY).includes(el) && !dragging) {
                // call method provided in attribute value
                binding.value(event);
            }
        };
        document.addEventListener("touchstart", el.eventClearDrag);
        document.addEventListener("touchmove", el.eventSetDrag);
        document.addEventListener("click", el.eventOnClick);
        document.addEventListener("touchend", el.eventOnClick);
    },
    unmounted: el => {
        document.removeEventListener("touchstart", el.eventClearDrag);
        document.removeEventListener("touchmove", el.eventSetDrag);
        document.removeEventListener("click", el.eventOnClick);
        document.removeEventListener("touchend", el.eventOnClick);
        el.removeAttribute("data-dragging");
    },
};

Old answer:

Directive

const clickOutside = {
    beforeMount: (el, binding) => {
        el.eventSetDrag = () => {
            el.setAttribute("data-dragging", "yes");
        };
        el.eventClearDrag = () => {
            el.removeAttribute("data-dragging");
        };
        el.eventOnClick = event => {
            const dragging = el.getAttribute("data-dragging");  
            // Check that the click was outside the el and its children, and wasn't a drag
            if (!(el == event.target || el.contains(event.target)) && !dragging) {
                // call method provided in attribute value
                binding.value(event);
            }
        };
        document.addEventListener("touchstart", el.eventClearDrag);
        document.addEventListener("touchmove", el.eventSetDrag);
        document.addEventListener("click", el.eventOnClick);
        document.addEventListener("touchend", el.eventOnClick);
    },
    unmounted: el => {
        document.removeEventListener("touchstart", el.eventClearDrag);
        document.removeEventListener("touchmove", el.eventSetDrag);
        document.removeEventListener("click", el.eventOnClick);
        document.removeEventListener("touchend", el.eventOnClick);
        el.removeAttribute("data-dragging");
    },
}

createApp(App)
  .directive("click-outside", clickOutside)
  .mount("#app");

This solution watch the element and the element's children of the component where the directive is applied to check if the event.target element is also a child. If that's the case it will not trigger, because it's inside the component.

How to use it

You only have to use as any directive, with a method reference to handle the trigger:

<template>
    <div v-click-outside="myMethod">
        <div class="handle" @click="doAnotherThing($event)">
            <div>Any content</div>
        </div>
    </div>
</template>

Difference between Hashing a Password and Encrypting it

I've always thought that Encryption can be converted both ways, in a way that the end value can bring you to original value and with Hashing you'll not be able to revert from the end result to the original value.

Convert JavaScript String to be all lower case?

Note that the function will ONLY work on STRING objects.

For instance, I was consuming a plugin, and was confused why I was getting a "extension.tolowercase is not a function" JS error.

 onChange: function(file, extension)
    {
      alert("extension.toLowerCase()=>" + extension.toLowerCase() + "<=");

Which produced the error "extension.toLowerCase is not a function" So I tried this piece of code, which revealed the problem!

alert("(typeof extension)=>" + (typeof extension) + "<=");;

The output was"(typeof extension)=>object<=" - so AhHa, I was NOT getting a string var for my input. The fix is straight forward though - just force the darn thing into a String!:

var extension = String(extension);

After the cast, the extension.toLowerCase() function worked fine.

When should I use double or single quotes in JavaScript?

There is strictly no difference, so it is mostly a matter of taste and of what is in the string (or if the JavaScript code itself is in a string), to keep number of escapes low.

The speed difference legend might come from PHP world, where the two quotes have different behavior.

ADB No Devices Found

I have found a solution for my case.

  1. Go to Tools->Layout Inspector.
  2. Press Restart button a few times.

I have no idea how it connect with ADB but it works.

How To Upload Files on GitHub

I didn't find the above answers sufficiently explicit, and it took me some time to figure it out for myself. The most useful page I found was: http://www.lockergnome.com/web/2011/12/13/how-to-use-github-to-contribute-to-open-source-projects/

I'm on a Unix box, using the command line. I expect this will all work on a Mac command line. (Mac or Window GUI looks to be available at desktop.github.com but I haven't tested this, and don't know how transferable this will be to the GUI.)

Step 1: Create a Github account Step 2: Create a new repository, typically with a README and LICENCE file created in the process. Step 3: Install "git" software. (Links in answers above and online help at github should suffice to do these steps, so I don't provide detailed instructions.) Step 4: Tell git who you are:

git config --global user.name "<NAME>"
git config --global user.email "<email>"

I think the e-mail must be one of the addresses you have associated with the github account. I used the same name as I used in github, but I think (not sure) that this is not required. Optionally you can add caching of credentials, so you don't need to type in your github account name and password so often. https://help.github.com/articles/caching-your-github-password-in-git/

Create and navigate to some top level working directory:

mkdir <working>
cd <working>

Import the nearly empty repository from github:

git clone https://github.com/<user>/<repository>

This might ask for credentials (if github repository is not 'public'.) Move to directory, and see what we've done:

cd <repository>
ls -a
git remote -v

(The 'ls' and 'git remote' commands are optional, they just show you stuff) Copy the 10000 files and millions of lines of code that you want to put in the repository:

cp -R <path>/src .
git status -s

(assuming everything you want is under a directory named "src".) (The second command again is optional and just shows you stuff)

Add all the files you just copied to git, and optionally admire the the results:

git add src
git status -s

Commit all the changes:

git commit -m "<commit comment>"

Push the changes

git push origin master

"Origin" is an alias for your github repository which was automatically set up by the "git clone" command. "master" is the branch you are pushing to. Go look at github in your browser and you should see all the files have been added.

Optionally remove the directory you did all this in, to reclaim disk space:

cd ..
rm -r <working>

Accessing clicked element in angularjs

While AngularJS allows you to get a hand on a click event (and thus a target of it) with the following syntax (note the $event argument to the setMaster function; documentation here: http://docs.angularjs.org/api/ng.directive:ngClick):

function AdminController($scope) {    
  $scope.setMaster = function(obj, $event){
    console.log($event.target);
  }
}

this is not very angular-way of solving this problem. With AngularJS the focus is on the model manipulation. One would mutate a model and let AngularJS figure out rendering.

The AngularJS-way of solving this problem (without using jQuery and without the need to pass the $event argument) would be:

<div ng-controller="AdminController">
    <ul class="list-holder">
        <li ng-repeat="section in sections" ng-class="{active : isSelected(section)}">
            <a ng-click="setMaster(section)">{{section.name}}</a>
        </li>
    </ul>
    <hr>
    {{selected | json}}
</div>

where methods in the controller would look like this:

$scope.setMaster = function(section) {
    $scope.selected = section;
}

$scope.isSelected = function(section) {
    return $scope.selected === section;
}

Here is the complete jsFiddle: http://jsfiddle.net/pkozlowski_opensource/WXJ3p/15/

Maximum size for a SQL Server Query? IN clause? Is there a Better Approach

Every SQL batch has to fit in the Batch Size Limit: 65,536 * Network Packet Size.

Other than that, your query is limited by runtime conditions. It will usually run out of stack size because x IN (a,b,c) is nothing but x=a OR x=b OR x=c which creates an expression tree similar to x=a OR (x=b OR (x=c)), so it gets very deep with a large number of OR. SQL 7 would hit a SO at about 10k values in the IN, but nowdays stacks are much deeper (because of x64), so it can go pretty deep.

Update

You already found Erland's article on the topic of passing lists/arrays to SQL Server. With SQL 2008 you also have Table Valued Parameters which allow you to pass an entire DataTable as a single table type parameter and join on it.

XML and XPath is another viable solution:

SELECT ...
FROM Table
JOIN (
   SELECT x.value(N'.',N'uniqueidentifier') as guid
   FROM @values.nodes(N'/guids/guid') t(x)) as guids
 ON Table.guid = guids.guid;

How to run a C# application at Windows startup?

An open source application called "Startup Creator" configures Windows Startup by creating a script while giving an easy to use interface. Utilizing powerful VBScript, it allows applications or services to start up at timed delay intervals, always in the same order. These scripts are automatically placed in your startup folder, and can be opened back up to allow modifications in the future.

http://startupcreator.codeplex.com/

How to reset sequence in postgres and fill id column with new data?

To retain order of the rows:

UPDATE thetable SET rowid=col_serial FROM 
(SELECT rowid, row_number() OVER ( ORDER BY lngid) AS col_serial FROM thetable ORDER BY lngid) AS t1 
WHERE thetable.rowid=t1.rowid;

How do I replace a character in a string in Java?

Try using String.replace() or String.replaceAll() instead.

String my_new_str = my_str.replace("&", "&amp;");

(Both replace all occurrences; replaceAll allows use of regex.)

How do I initialise all entries of a matrix with a specific value?

It is easy to assign repeated values to an array:

x(1:10) = 5;

If you want to generate the array of elements inline in a statement try something like this:

ones(1,10) * 5

or with repmat

repmat(5, 1, 10)

PowerShell: Comparing dates

I wanted to show how powerful it can be aside from just checking "-lt".

Example: I used it to calculate time differences take from Windows event view Application log:

Get the difference between the two date times:

PS> $Obj = ((get-date "10/22/2020 12:51:1") - (get-date "10/22/2020 12:20:1 "))

Object created:

PS> $Obj


Days              : 0
Hours             : 0
Minutes           : 31
Seconds           : 0
Milliseconds      : 0
Ticks             : 18600000000
TotalDays         : 0.0215277777777778
TotalHours        : 0.516666666666667
TotalMinutes      : 31
TotalSeconds      : 1860
TotalMilliseconds : 1860000

Access an item directly:

PS> $Obj.Minutes
31

How to return a part of an array in Ruby?

Ruby 2.6 Beginless/Endless Ranges

(..1)
# or
(...1)

(1..)
# or
(1...)

[1,2,3,4,5,6][..3]
=> [1, 2, 3, 4]

[1,2,3,4,5,6][...3]
 => [1, 2, 3]

ROLES = %w[superadmin manager admin contact user]
ROLES[ROLES.index('admin')..]
=> ["admin", "contact", "user"]

Java: object to byte[] and byte[] to object converter (for Tokyo Cabinet)

You can look at how Hector does this for Cassandra, where the goal is the same - convert everything to and from byte[] in order to store/retrieve from a NoSQL database - see here. For the primitive types (+String), there are special Serializers, otherwise there is the generic ObjectSerializer (expecting Serializable, and using ObjectOutputStream). You can, of course, use only it for everything, but there might be redundant meta-data in the serialized form.

I guess you can copy the entire package and make use of it.

How can I escape a double quote inside double quotes?

Use a backslash:

echo "\""     # Prints one " character.

How to play YouTube video in my Android application?

I didn't want to have to have the YouTube app present on the device so I used this tutorial:

http://www.viralandroid.com/2015/09/how-to-embed-youtube-video-in-android-webview.html

...to produce this code in my app:

WebView mWebView; 

@Override
public void onCreate(Bundle savedInstanceState) {
    setContentView(R.layout.video_webview);
    mWebView=(WebView)findViewById(R.id.videoview);

    //build your own src link with your video ID
    String videoStr = "<html><body>Promo video<br><iframe width=\"420\" height=\"315\" src=\"https://www.youtube.com/embed/47yJ2XCRLZs\" frameborder=\"0\" allowfullscreen></iframe></body></html>";

    mWebView.setWebViewClient(new WebViewClient() {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
                return false;
        }
    });
    WebSettings ws = mWebView.getSettings();
    ws.setJavaScriptEnabled(true);
    mWebView.loadData(videoStr, "text/html", "utf-8");

}

//video_webview
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_marginLeft="0dp"
    android:layout_marginRight="0dp"
    android:background="#000000"
    android:id="@+id/bmp_programme_ll"
    android:orientation="vertical" >

   <WebView
    android:id="@+id/videoview" 
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    />  
</LinearLayout>     

This worked just how I wanted it. It doesn't autoplay but the video streams within my app. Worth noting that some restricted videos won't play when embedded.

Spring MVC - How to return simple String as JSON in Rest Controller

In one project we addressed this using JSONObject (maven dependency info). We chose this because we preferred returning a simple String rather than a wrapper object. An internal helper class could easily be used instead if you don't want to add a new dependency.

Example Usage:

@RestController
public class TestController
{
    @RequestMapping("/getString")
    public String getString()
    {
        return JSONObject.quote("Hello World");
    }
}

How do I check whether a file exists without exceptions?

This is the simplest way to check if a file exists. Just because the file existed when you checked doesn't guarantee that it will be there when you need to open it.

import os
fname = "foo.txt"
if os.path.isfile(fname):
    print("file does exist at this time")
else:
    print("no such file exists at this time")

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

I wouldn't put it in the same <p>, since IMHO the two infos are semantically too different. If you must, I'd suggest this:

<p style="text-align:right">
 <span style="float:left">I'll be on the left</span>
 I'll be on the right
</p>

How to import popper.js?

I really don't understand why Javascript world trying to do thing more complicated. Why not just download and include in html? Trying to have something like Maven in Java? But we have to manually include it in html anyway? So, what is the point? Maybe someday I will understand but not now.

This is how I can get it

  • download & install NodeJs
  • run "npm install popper.js --save"
  • then I get this message

    [email protected] added 1 package in 1.215s

  • then where is "add package" ? very informative , right? I found it in my C:\Users\surasin\node_modules\popper.js\dist

Hope this help

Android file chooser

I used AndExplorer for this purpose and my solution is popup a dialog and then redirect on the market to install the misssing application:

My startCreation is trying to call external file/directory picker. If it is missing call show installResultMessage function.

private void startCreation(){
    Intent intent = new Intent();
    intent.setAction(Intent.ACTION_PICK);
    Uri startDir = Uri.fromFile(new File("/sdcard"));

    intent.setDataAndType(startDir,
            "vnd.android.cursor.dir/lysesoft.andexplorer.file");
    intent.putExtra("browser_filter_extension_whitelist", "*.csv");
    intent.putExtra("explorer_title", getText(R.string.andex_file_selection_title));
    intent.putExtra("browser_title_background_color",
            getText(R.string.browser_title_background_color));
    intent.putExtra("browser_title_foreground_color",
            getText(R.string.browser_title_foreground_color));
    intent.putExtra("browser_list_background_color",
            getText(R.string.browser_list_background_color));
    intent.putExtra("browser_list_fontscale", "120%");
    intent.putExtra("browser_list_layout", "2");

    try{
         ApplicationInfo info = getPackageManager()
                                 .getApplicationInfo("lysesoft.andexplorer", 0 );

            startActivityForResult(intent, PICK_REQUEST_CODE);
    } catch( PackageManager.NameNotFoundException e ){
        showInstallResultMessage(R.string.error_install_andexplorer);
    } catch (Exception e) {
        Log.w(TAG, e.getMessage());
    }
}

This methos is just pick up a dialog and if user wants install the external application from market

private void showInstallResultMessage(int msg_id) {
    AlertDialog dialog = new AlertDialog.Builder(this).create();
    dialog.setMessage(getText(msg_id));
    dialog.setButton(getText(R.string.button_ok),
            new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                    finish();
                }
            });
    dialog.setButton2(getText(R.string.button_install),
            new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                    Intent intent = new Intent(Intent.ACTION_VIEW);
                    intent.setData(Uri.parse("market://details?id=lysesoft.andexplorer"));
                    startActivity(intent);
                    finish();
                }
            });
    dialog.show();
}

SQL SELECT WHERE field contains words

This should ideally be done with the help of sql server full text search if using. However, if you can't get that working on your DB for some reason, here is a performance intensive solution :-

-- table to search in
CREATE TABLE dbo.myTable
    (
    myTableId int NOT NULL IDENTITY (1, 1),
    code varchar(200) NOT NULL, 
    description varchar(200) NOT NULL -- this column contains the values we are going to search in 
    )  ON [PRIMARY]
GO

-- function to split space separated search string into individual words
CREATE FUNCTION [dbo].[fnSplit] (@StringInput nvarchar(max),
@Delimiter nvarchar(1))
RETURNS @OutputTable TABLE (
  id nvarchar(1000)
)
AS
BEGIN
  DECLARE @String nvarchar(100);

  WHILE LEN(@StringInput) > 0
  BEGIN
    SET @String = LEFT(@StringInput, ISNULL(NULLIF(CHARINDEX(@Delimiter, @StringInput) - 1, -1),
    LEN(@StringInput)));
    SET @StringInput = SUBSTRING(@StringInput, ISNULL(NULLIF(CHARINDEX
    (
    @Delimiter, @StringInput
    ),
    0
    ), LEN
    (
    @StringInput)
    )
    + 1, LEN(@StringInput));

    INSERT INTO @OutputTable (id)
      VALUES (@String);
  END;

  RETURN;
END;
GO

-- this is the search script which can be optionally converted to a stored procedure /function


declare @search varchar(max) = 'infection upper acute genito'; -- enter your search string here
-- the searched string above should give rows containing the following
-- infection in upper side with acute genitointestinal tract
-- acute infection in upper teeth
-- acute genitointestinal pain

if (len(trim(@search)) = 0) -- if search string is empty, just return records ordered alphabetically
begin
 select 1 as Priority ,myTableid, code, Description from myTable order by Description 
 return;
end

declare @splitTable Table(
wordRank int Identity(1,1), -- individual words are assinged priority order (in order of occurence/position)
word varchar(200)
)
declare @nonWordTable Table( -- table to trim out auxiliary verbs, prepositions etc. from the search
id varchar(200)
)

insert into @nonWordTable values
('of'),
('with'),
('at'),
('in'),
('for'),
('on'),
('by'),
('like'),
('up'),
('off'),
('near'),
('is'),
('are'),
(','),
(':'),
(';')

insert into @splitTable
select id from dbo.fnSplit(@search,' '); -- this function gives you a table with rows containing all the space separated words of the search like in this e.g., the output will be -
--  id
-------------
-- infection
-- upper
-- acute
-- genito

delete s from @splitTable s join @nonWordTable n  on s.word = n.id; -- trimming out non-words here
declare @countOfSearchStrings int = (select count(word) from @splitTable);  -- count of space separated words for search
declare @highestPriority int = POWER(@countOfSearchStrings,3);

with plainMatches as
(
select myTableid, @highestPriority as Priority from myTable where Description like @search  -- exact matches have highest priority
union                                      
select myTableid, @highestPriority-1 as Priority from myTable where Description like  @search + '%'  -- then with something at the end
union                                      
select myTableid, @highestPriority-2 as Priority from myTable where Description like '%' + @search -- then with something at the beginning
union                                      
select myTableid, @highestPriority-3 as Priority from myTable where Description like '%' + @search + '%' -- then if the word falls somewhere in between
),
splitWordMatches as( -- give each searched word a rank based on its position in the searched string
                     -- and calculate its char index in the field to search
select myTable.myTableid, (@countOfSearchStrings - s.wordRank) as Priority, s.word,
wordIndex = CHARINDEX(s.word, myTable.Description)  from myTable join @splitTable s on myTable.Description like '%'+ s.word + '%'
-- and not exists(select myTableid from plainMatches p where p.myTableId = myTable.myTableId) -- need not look into myTables that have already been found in plainmatches as they are highest ranked
                                                                              -- this one takes a long time though, so commenting it, will have no impact on the result
),
matchingRowsWithAllWords as (
 select myTableid, count(myTableid) as myTableCount from splitWordMatches group by(myTableid) having count(myTableid) = @countOfSearchStrings
)
, -- trim off the CTE here if you don't care about the ordering of words to be considered for priority
wordIndexRatings as( -- reverse the char indexes retrived above so that words occuring earlier have higher weightage
                     -- and then normalize them to sequential values
select s.myTableid, Priority, word, ROW_NUMBER() over (partition by s.myTableid order by wordindex desc) as comparativeWordIndex 
from splitWordMatches s join matchingRowsWithAllWords m on s.myTableId = m.myTableId
)
,
wordIndexSequenceRatings as ( -- need to do this to ensure that if the same set of words from search string is found in two rows,
                              -- their sequence in the field value is taken into account for higher priority
    select w.myTableid, w.word, (w.Priority + w.comparativeWordIndex + coalesce(sequncedPriority ,0)) as Priority
    from wordIndexRatings w left join 
    (
     select w1.myTableid, w1.priority, w1.word, w1.comparativeWordIndex, count(w1.myTableid) as sequncedPriority
     from wordIndexRatings w1 join wordIndexRatings w2 on w1.myTableId = w2.myTableId and w1.Priority > w2.Priority and w1.comparativeWordIndex>w2.comparativeWordIndex
     group by w1.myTableid, w1.priority,w1.word, w1.comparativeWordIndex
    ) 
    sequencedPriority on w.myTableId = sequencedPriority.myTableId and w.Priority = sequencedPriority.Priority
),
prioritizedSplitWordMatches as ( -- this calculates the cumulative priority for a field value
select  w1.myTableId, sum(w1.Priority) as OverallPriority from wordIndexSequenceRatings w1 join wordIndexSequenceRatings w2 on w1.myTableId =  w2.myTableId 
where w1.word <> w2.word group by w1.myTableid 
),
completeSet as (
select myTableid, priority from plainMatches -- get plain matches which should be highest ranked
union
select myTableid, OverallPriority as priority from prioritizedSplitWordMatches -- get ranked split word matches (which are ordered based on word rank in search string and sequence)
),
maximizedCompleteSet as( -- set the priority of a field value = maximum priority for that field value
select myTableid, max(priority) as Priority  from completeSet group by myTableId
)
select priority, myTable.myTableid , code, Description from maximizedCompleteSet m join myTable  on m.myTableId = myTable.myTableId 
order by Priority desc, Description -- order by priority desc to get highest rated items on top
--offset 0 rows fetch next 50 rows only -- optional paging

What is the error "Every derived table must have its own alias" in MySQL?

Here's a different example that can't be rewritten without aliases ( can't GROUP BY DISTINCT).

Imagine a table called purchases that records purchases made by customers at stores, i.e. it's a many to many table and the software needs to know which customers have made purchases at more than one store:

SELECT DISTINCT customer_id, SUM(1)
  FROM ( SELECT DISTINCT customer_id, store_id FROM purchases)
  GROUP BY customer_id HAVING 1 < SUM(1);

..will break with the error Every derived table must have its own alias. To fix:

SELECT DISTINCT customer_id, SUM(1)
  FROM ( SELECT DISTINCT customer_id, store_id FROM purchases) AS custom
  GROUP BY customer_id HAVING 1 < SUM(1);

( Note the AS custom alias).

How to find the array index with a value?

You can use indexOf:

var imageList = [100,200,300,400,500];
var index = imageList.indexOf(200); // 1

You will get -1 if it cannot find a value in the array.

Moment.js with Vuejs

For moment.js at Vue 3

npm install moment --save

Then in any component

import moment from 'moment'

...

export default {
  created: function () {
    this.moment = moment;
  },

...

<div class="comment-line">
   {{moment(new Date()).format('DD.MM.YYYY [&nbsp;] HH:mm')}}
</div>

Convert integer into its character equivalent, where 0 => a, 1 => b, etc

Javascript's String.fromCharCode(code1, code2, ..., codeN) takes an infinite number of arguments and returns a string of letters whose corresponding ASCII values are code1, code2, ... codeN. Since 97 is 'a' in ASCII, we can adjust for your indexing by adding 97 to your index.

function indexToChar(i) {
  return String.fromCharCode(i+97); //97 in ASCII is 'a', so i=0 returns 'a', 
                                    // i=1 returns 'b', etc
}

What is the best way to delete a value from an array in Perl?

The best I found was a combination of "undef" and "grep":

foreach $index ( @list_of_indexes_to_be_skiped ) {
      undef($array[$index]);
}
@array = grep { defined($_) } @array;

That does the trick! Federico

How can I inspect element in chrome when right click is disabled?

CTRL+SHIFT+I brings up the developers tools.

How to fix docker: Got permission denied issue

We always forget about ACLs . See setfacl.


sudo setfacl -m user:$USER:rw /var/run/docker.sock

Where to find Application Loader app in Mac?

you can find it by going to xcode > open developer tool > application Loader

enter image description here

Copy filtered data to another sheet using VBA

Best way of doing it

Below code is to copy the visible data in DBExtract sheet, and paste it into duplicateRecords sheet, with only filtered values. Range selected by me is the maximum range that can be occupied by my data. You can change it as per your need.

  Sub selectVisibleRange()

    Dim DbExtract, DuplicateRecords As Worksheet
    Set DbExtract = ThisWorkbook.Sheets("Export Worksheet")
    Set DuplicateRecords = ThisWorkbook.Sheets("DuplicateRecords")

    DbExtract.Range("A1:BF9999").SpecialCells(xlCellTypeVisible).Copy
    DuplicateRecords.Cells(1, 1).PasteSpecial


    End Sub

How can I determine installed SQL Server instances and their versions?

If you are interested in determining this in a script, you can try the following:

sc \\server_name query | grep MSSQL

Note: grep is part of gnuwin32 tools

How to get the innerHTML of selectable jquery element?

$(function() {
        $("#select-image").selectable({
            selected: function( event, ui ) { 
                var $variable = $('.ui-selected').html(); 
                console.log($variable);
            }
        });
    });

or

$(function() {
        $("#select-image").selectable({
            selected: function( event, ui ) { 
                var $variable = $('.ui-selected').text(); 
                console.log($variable);
            }
        });
    });

or

$(function() {
        $("#select-image").selectable({
            selected: function( event, ui ) { 
                var $variable = $('.ui-selected').val(); 
                console.log($variable);
            }
        });
    });

Getting list of tables, and fields in each, in a database

in a Microsoft SQL Server you can use this:

declare @sql2 nvarchar(2000)
        set @sql2  ='
use ?
if (  db_name(db_id()) not in (''master'',''tempdb'',''model'',''msdb'',''SSISDB'')  )
begin   

select
    db_name() as db,
    SS.name as schemaname,
    SO.name tablename,
    SC.name columnname,
    ST.name type,
    case when ST.name in (''nvarchar'', ''nchar'')
        then convert(varchar(10), ( SC.max_length / 2 ))
        when ST.name in (''char'', ''varchar'')
        then convert(varchar(10), SC.max_length)
        else null
    end as length,
    case when SC.is_nullable = 0 then ''No'' when SC.is_nullable = 1 then ''Yes'' else null end as nullable,
    isnull(SC.column_id,0) as col_number
from sys.objects                  SO
join sys.schemas                  SS
    on SS.schema_id = SO.schema_id
join sys.columns             SC
on SO.object_id     = SC.object_id
left join sys.types               ST
    on SC.user_type_id = ST.user_type_id and SC.system_type_id = ST.system_type_id
    where SO.is_ms_shipped = 0 
end
'

exec sp_msforeachdb @command1 = @sql2

this shows you all tables and columns ( and their definition ) from all userdefined databases.

Calculating how many minutes there are between two times

You just need to query the TotalMinutes property like this varTime.TotalMinutes

Convert byte to string in Java

You have to construct a new string out of a byte array. The first element in your byteArray should be 0x63. If you want to add any more letters, make the byteArray longer and add them to the next indices.

byte[] byteArray = new byte[1];
byteArray[0] = 0x63;

try {
    System.out.println("string " + new String(byteArray, "US-ASCII"));
} catch (UnsupportedEncodingException e) {
    // TODO: Handle exception.
    e.printStackTrace();
}

Note that specifying the encoding will eventually throw an UnsupportedEncodingException and you must handle that accordingly.

How to read a file line-by-line into a list?

If you'd like to read a file from the command line or from stdin, you can also use the fileinput module:

# reader.py
import fileinput

content = []
for line in fileinput.input():
    content.append(line.strip())

fileinput.close()

Pass files to it like so:

$ python reader.py textfile.txt 

Read more here: http://docs.python.org/2/library/fileinput.html

If list index exists, do X

Oneliner:

do_X() if len(your_list) > your_index else do_something_else()  

Full example:

In [10]: def do_X(): 
    ...:     print(1) 
    ...:                                                                                                                                                                                                                                      

In [11]: def do_something_else(): 
    ...:     print(2) 
    ...:                                                                                                                                                                                                                                      

In [12]: your_index = 2                                                                                                                                                                                                                       

In [13]: your_list = [1,2,3]                                                                                                                                                                                                                  

In [14]: do_X() if len(your_list) > your_index else do_something_else()                                                                                                                                                                      
1

Just for info. Imho, try ... except IndexError is better solution.

Printing a char with printf

In C char gets promoted to int in expressions. That pretty much explains every question, if you think about it.

Source: The C Programming Language by Brian W.Kernighan and Dennis M.Ritchie

A must read if you want to learn C.

Also see this stack overflow page, where people much more experienced then me can explain it much better then I ever can.

How do I see what character set a MySQL database / table / column is?

For columns:

SHOW FULL COLUMNS FROM table_name;

jQuery: Test if checkbox is NOT checked

I used this and in worked for me!

$("checkbox selector").click(function() {
    if($(this).prop('checked')==true){
       do what you need!
    }
});

How to disable an input box using angular.js

Your markup should contain an additional attribute called ng-disabled whose value should be a condition or expression that would evaluate to be either true or false.

    <input data-ng-model="userInf.username"  class="span12 editEmail" 
       type="text"  placeholder="[email protected]"  
       pattern="[^@]+@[^@]+\.[a-zA-Z]{2,6}" 
       required 
       ng-disabled="{condition or expression}"
/>

And in the controller you may have some code that would affect the value of ng-disabled directive.

WMI "installed" query different from add/remove programs list?

I have been using Inno Setup for an installer. I'm using 64-bit Windows 7 only. I'm finding that registry entries are being written to

HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall

I haven't yet figured out how to get this list to be reported by WMI (although the program is listed as installed in Programs and Features). If I figure it out, I'll try to remember to report back here.

UPDATE:

Entries for 32-bit programs installed on a 64-bit machine go in that registry location. There's more written here:

http://mdb-blog.blogspot.com/2010/09/c-check-if-programapplication-is.html

See my comment that describes 32-bit vs 64-bit behavior in that same post here:

http://mdb-blog.blogspot.com/2010/09/c-check-if-programapplication-is.html?showComment=1300402090679#c861009270784046894

Unfortunately, there doesn't seem to be a way to get WMI to list all programs from the add/remove programs list (aka Programs and Features in Windows 7, not sure about Vista). My current code has dropped WMI in favor of using the registry. The code itself to interrogate the registry is even easier than using WMI. Sample code is in the above link.

Unable to compile class for JSP: The type java.util.Map$Entry cannot be resolved. It is indirectly referenced from required .class files

I recently get across the same issue. I was using IntelliJx64 with Tomcat7.0.32 with jdk.8.0.102. There was no issue then. I was able to directly access my deployment localhost:[port] without adding [mywebapp] or /ROOT.

When I tried to migrate to eclipse neon, I came across the same bug that is discussed when I tried to set the path as empty string. When I enforced execution environment to Java7 and set modules to empty it did not solve toe issue. However, when I changed my tomcat installation to 7.072 and manually changed context path configuration to path="" the problem was solved in eclipse. (You can manipulate the path via double click server and switching to module tab too.)

My wonder is how come IntelliJ was not giving any issues with the same bug which was supposed to be related to tomcat installation version?

There also seems to be a relation with the IDE in use.

Does Java have a path joining method?

Try:

String path1 = "path1";
String path2 = "path2";

String joinedPath = new File(path1, path2).toString();

App can't be opened because it is from an unidentified developer

It's because of the Security options.

Go to System Preferences... > Security & Privacy and there should be a button saying Open Anyway, under the General tab.

You can avoid doing this by changing the options under Allow apps downloaded from:, however I would recommend keeping it at the default Mac App Store and identified developers.

How can I do a line break (line continuation) in Python?

If you want to break your line because of a long literal string, you can break that string into pieces:

long_string = "a very long string"
print("a very long string")

will be replaced by

long_string = (
  "a "
  "very "
  "long "
  "string"
)
print(
  "a "
  "very "
  "long "
  "string"
)

Output for both print statements:

a very long string

Notice the parenthesis in the affectation.

Notice also that breaking literal strings into pieces allows to use the literal prefix only on parts of the string and mix the delimiters:

s = (
  '''2+2='''
  f"{2+2}"
)

Disable Rails SQL logging in console

Here's a variation I consider somewhat cleaner, that still allows potential other logging from AR. In config/environments/development.rb :

config.after_initialize do
  ActiveRecord::Base.logger = Rails.logger.clone
  ActiveRecord::Base.logger.level = Logger::INFO
end

Maximum packet size for a TCP connection

Generally, this will be dependent on the interface the connection is using. You can probably use an ioctl() to get the MTU, and if it is ethernet, you can usually get the maximum packet size by subtracting the size of the hardware header from that, which is 14 for ethernet with no VLAN.

This is only the case if the MTU is at least that large across the network. TCP may use path MTU discovery to reduce your effective MTU.

The question is, why do you care?

Check element exists in array

You may be able to use the built-in function dir() to produce similar behavior to PHP's isset(), something like:

if 'foo' in dir():  # returns False, foo is not defined yet.
    pass

foo = 'b'

if 'foo' in dir():  # returns True, foo is now defined and in scope.
   pass

dir() returns a list of the names in the current scope, more information can be found here: http://docs.python.org/library/functions.html#dir.

Laravel is there a way to add values to a request array

enough said on this subject but i couldn't resist to add my own answer. I believe the simplest approach is

request()->merge([ 'foo' => 'bar' ]);

JavaScript - Use variable in string match

xxx.match(yyy, 'g').length

How do I import the javax.servlet API in my Eclipse project?

Ensure you've the right Eclipse and Server

Ensure that you're using at least Eclipse IDE for Enterprise Java developers (with the Enterprise). It contains development tools to create dynamic web projects and easily integrate servletcontainers (those tools are part of Web Tools Platform, WTP). In case you already had Eclipse IDE for Java (without Enterprise), and manually installed some related plugins, then chances are that it wasn't done properly. You'd best trash it and grab the real Eclipse IDE for Enterprise Java one.

You also need to ensure that you already have a servletcontainer installed on your machine which implements at least the same Servlet API version as the servletcontainer in the production environment, for example Apache Tomcat, Oracle GlassFish, JBoss AS/WildFly, etc. Usually, just downloading the ZIP file and extracting it is sufficient. In case of Tomcat, do not download the EXE format, that's only for Windows based production environments. See also a.o. Several ports (8005, 8080, 8009) required by Tomcat Server at localhost are already in use.

A servletcontainer is a concrete implementation of the Servlet API. Note that the Java EE SDK download at Oracle.com basically contains GlassFish. So if you happen to already have downloaded Java EE SDK, then you basically already have GlassFish. Also note that for example GlassFish and JBoss AS/WildFly are more than just a servletcontainer, they also supports JSF, EJB, JPA and all other Java EE fanciness. See also a.o. What exactly is Java EE?


Integrate Server in Eclipse and associate it with Project

Once having installed both Eclipse for Enterprise Java and a servletcontainer on your machine, do the following steps in Eclipse:

  1. Integrate servletcontainer in Eclipse

    a. Via Servers view

    • Open the Servers view in the bottom box.

    • Rightclick there and choose New > Server.

    • Pick the appropriate servletcontainer make and version and walk through the wizard.

      enter image description here

    b. Or, via Eclipse preferences

    • Open Window > Preferences > Server > Runtime Environments.

    • You can Add, Edit and Remove servers here.

      enter image description here

  2. Associate server with project

    a. In new project

    • Open the Project Navigator/Explorer on the left hand side.

    • Rightclick there and choose New > Project and then in menu Web > Dynamic Web Project.

    • In the wizard, set the Target Runtime to the integrated server.

      enter image description here

    b. Or, in existing project

    • Rightclick project and choose Properties.

    • In Targeted Runtimes section, select the integrated server.

      enter image description here

    Either way, Eclipse will then automatically take the servletcontainer's libraries in the build path. This way you'll be able to import and use the Servlet API.


Never carry around loose server-specific JAR files

You should in any case not have the need to fiddle around in the Build Path property of the project. You should above all never manually copy/download/move/include the individual servletcontainer-specific libraries like servlet-api.jar, jsp-api.jar, el-api.jar, j2ee.jar, javaee.jar, etc. It would only lead to future portability, compatibility, classpath and maintainability troubles, because your webapp would not work when it's deployed to a servletcontainer of a different make/version than where those libraries are originally obtained from.

In case you're using Maven, you need to make absolutely sure that servletcontainer-specific libraries which are already provided by the target runtime are marked as <scope>provided</scope>.

Here are some typical exceptions which you can get when you litter the /WEB-INF/lib or even /JRE/lib, /JRE/lib/ext, etc with servletcontainer-specific libraries in a careless attempt to fix the compilation errors:

libaio.so.1: cannot open shared object file

It looks like a 32/64 bit mismatch. The ldd output shows that mainly libraries from /lib64 are chosen. That would indicate that you have installed a 64 bit version of the Oracle client and have created a 64 bit executable. But libaio.so is probably a 32 bit library and cannot be used for your application.

So you either need a 64 bit version of libaio or you create a 32 bit version of your application.

Pytorch tensor to numpy array

There are 4 dimensions of the tensor you want to convert.

[:, ::-1, :, :] 

: means that the first dimension should be copied as it is and converted, same goes for the third and fourth dimension.

::-1 means that for the second axes it reverses the the axes

Error 'LINK : fatal error LNK1123: failure during conversion to COFF: file invalid or corrupt' after installing Visual Studio 2012 Release Preview

I solved this by doing the following:

  1. In a command prompt, type msconfig and press enter.
  2. Click services tab.
  3. Look for "Application Experience" and put tick mark (that is, select this to enable).
  4. Click OK. And restart if necessary.

Thus the problem will go forever. Do build randomly and debug your C++ projects without any disturbance.

Find out whether radio button is checked with JQuery?

The solution will be simple, As you just need 'listeners' when a certain radio button is checked. Do it :-

if($('#yourRadioButtonId').is(':checked')){ 
// Do your listener's stuff here. 
}

How to import a csv file using python with headers intact, where first column is a non-numerical

You can use pandas library and reference the rows and columns like this:

import pandas as pd

input = pd.read_csv("path_to_file");

#for accessing ith row:
input.iloc[i]

#for accessing column named X
input.X

#for accessing ith row and column named X
input.iloc[i].X

javascript - pass selected value from popup window to parent window input box

From your code

<input type=button value="Select" onClick="sendValue(this.form.details);"

Im not sure that your this.form.details valid or not.

IF it's valid, have a look in window.opener.document.getElementById('details').value = selvalue;

I can't found an input's id contain details I'm just found only id=sku1 (recommend you to add " like id="sku1").

And from your id it's hardcode. Let's see how to do with dynamic when a child has callback to update some textbox on the parent Take a look at here.

First page.

<html>
<head>
<script>
    function callFromDialog(id,data){ //for callback from the dialog
        document.getElementById(id).value = data;
        // do some thing other if you want
    }

    function choose(id){
        var URL = "secondPage.html?id=" + id + "&dummy=avoid#";
        window.open(URL,"mywindow","menubar=1,resizable=1,width=350,height=250")
    }
</script>
</head>
<body>
<input id="tbFirst" type="text" /> <button onclick="choose('tbFirst')">choose</button>
<input id="tbSecond" type="text" /> <button onclick="choose('tbSecond')">choose</button>
</body>
</html>

Look in function choose I'm sent an id of textbox to the popup window (don't forget to add dummy data at last of URL param like &dummy=avoid#)

Popup Page

<html>
<head>
<script>
    function goSelect(data){
        var idFromCallPage = getUrlVars()["id"];
        window.opener.callFromDialog(idFromCallPage,data); //or use //window.opener.document.getElementById(idFromCallPage).value = data;
        window.close();
    }


    function getUrlVars(){
        var vars = [], hash;
        var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
        for(var i = 0; i < hashes.length; i++)
        {
            hash = hashes[i].split('=');
            vars.push(hash[0]);
            vars[hash[0]] = hash[1];
        }
        return vars;
    }
</script>
</head>
<body>
<a href="#" onclick="goSelect('Car')">Car</a> <br />
<a href="#" onclick="goSelect('Food')">Food</a> <br />
</body>
</html>

I have add function getUrlVars for get URL param that the parent has pass to child.

Okay, when select data in the popup, for this case it's will call function goSelect

In that function will get URL param to sent back.

And when you need to sent back to the parent just use window.opener and the name of function like window.opener.callFromDialog

By fully is window.opener.callFromDialog(idFromCallPage,data);

Or if you want to use window.opener.document.getElementById(idFromCallPage).value = data; It's ok too.

Is recursion ever faster than looping?

This is a guess. Generally recursion probably doesn't beat looping often or ever on problems of decent size if both are using really good algorithms(not counting implementation difficulty) , it may be different if used with a language w/ tail call recursion(and a tail recursive algorithm and with loops also as part of the language)-which would probably have very similar and possibly even prefer recursion some of the time.

Construct pandas DataFrame from items in nested dictionary

pd.concat accepts a dictionary. With this in mind, it is possible to improve upon the currently accepted answer in terms of simplicity and performance by use a dictionary comprehension to build a dictionary mapping keys to sub-frames.

pd.concat({k: pd.DataFrame(v).T for k, v in user_dict.items()}, axis=0)

Or,

pd.concat({
        k: pd.DataFrame.from_dict(v, 'index') for k, v in user_dict.items()
    }, 
    axis=0)

              att_1     att_2
12 Category 1     1  whatever
   Category 2    23   another
15 Category 1    10       foo
   Category 2    30       bar

How to use performSelector:withObject:afterDelay: with primitive types in Cocoa?

I find that the quickest (but somewhat dirty) way to do this is by invoking objc_msgSend directly. However, it's dangerous to invoke it directly because you need to read the documentation and make sure that you're using the correct variant for the type of return value and because objc_msgSend is defined as vararg for compiler convenience but is actually implemented as fast assembly glue. Here's some code used to call a delegate method -[delegate integerDidChange:] that takes a single integer argument.

#import <objc/message.h>


SEL theSelector = @selector(integerDidChange:);
if ([self.delegate respondsToSelector:theSelector])
{
    typedef void (*IntegerDidChangeFuncPtrType)(id, SEL, NSInteger);
    IntegerDidChangeFuncPtrType MyFunction = (IntegerDidChangeFuncPtrType)objc_msgSend;
    MyFunction(self.delegate, theSelector, theIntegerThatChanged);
}

This first saves the selector since we're going to refer to it multiple times and it would be easy to create a typo. It then verifies that the delegate actually responds to the selector - it might be an optional protocol. It then creates a function pointer type that specifies the actual signature of the selector. Keep in mind that all Objective-C messages have two hidden first arguments, the object being messaged and the selector being sent. Then we create a function pointer of the appropriate type and set it to point to the underlying objc_msgSend function. Keep in mind that if the return value is a float or struct, you need to use a different variant of objc_msgSend. Finally, send the message using the same machinery that Objective-C uses under the sheets.

TypeError: 'NoneType' object is not iterable in Python

It means that the data variable is passing None (which is type NoneType), its equivalent for nothing. So it can't be iterable as a list, as you are trying to do.

Exit Shell Script Based on Process Exit Code

If you just call exit in Bash without any parameters, it will return the exit code of the last command. Combined with OR, Bash should only invoke exit, if the previous command fails. But I haven't tested this.

command1 || exit;
command2 || exit;

Bash will also store the exit code of the last command in the variable $?.

Coarse-grained vs fine-grained

One more way to understand would be to think in terms of communication between processes and threads. Processes communicate with the help of coarse grained communication mechanisms like sockets, signal handlers, shared memory, semaphores and files. Threads, on the other hand, have access to shared memory space that belongs to a process, which allows them to apply finer grain communication mechanisms.

Source: Java concurrency in practice

The definitive guide to form-based website authentication

When hashing, don't use fast hash algorithms such as MD5 (many hardware implementations exist). Use something like SHA-512. For passwords, slower hashes are better.

The faster you can create hashes, the faster any brute force checker can work. Slower hashes will therefore slow down brute forcing. A slow hash algorithm will make brute forcing impractical for longer passwords (8 digits +)

How to move files from one git repo to another (not a clone), preserving history

If the paths for the files in question are the same in the two repos and you're wanting to bring over just one file or a small set of related files, one easy way to do this is to use git cherry-pick.

The first step is to bring the commits from the other repo into your own local repo using git fetch <remote-url>. This will leave FETCH_HEAD pointing to the head commit from the other repo; if you want to preserve a reference to that commit after you've done other fetches you may want to tag it with git tag other-head FETCH_HEAD.

You will then need to create an initial commit for that file (if it doesn't exist) or a commit to bring the file to a state that can be patched with the first commit from the other repo you want to bring in. You may be able to do this with a git cherry-pick <commit-0> if commit-0 introduced the files you want, or you may need to construct the commit 'by hand'. Add -n to the cherry-pick options if you need to modify the initial commit to, e.g., drop files from that commit you don't want to bring in.

After that, you can continue to git cherry-pick subsequent commits, again using -n where necessary. In the simplest case (all commits are exactly what you want and apply cleanly) you can give the full list of commits on the cherry-pick command line: git cherry-pick <commit-1> <commit-2> <commit-3> ....

How to default to other directory instead of home directory

Just write that line to a file "cd.sh", then do this from your shell prompt:

. ./cd.sh

Or you can create an alias or function in your $HOME/.bashrc file:

foo() { cd /d/work_space_for_my_company/project/code_source ; }

If the directory name includes spaces or other shell metacharacters, you'll need quotation marks; it won't hurt to add them even if they're not necessary:

foo() { cd "/d/Work Space/project/code_source" ; }

(Note that I've omitted the ../../..; you don't need it.)

EDIT: If you add a line

foo

to your .bashrc after the function definition, your shell will start in that directory. Or you can just use the cd command directly in your .bashrc if you aren't going to need to use the function later.

(The name foo is just an example; you should pick a more meaningful name.)

How can I count the number of children?

Try to get using:

var count = $("ul > li").size();
alert(count);

Where can I download english dictionary database in a text format?

user1247808 has a good link with: wget -c

http://www.androidtech.com/downloads/wordnet20-from-prolog-all-3.zip

If that isn't enough words for you:

http://dumps.wikimedia.org/enwiktionary/latest/enwiktionary-latest-all-titles-in-ns0.gz (updated url from Michael Kropat's suggestion)

Although that file name changes, you'll want to find the latest ... that turns out just to be a big (very big) text file.

http://dumps.wikimedia.org/enwiktionary/

C# Convert a Base64 -> byte[]

You're looking for the FromBase64Transform class, used with the CryptoStream class.

If you have a string, you can also call Convert.FromBase64String.

npm not working - "read ECONNRESET"

This can be caused by installing anything with npm using sudo -- this causes the files in the cache to be owned by root, resulting in this problem. You can fix it by running:

sudo rm -rf ~/.npm

to remove the cache. Then try whatever you were doing again, making sure you never use sudo along with npm (or the problem may come back).

Lots more information: npm throws error without sudo

Read Session Id using Javascript

Here's a short and sweet JavaScript function to fetch the session ID:

function session_id() {
    return /SESS\w*ID=([^;]+)/i.test(document.cookie) ? RegExp.$1 : false;
}

Or if you prefer a variable, here's a simple one-liner:

var session_id = /SESS\w*ID=([^;]+)/i.test(document.cookie) ? RegExp.$1 : false;

Should match the session ID cookie for PHP, JSP, .NET, and I suppose various other server-side processors as well.

Android: I am unable to have ViewPager WRAP_CONTENT

Using Daniel López Localle answer, I created this class in Kotlin. Hope it save you more time

class DynamicHeightViewPager @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null) : ViewPager(context, attrs) {

override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
    var heightMeasureSpec = heightMeasureSpec

    var height = 0
    for (i in 0 until childCount) {
        val child = getChildAt(i)
        child.measure(widthMeasureSpec, View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED))
        val h = child.measuredHeight
        if (h > height) height = h
    }

    if (height != 0) {
        heightMeasureSpec = View.MeasureSpec.makeMeasureSpec(height, View.MeasureSpec.EXACTLY)
    }

    super.onMeasure(widthMeasureSpec, heightMeasureSpec)
}}

How to use a variable for the database name in T-SQL?

Unfortunately you can't declare database names with a variable in that format.

For what you're trying to accomplish, you're going to need to wrap your statements within an EXEC() statement. So you'd have something like:

DECLARE @Sql varchar(max) ='CREATE DATABASE ' + @DBNAME

Then call

EXECUTE(@Sql) or sp_executesql(@Sql)

to execute the sql string.

Android: android.content.res.Resources$NotFoundException: String resource ID #0x5

Just wanted to point out another reason this error can be thrown is if you defined a string resource for one translation of your app but did not provide a default string resource.

Example of the Issue:

As you can see below, I had a string resource for a Spanish string "get_started". It can still be referenced in code, but if the phone is not in Spanish it will have no resource to load and crash when calling getString().

values-es/strings.xml

<string name="get_started">SIGUIENTE</string>

Reference to resource

textView.setText(getString(R.string.get_started)

Logcat:

06-11 11:46:37.835    7007-7007/? E/AndroidRuntime? FATAL EXCEPTION: main
Process: com.app.test PID: 7007
android.content.res.Resources$NotFoundException: String resource ID #0x7f0700fd
        at android.content.res.Resources.getText(Resources.java:299)
        at android.content.res.Resources.getString(Resources.java:385)
        at com.juvomobileinc.tigousa.ui.signin.SignInFragment$4.onClick(SignInFragment.java:188)
        at android.view.View.performClick(View.java:4780)
        at android.view.View$PerformClick.run(View.java:19866)
        at android.os.Handler.handleCallback(Handler.java:739)
        at android.os.Handler.dispatchMessage(Handler.java:95)
        at android.os.Looper.loop(Looper.java:135)
        at android.app.ActivityThread.main(ActivityThread.java:5254)
        at java.lang.reflect.Method.invoke(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:372)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)

Solution to the Issue

Preventing this is quite simple, just make sure that you always have a default string resource in values/strings.xml so that if the phone is in another language it will always have a resource to fall back to.

values/strings.xml

<string name="get_started">Get Started</string>

values-en/strings.xml

<string name="get_started">Get Started</string>

values-es/strings.xml

<string name="get_started">Siguiente</string>

values-de/strings.xml

<string name="get_started">Ioslegen</string>

How to get a file directory path from file path?

dirname and basename are the tools you're looking for for extracting path components:

$ export VAR='/home/pax/file.c'
$ echo "$(dirname "${VAR}")" ; echo "$(basename "${VAR}")"
/home/pax
file.c

They're not internal Bash commands but they're part of the POSIX standard - see dirname and basename. Hence, they're probably available on, or can be obtained for, most platforms that are capable of running bash.

How to import Maven dependency in Android Studio/IntelliJ?

  1. Uncheck "Offline work" in File>Settings>Gradle>Global Gradle Settings
  2. Resync the project, for example by restarting the Android Studio
  3. Once synced, you can check the option again to work offline.

Priority queue in .Net

A Simple Max Heap Implementation.

https://github.com/bharathkumarms/AlgorithmsMadeEasy/blob/master/AlgorithmsMadeEasy/MaxHeap.cs

using System;
using System.Collections.Generic;
using System.Linq;

namespace AlgorithmsMadeEasy
{
    class MaxHeap
    {
        private static int capacity = 10;
        private int size = 0;
        int[] items = new int[capacity];

        private int getLeftChildIndex(int parentIndex) { return 2 * parentIndex + 1; }
        private int getRightChildIndex(int parentIndex) { return 2 * parentIndex + 2; }
        private int getParentIndex(int childIndex) { return (childIndex - 1) / 2; }

        private int getLeftChild(int parentIndex) { return this.items[getLeftChildIndex(parentIndex)]; }
        private int getRightChild(int parentIndex) { return this.items[getRightChildIndex(parentIndex)]; }
        private int getParent(int childIndex) { return this.items[getParentIndex(childIndex)]; }

        private bool hasLeftChild(int parentIndex) { return getLeftChildIndex(parentIndex) < size; }
        private bool hasRightChild(int parentIndex) { return getRightChildIndex(parentIndex) < size; }
        private bool hasParent(int childIndex) { return getLeftChildIndex(childIndex) > 0; }

        private void swap(int indexOne, int indexTwo)
        {
            int temp = this.items[indexOne];
            this.items[indexOne] = this.items[indexTwo];
            this.items[indexTwo] = temp;
        }

        private void hasEnoughCapacity()
        {
            if (this.size == capacity)
            {
                Array.Resize(ref this.items,capacity*2);
                capacity *= 2;
            }
        }

        public void Add(int item)
        {
            this.hasEnoughCapacity();
            this.items[size] = item;
            this.size++;
            heapifyUp();
        }

        public int Remove()
        {
            int item = this.items[0];
            this.items[0] = this.items[size-1];
            this.items[this.size - 1] = 0;
            size--;
            heapifyDown();
            return item;
        }

        private void heapifyUp()
        {
            int index = this.size - 1;
            while (hasParent(index) && this.items[index] > getParent(index))
            {
                swap(index, getParentIndex(index));
                index = getParentIndex(index);
            }
        }

        private void heapifyDown()
        {
            int index = 0;
            while (hasLeftChild(index))
            {
                int bigChildIndex = getLeftChildIndex(index);
                if (hasRightChild(index) && getLeftChild(index) < getRightChild(index))
                {
                    bigChildIndex = getRightChildIndex(index);
                }

                if (this.items[bigChildIndex] < this.items[index])
                {
                    break;
                }
                else
                {
                    swap(bigChildIndex,index);
                    index = bigChildIndex;
                }
            }
        }
    }
}

/*
Calling Code:
    MaxHeap mh = new MaxHeap();
    mh.Add(10);
    mh.Add(5);
    mh.Add(2);
    mh.Add(1);
    mh.Add(50);
    int maxVal  = mh.Remove();
    int newMaxVal = mh.Remove();
*/

How can I clear event subscriptions in C#?

Conceptual extended boring comment.

I rather use the word "event handler" instead of "event" or "delegate". And used the word "event" for other stuff. In some programming languages (VB.NET, Object Pascal, Objective-C), "event" is called a "message" or "signal", and even have a "message" keyword, and specific sugar syntax.

const
  WM_Paint = 998;  // <-- "question" can be done by several talkers
  WM_Clear = 546;

type
  MyWindowClass = class(Window)
    procedure NotEventHandlerMethod_1;
    procedure NotEventHandlerMethod_17;

    procedure DoPaintEventHandler; message WM_Paint; // <-- "answer" by this listener
    procedure DoClearEventHandler; message WM_Clear;
  end;

And, in order to respond to that "message", a "event handler" respond, whether is a single delegate or multiple delegates.

Summary: "Event" is the "question", "event handler (s)" are the answer (s).

Update MongoDB field using value of another field

You should iterate through. For your specific case:

db.person.find().snapshot().forEach(
    function (elem) {
        db.person.update(
            {
                _id: elem._id
            },
            {
                $set: {
                    name: elem.firstname + ' ' + elem.lastname
                }
            }
        );
    }
);

Where does Vagrant download its .box files to?

The actual .box file is deleted by Vagrant once the download and box installation is complete. As mentioned in other answers, whilst downloading, the .box file is stored as:

~/.vagrant.d/tmp/boxXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

where the file name is 'box' followed by a 40 byte hexadecimal hash. A temporary file on my system for example, is:

~/.vagrant.d/tmp/boxc74a85fe4af3197a744851517c6af4d4959db77f

As far as I can tell, this file is never saved with a *.box extension, which explains why the searches above failed to locate it. There are two ways to retrieve the actual box file:

  1. Download the .box file from vagrantcloud.com

    1. Find the box you're interested in on the atlas. For example, https://atlas.hashicorp.com/ubuntu/boxes/trusty64/versions/20150530.0.1
    2. Replace the domain name with vagrantcloud.com. So https://atlas.hashicorp.com/ubuntu/boxes/trusty64/versions/20150530.0.1 becomes https://vagrantcloud.com/ubuntu/boxes/trusty64/versions/20150530.0.1/providers/virtualbox.box.
    3. Add /providers/virtualbox.box to the end of that URL. So https://vagrantcloud.com/ubuntu/boxes/trusty64/versions/20150530.0.1 becomes https://vagrantcloud.com/ubuntu/boxes/trusty64/versions/20150530.0.1/providers/virtualbox.box
    4. Save the .box file
    5. Use the .box as you wish, for example, hosting it yourself and pointing config.vm.box_url to the URL. OR
  2. Get the .box directly from Vagrant

    This requires you to modify the ruby source to prevent Vagrant from deleting the box after successful download.

    1. Locate the box_add.rb file in your Vagrant installation directory. On my system it's located at /Applications/Vagrant/embedded/gems/gems/vagrant-1.5.2/lib/vagrant/action/builtin/box_add.rb
    2. Find the box_add function. Within the box_add function, there is a block that reads:

      ensure # Make sure we delete the temporary file after we add it, # unless we were interrupted, in which case we keep it around # so we can resume the download later. if !@download_interrupted @logger.debug("Deleting temporary box: #{box_url}") begin box_url.delete if box_url rescue Errno::ENOENT # Not a big deal, the temp file may not actually exist end end

    3. Comment this block out.
    4. Add another box using vagrant add box <boxname>.
    5. Wait for it to download. You can watch it save in the ~/.vagrant.d/tmp/ directory as a boxXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX file.
    6. Rename the the file to something more useful. Eg, mv boxXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX trusty64.box.

Why would you want this?

For me, this has been useful to retrieve the .box file so it can be hosted on local, fast infrastructure as opposed to downloading from HashiCorp's Atlas box catalog or another box provider.

This really should be part of the default Vagrant functionality as it has a very definitive use case.

Show history of a file?

You can use git log to display the diffs while searching:

git log -p -- path/to/file

How to convert a GUID to a string in C#?

In Visual Basic, you can call a parameterless method without the braces (()). In C#, they're mandatory. So you should write:

String guid = System.Guid.NewGuid().ToString();

Without the braces, you're assigning the method itself (instead of its result) to the variable guid, and obviously the method cannot be converted to a String, hence the error.

Mongoose: CastError: Cast to ObjectId failed for value "[object Object]" at path "_id"

For the record: I had this error trying to fill a subdocument in a wrong way:

{
[CastError: Cast to ObjectId failed for value "[object Object]" at path "_id"]
message: 'Cast to ObjectId failed for value "[object Object]" at path "_id"',
name: 'CastError',
type: 'ObjectId',
path: '_id'
value:
  [ { timestamp: '2014-07-03T00:23:45-04:00',
  date_start: '2014-07-03T00:23:45-04:00',
  date_end: '2014-07-03T00:23:45-04:00',
  operation: 'Deactivation' } ],
}

look ^ value is an array containing an object: wrong!

Explanation: I was sending data from php to a node.js API in this way:

$history = json_encode(
array(
  array(
  'timestamp'  => date('c', time()),
  'date_start' => date('c', time()),
  'date_end'   => date('c', time()),
  'operation'  => 'Deactivation'
)));

As you can see $history is an array containing an array. That's why mongoose try to fill _id (or any other field) with an array instead than a Scheme.ObjectId (or any other data type). The following works:

$history = json_encode(
array(
  'timestamp'  => date('c', time()),
  'date_start' => date('c', time()),
  'date_end'   => date('c', time()),
  'operation'  => 'Deactivation'
));

Correct way to write loops for promise.

Given

  • asyncFn function
  • array of items

Required

  • promise chaining .then()'s in series (in order)
  • native es6

Solution

let asyncFn = (item) => {
  return new Promise((resolve, reject) => {
    setTimeout( () => {console.log(item); resolve(true)}, 1000 )
  })
}

// asyncFn('a')
// .then(()=>{return async('b')})
// .then(()=>{return async('c')})
// .then(()=>{return async('d')})

let a = ['a','b','c','d']

a.reduce((previous, current, index, array) => {
  return previous                                    // initiates the promise chain
  .then(()=>{return asyncFn(array[index])})      //adds .then() promise for each item
}, Promise.resolve())

How to get the width of a react element

A good practice is listening for resize events to prevent resize on render or even a user window resize that can bug your application.

const MyComponent = ()=> {
  const myRef = useRef(null)

  const [myComponenetWidth, setMyComponentWidth] = useState('')

  const handleResize = ()=>{ 
    setMyComponentWidth(myRef.current.offsetWidth)
  }

  useEffect(() =>{
    if(myRef.current)
      myRef.current.addEventListener('resize', handleResize)

    return ()=> {
     myRef.current.removeEventListener('resize', handleResize)
    }
  }, [myRef])

  return (
  <div ref={MyRef}>Hello</div>
  )
}

How to convert a Java object (bean) to key-value pairs (and vice versa)?

If you really really want performance you can go the code generation route.

You can do this on your on by doing your own reflection and building a mixin AspectJ ITD.

Or you can use Spring Roo and make a Spring Roo Addon. Your Roo addon will do something similar to the above but will be available to everyone who uses Spring Roo and you don't have to use Runtime Annotations.

I have done both. People crap on Spring Roo but it really is the most comprehensive code generation for Java.

How to count the number of words in a sentence, ignoring numbers, punctuation and whitespace?

str.split() without any arguments splits on runs of whitespace characters:

>>> s = 'I am having a very nice day.'
>>> 
>>> len(s.split())
7

From the linked documentation:

If sep is not specified or is None, a different splitting algorithm is applied: runs of consecutive whitespace are regarded as a single separator, and the result will contain no empty strings at the start or end if the string has leading or trailing whitespace.

Pandas: Looking up the list of sheets in an excel file

from openpyxl import load_workbook

sheets = load_workbook(excel_file, read_only=True).sheetnames

For a 5MB Excel file I'm working with, load_workbook without the read_only flag took 8.24s. With the read_only flag it only took 39.6 ms. If you still want to use an Excel library and not drop to an xml solution, that's much faster than the methods that parse the whole file.

Pandas aggregate count distinct

How about either of:

>>> df
         date  duration user_id
0  2013-04-01        30    0001
1  2013-04-01        15    0001
2  2013-04-01        20    0002
3  2013-04-02        15    0002
4  2013-04-02        30    0002
>>> df.groupby("date").agg({"duration": np.sum, "user_id": pd.Series.nunique})
            duration  user_id
date                         
2013-04-01        65        2
2013-04-02        45        1
>>> df.groupby("date").agg({"duration": np.sum, "user_id": lambda x: x.nunique()})
            duration  user_id
date                         
2013-04-01        65        2
2013-04-02        45        1

How to delete SQLite database from Android programmatically

Also from Eclipse you can use DDMS which makes it really easy.

Just make sure your emulator is running, and then switch to DDMS perspective in Eclipse. You'll have full access to the File Explorer which will allow you to go in and easily delete the entire database.

Nesting await in Parallel.ForEach

After introducing a bunch of helper methods, you will be able run parallel queries with this simple syntax:

const int DegreeOfParallelism = 10;
IEnumerable<double> result = await Enumerable.Range(0, 1000000)
    .Split(DegreeOfParallelism)
    .SelectManyAsync(async i => await CalculateAsync(i).ConfigureAwait(false))
    .ConfigureAwait(false);

What happens here is: we split source collection into 10 chunks (.Split(DegreeOfParallelism)), then run 10 tasks each processing its items one by one (.SelectManyAsync(...)) and merge those back into a single list.

Worth mentioning there is a simpler approach:

double[] result2 = await Enumerable.Range(0, 1000000)
    .Select(async i => await CalculateAsync(i).ConfigureAwait(false))
    .WhenAll()
    .ConfigureAwait(false);

But it needs a precaution: if you have a source collection that is too big, it will schedule a Task for every item right away, which may cause significant performance hits.

Extension methods used in examples above look as follows:

public static class CollectionExtensions
{
    /// <summary>
    /// Splits collection into number of collections of nearly equal size.
    /// </summary>
    public static IEnumerable<List<T>> Split<T>(this IEnumerable<T> src, int slicesCount)
    {
        if (slicesCount <= 0) throw new ArgumentOutOfRangeException(nameof(slicesCount));

        List<T> source = src.ToList();
        var sourceIndex = 0;
        for (var targetIndex = 0; targetIndex < slicesCount; targetIndex++)
        {
            var list = new List<T>();
            int itemsLeft = source.Count - targetIndex;
            while (slicesCount * list.Count < itemsLeft)
            {
                list.Add(source[sourceIndex++]);
            }

            yield return list;
        }
    }

    /// <summary>
    /// Takes collection of collections, projects those in parallel and merges results.
    /// </summary>
    public static async Task<IEnumerable<TResult>> SelectManyAsync<T, TResult>(
        this IEnumerable<IEnumerable<T>> source,
        Func<T, Task<TResult>> func)
    {
        List<TResult>[] slices = await source
            .Select(async slice => await slice.SelectListAsync(func).ConfigureAwait(false))
            .WhenAll()
            .ConfigureAwait(false);
        return slices.SelectMany(s => s);
    }

    /// <summary>Runs selector and awaits results.</summary>
    public static async Task<List<TResult>> SelectListAsync<TSource, TResult>(this IEnumerable<TSource> source, Func<TSource, Task<TResult>> selector)
    {
        List<TResult> result = new List<TResult>();
        foreach (TSource source1 in source)
        {
            TResult result1 = await selector(source1).ConfigureAwait(false);
            result.Add(result1);
        }
        return result;
    }

    /// <summary>Wraps tasks with Task.WhenAll.</summary>
    public static Task<TResult[]> WhenAll<TResult>(this IEnumerable<Task<TResult>> source)
    {
        return Task.WhenAll<TResult>(source);
    }
}

jQuery - Follow the cursor with a DIV

This works for me. Has a nice delayed action going on.

var $mouseX = 0, $mouseY = 0;
var $xp = 0, $yp =0;

$(document).mousemove(function(e){
    $mouseX = e.pageX;
    $mouseY = e.pageY;    
});

var $loop = setInterval(function(){
// change 12 to alter damping higher is slower
$xp += (($mouseX - $xp)/12);
$yp += (($mouseY - $yp)/12);
$("#moving_div").css({left:$xp +'px', top:$yp +'px'});  
}, 30);

Nice and simples

Search for exact match of string in excel row using VBA Macro

Try this:

Sub GetColumns()

Dim lnRow As Long, lnCol As Long

lnRow = 3 'For testing

lnCol = Sheet1.Cells(lnRow, 1).EntireRow.Find(What:="sds", LookIn:=xlValues, LookAt:=xlPart, SearchOrder:=xlByColumns, SearchDirection:=xlNext, MatchCase:=False).Column

End Sub

Probably best not to use colIndex and rowIndex as variable names as they are already mentioned in the Excel Object Library.

What are the special dollar sign shell variables?

  • $_ last argument of last command
  • $# number of arguments passed to current script
  • $* / $@ list of arguments passed to script as string / delimited list

off the top of my head. Google for bash special variables.

Value Change Listener to JTextField

DocumentFilter ? It gives you the ability to manipulate.

[ http://www.java2s.com/Tutorial/Java/0240__Swing/FormatJTextFieldstexttouppercase.htm ]

Sorry. J am using Jython (Python in Java) - but easy to understand

# python style
# upper chars [ text.upper() ]

class myComboBoxEditorDocumentFilter( DocumentFilter ):
def __init__(self,jtext):
    self._jtext = jtext

def insertString(self,FilterBypass_fb, offset, text, AttributeSet_attrs):
    txt = self._jtext.getText()
    print('DocumentFilter-insertString:',offset,text,'old:',txt)
    FilterBypass_fb.insertString(offset, text.upper(), AttributeSet_attrs)

def replace(self,FilterBypass_fb, offset, length, text, AttributeSet_attrs):
    txt = self._jtext.getText()
    print('DocumentFilter-replace:',offset, length, text,'old:',txt)
    FilterBypass_fb.replace(offset, length, text.upper(), AttributeSet_attrs)

def remove(self,FilterBypass_fb, offset, length):
    txt = self._jtext.getText()
    print('DocumentFilter-remove:',offset, length, 'old:',txt)
    FilterBypass_fb.remove(offset, length)

// (java style ~example for ComboBox-jTextField)
cb = new ComboBox();
cb.setEditable( true );
cbEditor = cb.getEditor();
cbEditorComp = cbEditor.getEditorComponent();
cbEditorComp.getDocument().setDocumentFilter(new myComboBoxEditorDocumentFilter(cbEditorComp));

How long to brute force a salted SHA-512 hash? (salt provided)

In your case, breaking the hash algorithm is equivalent to finding a collision in the hash algorithm. That means you don't need to find the password itself (which would be a preimage attack), you just need to find an output of the hash function that is equal to the hash of a valid password (thus "collision"). Finding a collision using a birthday attack takes O(2^(n/2)) time, where n is the output length of the hash function in bits.

SHA-2 has an output size of 512 bits, so finding a collision would take O(2^256) time. Given there are no clever attacks on the algorithm itself (currently none are known for the SHA-2 hash family) this is what it takes to break the algorithm.

To get a feeling for what 2^256 actually means: currently it is believed that the number of atoms in the (entire!!!) universe is roughly 10^80 which is roughly 2^266. Assuming 32 byte input (which is reasonable for your case - 20 bytes salt + 12 bytes password) my machine takes ~0,22s (~2^-2s) for 65536 (=2^16) computations. So 2^256 computations would be done in 2^240 * 2^16 computations which would take

2^240 * 2^-2 = 2^238 ~ 10^72s ~ 3,17 * 10^64 years

Even calling this millions of years is ridiculous. And it doesn't get much better with the fastest hardware on the planet computing thousands of hashes in parallel. No human technology will be able to crunch this number into something acceptable.

So forget brute-forcing SHA-256 here. Your next question was about dictionary words. To retrieve such weak passwords rainbow tables were used traditionally. A rainbow table is generally just a table of precomputed hash values, the idea is if you were able to precompute and store every possible hash along with its input, then it would take you O(1) to look up a given hash and retrieve a valid preimage for it. Of course this is not possible in practice since there's no storage device that could store such enormous amounts of data. This dilemma is known as memory-time tradeoff. As you are only able to store so many values typical rainbow tables include some form of hash chaining with intermediary reduction functions (this is explained in detail in the Wikipedia article) to save on space by giving up a bit of savings in time.

Salts were a countermeasure to make such rainbow tables infeasible. To discourage attackers from precomputing a table for a specific salt it is recommended to apply per-user salt values. However, since users do not use secure, completely random passwords, it is still surprising how successful you can get if the salt is known and you just iterate over a large dictionary of common passwords in a simple trial and error scheme. The relationship between natural language and randomness is expressed as entropy. Typical password choices are generally of low entropy, whereas completely random values would contain a maximum of entropy.

The low entropy of typical passwords makes it possible that there is a relatively high chance of one of your users using a password from a relatively small database of common passwords. If you google for them, you will end up finding torrent links for such password databases, often in the gigabyte size category. Being successful with such a tool is usually in the range of minutes to days if the attacker is not restricted in any way.

That's why generally hashing and salting alone is not enough, you need to install other safety mechanisms as well. You should use an artificially slowed down entropy-enducing method such as PBKDF2 described in PKCS#5 and you should enforce a waiting period for a given user before they may retry entering their password. A good scheme is to start with 0.5s and then doubling that time for each failed attempt. In most cases users don't notice this and don't fail much more often than three times on average. But it will significantly slow down any malicious outsider trying to attack your application.

PostgreSQL wildcard LIKE for any of a list of words

One 'elegant' solution would be to use full text search: http://www.postgresql.org/docs/9.0/interactive/textsearch.html. Then you would use full text search queries.

What is the runtime performance cost of a Docker container?

Here's some more benchmarks for Docker based memcached server versus host native memcached server using Twemperf benchmark tool https://github.com/twitter/twemperf with 5000 connections and 20k connection rate

Connect time overhead for docker based memcached seems to agree with above whitepaper at roughly twice native speed.

Twemperf Docker Memcached

Connection rate: 9817.9 conn/s
Connection time [ms]: avg 341.1 min 73.7 max 396.2 stddev 52.11
Connect time [ms]: avg 55.0 min 1.1 max 103.1 stddev 28.14
Request rate: 83942.7 req/s (0.0 ms/req)
Request size [B]: avg 129.0 min 129.0 max 129.0 stddev 0.00
Response rate: 83942.7 rsp/s (0.0 ms/rsp)
Response size [B]: avg 8.0 min 8.0 max 8.0 stddev 0.00
Response time [ms]: avg 28.6 min 1.2 max 65.0 stddev 0.01
Response time [ms]: p25 24.0 p50 27.0 p75 29.0
Response time [ms]: p95 58.0 p99 62.0 p999 65.0

Twemperf Centmin Mod Memcached

Connection rate: 11419.3 conn/s
Connection time [ms]: avg 200.5 min 0.6 max 263.2 stddev 73.85
Connect time [ms]: avg 26.2 min 0.0 max 53.5 stddev 14.59
Request rate: 114192.6 req/s (0.0 ms/req)
Request size [B]: avg 129.0 min 129.0 max 129.0 stddev 0.00
Response rate: 114192.6 rsp/s (0.0 ms/rsp)
Response size [B]: avg 8.0 min 8.0 max 8.0 stddev 0.00
Response time [ms]: avg 17.4 min 0.0 max 28.8 stddev 0.01
Response time [ms]: p25 12.0 p50 20.0 p75 23.0
Response time [ms]: p95 28.0 p99 28.0 p999 29.0

Here's bencmarks using memtier benchmark tool

memtier_benchmark docker Memcached

4         Threads
50        Connections per thread
10000     Requests per thread
Type        Ops/sec     Hits/sec   Misses/sec      Latency       KB/sec
------------------------------------------------------------------------
Sets       16821.99          ---          ---      1.12600      2271.79
Gets      168035.07    159636.00      8399.07      1.12000     23884.00
Totals    184857.06    159636.00      8399.07      1.12100     26155.79

memtier_benchmark Centmin Mod Memcached

4         Threads
50        Connections per thread
10000     Requests per thread
Type        Ops/sec     Hits/sec   Misses/sec      Latency       KB/sec
------------------------------------------------------------------------
Sets       28468.13          ---          ---      0.62300      3844.59
Gets      284368.51    266547.14     17821.36      0.62200     39964.31
Totals    312836.64    266547.14     17821.36      0.62200     43808.90

scrollable div inside container

I created an enhanced version, based on Trey Copland's fiddle, that I think is more like what you wanted. Added here for future reference to those who come here later. Fiddle example

    <body>
<style>
.modal {
  height: 390px;
  border: 5px solid green;
}
.heading {
  padding: 10px;
}
.content {
  height: 300px;
  overflow:auto;
  border: 5px solid red;
}
.scrollable {
  height: 1200px;
  border: 5px solid yellow;

}
.footer {
  height: 2em;
  padding: .5em;
}
</style>
      <div class="modal">
          <div class="heading">
            <h4>Heading</h4>
          </div>
          <div class="content">
              <div class="scrollable" >hello</div>
          </div>
          <div class="footer">
            Footer
          </div>
      </div>
    </body>