Programs & Examples On #Rspec rails

rspec-rails is an extension of the RSpec testing framework that provides support for testing Ruby on Rails applications.

rails + MySQL on OSX: Library not loaded: libmysqlclient.18.dylib

If you're using Bitnami RubyStack and ran across the similar problem. Try this one

sudo ln -s /Applications/rubystack-2.0.0-17/mysql/lib/libmysqlclient.18.dylib /usr/lib/libmysqlclient.18.dylib

How to start rails server?

If you are in rails2 version then to start the server you have do,

script/server or

./script/server

But if you are in rails3 or above version then to start the server you have do,

rails server or

rails s

How to run a single RSpec test?

There are many options:

rspec spec                           # All specs
rspec spec/models                    # All specs in the models directory
rspec spec/models/a_model_spec.rb    # All specs in the some_model model spec
rspec spec/models/a_model_spec.rb:nn # Run the spec that includes line 'nn'
rspec -e"text from a test"           # Runs specs that match the text
rspec spec --tag focus               # Runs specs that have :focus => true
rspec spec --tag focus:special       # Run specs that have :focus => special
rspec spec --tag focus ~skip         # Run tests except those with :focus => true

incompatible character encodings: ASCII-8BIT and UTF-8

I solved it by following these steps:

  • Make sure config.encoding = "utf-8" is in the application.rb file.
  • Make sure you are using the 'mysql2' gem.
  • Put # encoding: utf-8 at the top of file containing UTF-8 characters.
  • Above the <App Name>::Application.initialize! line in the environment.rb file, add following two lines:

    Encoding.default_external = Encoding::UTF_8
    Encoding.default_internal = Encoding::UTF_8
    

http://rorguide.blogspot.com/2011/06/incompatible-character-encodings-ascii.html

check if a string matches an IP address pattern in python?

You may try the following (the program can be further optimized):

path = "/abc/test1.txt"
fh = open (path, 'r')
ip_arr_tmp = []
ip_arr = []
ip_arr_invalid = []

for lines in fh.readlines():
    resp = re.search ("([0-9]+).([0-9]+).([0-9]+).([0-9]+)", lines)
    print resp

    if resp != None:
       (p1,p2,p3,p4) = [resp.group(1), resp.group(2), resp.group(3), resp.group(4)]       

       if (int(p1) < 0 or int(p2) < 0 or int(p3) < 0 or int(p4) <0):
           ip_arr_invalid.append("%s.%s.%s.%s" %(p1,p2,p3,p4))

       elif (int(p1) > 255 or int(p2) > 255 or int(p3) > 255 or int(p4) > 255):
            ip_arr_invalid.append("%s.%s.%s.%s" %(p1,p2,p3,p4))

       elif (len(p1)>3 or len(p2)>3 or len(p3)>3 or len(p4)>3):
            ip_arr_invalid.append("%s.%s.%s.%s" %(p1,p2,p3,p4))

       else:
           ip = ("%s.%s.%s.%s" %(p1,p2,p3,p4))
           ip_arr_tmp.append(ip)

print ip_arr_tmp

for item in ip_arr_tmp:
    if not item in ip_arr:
       ip_arr.append(item)

print ip_arr

How to make a 3-level collapsing menu in Bootstrap?

Bootstrap 3 dropped native support for nested collapsing menus, but there's a way to re-enable it with a 3rd party script. It's called SmartMenus. It means adding three new resources to your page, but it seamlessly supports Bootstrap 3.x with multiple levels of menus for nested <ul>/<li> elements with class="dropdown-menu". It automatically displays the proper caret indicator as well.

<head>
   ...
   <script src=".../jquery.smartmenus.min.js"></script>
   <script src=".../jquery.smartmenus.bootstrap.min.js"></script>
   ...
   <link rel="stylesheet" href=".../jquery.smartmenus.bootstrap.min.css"/>
   ...
</head>

Here's a demo page: http://vadikom.github.io/smartmenus/src/demo/bootstrap-navbar-fixed-top.html

PHP PDO returning single row

Thanks to Steven's suggestion to use fetchColumn, here's my recommendation to cut short one line from your code.

$DBH = new PDO( "connection string goes here" );
$STH = $DBH->query( "select figure from table1" );
$result = $STH->fetchColumn();
echo $result;
$DBH = null;

Entity Framework - Code First - Can't Store List<String>

This answer is based on the ones provided by @Sasan and @CAD bloke.

If you wish to use this in .NET Standard 2 or don't want Newtonsoft, see Xaniff's answer below

Works only with EF Core 2.1+ (not .NET Standard compatible)(Newtonsoft JsonConvert)

builder.Entity<YourEntity>().Property(p => p.Strings)
    .HasConversion(
        v => JsonConvert.SerializeObject(v),
        v => JsonConvert.DeserializeObject<List<string>>(v));

Using the EF Core fluent configuration we serialize/deserialize the List to/from JSON.

Why this code is the perfect mix of everything you could strive for:

  • The problem with Sasn's original answer is that it will turn into a big mess if the strings in the list contains commas (or any character chosen as the delimiter) because it will turn a single entry into multiple entries but it is the easiest to read and most concise.
  • The problem with CAD bloke's answer is that it is ugly and requires the model to be altered which is a bad design practice (see Marcell Toth's comment on Sasan's answer). But it is the only answer that is data-safe.

Dealing with HTTP content in HTTPS pages

Best way work for me

<img src="/path/image.png" />// this work only online
    or
    <img src="../../path/image.png" /> // this work both
    or asign variable
    <?php 
    $base_url = '';
    if($_SERVER['HTTP_HOST'] == 'localhost')
    {
         $base_url = 'localpath'; 
    }
    ?>
    <img src="<?php echo $base_url;?>/path/image.png" /> 

Excel 2010: how to use autocomplete in validation list

As other people suggested, you need to use a combobox. However, most tutorials show you how to set up just one combobox and the process is quite tedious.

As I faced this problem before when entering a large amount of data from a list, I can suggest you use this autocomplete add-in . It helps you create the combobox on any cells you select and you can define a list to appear in the dropdown.

cast class into another class or convert class to another

You have already defined the conversion, you just need to take it one step further if you would like to be able to cast. For example:

public class sub1
{
    public int a;
    public int b;
    public int c;

    public static explicit operator maincs(sub1 obj)
    {
        maincs output = new maincs() { a = obj.a, b = obj.b, c = obj.c };
        return output;
    }
}

Which then allows you to do something like

static void Main()
{
    sub1 mySub = new sub1();
    maincs myMain = (maincs)mySub;
}

importing a CSV into phpmyadmin

In phpMyAdmin, click the table, and then click the Import tab at the top of the page.

Browse and open the csv file. Leave the charset as-is. Uncheck partial import unless you have a HUGE dataset (or slow server). The format should already have selected “CSV” after selecting your file, if not then select it (not using LOAD DATA). If you want to clear the whole table before importing, check “Replace table data with file”. Optionally check “Ignore duplicate rows” if you think you have duplicates in the CSV file. Now the important part, set the next four fields to these values:

Fields terminated by: ,
Fields enclosed by: “
Fields escaped by: \
Lines terminated by: auto

Currently these match the defaults except for “Fields terminated by”, which defaults to a semicolon.

Now click the Go button, and it should run successfully.

Convert Char to String in C

//example
char character;//to be scanned
char merge[2];// this is just temporary array to merge with      
merge[0] = character;
merge[1] = '\0';
//now you have changed it into a string

Continuous Integration vs. Continuous Delivery vs. Continuous Deployment

lets keep it short :

CI: A software development practice where members of a team integrate their work at least daily. Each integration is verified by automated build (include tests)to detect error as quick as possible. CD: CD Builds on CI, where you build software in such a way that the software can be released to production at any time.

Is there a /dev/null on Windows?

NUL works programmatically as well. E.g. the following:

freopen("NUL", "w", stderr);

works as expected without creating a file. (MSVC++ 12.0)

Parse v. TryParse

Parse throws an exception if it cannot parse the value, whereas TryParse returns a bool indicating whether it succeeded.

TryParse does not just try/catch internally - the whole point of it is that it is implemented without exceptions so that it is fast. In fact the way it is most likely implemented is that internally the Parse method will call TryParse and then throw an exception if it returns false.

In a nutshell, use Parse if you are sure the value will be valid; otherwise use TryParse.

How to refresh an IFrame using Javascript?

Resetting the src attribute directly:

iframe.src = iframe.src;

Resetting the src with a time stamp for cache busting:

iframe.src =  iframe.src.split("?")[0] + "?_=" + new Date().getTime();

Clearing the src when query strings option is not possible (Data URI):

var wasSrc = iframe.src

iframe.onload = function() {
    iframe.onload = undefined;
    iframe.src = wasSrc;
}

How to draw a dotted line with css?

Using hr created two lines for me, one solid and one dotted.

I found that this worked quite well:

div {
border-top: 1px dotted #cccccc;
color: #ffffff;
background-color: #ffffff;
height: 1px;
width: 95%;
}

Plus, because you can make the width a percentage, it will always have some space on either side (even when you resize the window).

What database does Google use?

Bigtable

A Distributed Storage System for Structured Data

Bigtable is a distributed storage system (built by Google) for managing structured data that is designed to scale to a very large size: petabytes of data across thousands of commodity servers.

Many projects at Google store data in Bigtable, including web indexing, Google Earth, and Google Finance. These applications place very different demands on Bigtable, both in terms of data size (from URLs to web pages to satellite imagery) and latency requirements (from backend bulk processing to real-time data serving).

Despite these varied demands, Bigtable has successfully provided a flexible, high-performance solution for all of these Google products.

Some features

  • fast and extremely large-scale DBMS
  • a sparse, distributed multi-dimensional sorted map, sharing characteristics of both row-oriented and column-oriented databases.
  • designed to scale into the petabyte range
  • it works across hundreds or thousands of machines
  • it is easy to add more machines to the system and automatically start taking advantage of those resources without any reconfiguration
  • each table has multiple dimensions (one of which is a field for time, allowing versioning)
  • tables are optimized for GFS (Google File System) by being split into multiple tablets - segments of the table as split along a row chosen such that the tablet will be ~200 megabytes in size.

Architecture

BigTable is not a relational database. It does not support joins nor does it support rich SQL-like queries. Each table is a multidimensional sparse map. Tables consist of rows and columns, and each cell has a time stamp. There can be multiple versions of a cell with different time stamps. The time stamp allows for operations such as "select 'n' versions of this Web page" or "delete cells that are older than a specific date/time."

In order to manage the huge tables, Bigtable splits tables at row boundaries and saves them as tablets. A tablet is around 200 MB, and each machine saves about 100 tablets. This setup allows tablets from a single table to be spread among many servers. It also allows for fine-grained load balancing. If one table is receiving many queries, it can shed other tablets or move the busy table to another machine that is not so busy. Also, if a machine goes down, a tablet may be spread across many other servers so that the performance impact on any given machine is minimal.

Tables are stored as immutable SSTables and a tail of logs (one log per machine). When a machine runs out of system memory, it compresses some tablets using Google proprietary compression techniques (BMDiff and Zippy). Minor compactions involve only a few tablets, while major compactions involve the whole table system and recover hard-disk space.

The locations of Bigtable tablets are stored in cells. The lookup of any particular tablet is handled by a three-tiered system. The clients get a point to a META0 table, of which there is only one. The META0 table keeps track of many META1 tablets that contain the locations of the tablets being looked up. Both META0 and META1 make heavy use of pre-fetching and caching to minimize bottlenecks in the system.

Implementation

BigTable is built on Google File System (GFS), which is used as a backing store for log and data files. GFS provides reliable storage for SSTables, a Google-proprietary file format used to persist table data.

Another service that BigTable makes heavy use of is Chubby, a highly-available, reliable distributed lock service. Chubby allows clients to take a lock, possibly associating it with some metadata, which it can renew by sending keep alive messages back to Chubby. The locks are stored in a filesystem-like hierarchical naming structure.

There are three primary server types of interest in the Bigtable system:

  1. Master servers: assign tablets to tablet servers, keeps track of where tablets are located and redistributes tasks as needed.
  2. Tablet servers: handle read/write requests for tablets and split tablets when they exceed size limits (usually 100MB - 200MB). If a tablet server fails, then a 100 tablet servers each pickup 1 new tablet and the system recovers.
  3. Lock servers: instances of the Chubby distributed lock service. Lots of actions within BigTable require acquisition of locks including opening tablets for writing, ensuring that there is no more than one active Master at a time, and access control checking.

Example from Google's research paper:

alt text

A slice of an example table that stores Web pages. The row name is a reversed URL. The contents column family contains the page contents, and the anchor column family contains the text of any anchors that reference the page. CNN's home page is referenced by both the Sports Illustrated and the MY-look home pages, so the row contains columns named anchor:cnnsi.com and anchor:my.look.ca. Each anchor cell has one version; the contents column has three versions, at timestamps t3, t5, and t6.

API

Typical operations to BigTable are creation and deletion of tables and column families, writing data and deleting columns from a row. BigTable provides this functions to application developers in an API. Transactions are supported at the row level, but not across several row keys.


Here is the link to the PDF of the research paper.

And here you can find a video showing Google's Jeff Dean in a lecture at the University of Washington, discussing the Bigtable content storage system used in Google's backend.

How to select an element with 2 classes

You can chain class selectors without a space between them:

.a.b {
     color: #666;
}

Note that, if it matters to you, IE6 treats .a.b as .b, so in that browser both div.a.b and div.b will have gray text. See this answer for a comparison between proper browsers and IE6.

Generating 8-character only UUIDs

Actually I want timestamp based shorter unique identifier, hence tried the below program.

It is guessable with nanosecond + ( endians.length * endians.length ) combinations.

public class TimStampShorterUUID {

    private static final Character [] endians = 
           {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 
            'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 
            'u', 'v', 'w', 'x', 'y', 'z', 
            'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 
            'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 
            'U', 'V', 'W', 'X', 'Y', 'Z',
            '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'
            };

   private static ThreadLocal<Character> threadLocal =  new ThreadLocal<Character>();

   private static AtomicLong iterator = new AtomicLong(-1);


    public static String generateShorterTxnId() {
        // Keep this as secure random when we want more secure, in distributed systems
        int firstLetter = ThreadLocalRandom.current().nextInt(0, (endians.length));

        //Sometimes your randomness and timestamp will be same value,
        //when multiple threads are trying at the same nano second
        //time hence to differentiate it, utilize the threads requesting
        //for this value, the possible unique thread numbers == endians.length
        Character secondLetter = threadLocal.get();
        if (secondLetter == null) {
            synchronized (threadLocal) {
                if (secondLetter == null) {
                    threadLocal.set(endians[(int) (iterator.incrementAndGet() % endians.length)]);
                }
            }
            secondLetter = threadLocal.get();
        }
        return "" + endians[firstLetter] + secondLetter + System.nanoTime();
    }


    public static void main(String[] args) {

        Map<String, String> uniqueKeysTestMap = new ConcurrentHashMap<>();

        Thread t1 = new Thread() {  
            @Override
            public void run() {
                while(true) {
                    String time = generateShorterTxnId();
                    String result = uniqueKeysTestMap.put(time, "");
                    if(result != null) {
                        System.out.println("failed! - " + time);
                    }
                }
            }       
        };

        Thread t2 = new Thread() {  
            @Override
            public void run() {
                while(true) {
                    String time = generateShorterTxnId();
                    String result = uniqueKeysTestMap.put(time, "");
                    if(result != null) {
                        System.out.println("failed! - " + time);
                    }
                }
            }       
        };

        Thread t3 = new Thread() {  
            @Override
            public void run() {
                while(true) {
                    String time = generateShorterTxnId();
                    String result = uniqueKeysTestMap.put(time, "");
                    if(result != null) {
                        System.out.println("failed! - " + time);
                    }
                }
            }       
        };

        Thread t4 = new Thread() {  
            @Override
            public void run() {
                while(true) {
                    String time = generateShorterTxnId();
                    String result = uniqueKeysTestMap.put(time, "");
                    if(result != null) {
                        System.out.println("failed! - " + time);
                    }
                }
            }       
        };

        Thread t5 = new Thread() {  
            @Override
            public void run() {
                while(true) {
                    String time = generateShorterTxnId();
                    String result = uniqueKeysTestMap.put(time, "");
                    if(result != null) {
                        System.out.println("failed! - " + time);
                    }
                }
            }
        };

        Thread t6 = new Thread() {  
            @Override
            public void run() {
                while(true) {
                    String time = generateShorterTxnId();
                    String result = uniqueKeysTestMap.put(time, "");
                    if(result != null) {
                        System.out.println("failed! - " + time);
                    }
                }
            }   
        };

        Thread t7 = new Thread() {  
            @Override
            public void run() {
                while(true) {
                    String time = generateShorterTxnId();
                    String result = uniqueKeysTestMap.put(time, "");
                    if(result != null) {
                        System.out.println("failed! - " + time);
                    }
                }
            }
        };

        t1.start();
        t2.start();
        t3.start();
        t4.start();
        t5.start();
        t6.start();
        t7.start();
    }
}

UPDATE: This code will work on single JVM, but we should think on distributed JVM, hence i am thinking two solutions one with DB and another one without DB.

with DB

Company name (shortname 3 chars) ---- Random_Number ---- Key specific redis COUNTER
(3 char) ------------------------------------------------ (2 char) ---------------- (11 char)

without DB

IPADDRESS ---- THREAD_NUMBER ---- INCR_NUMBER ---- epoch milliseconds
(5 chars) ----------------- (2char) ----------------------- (2 char) ----------------- (6 char)

will update you once coding is done.

How can I print to the same line?

You could print the backspace character '\b' as many times as necessary to delete the line before printing the updated progress bar.

Naming threads and thread-pools of ExecutorService

The BasicThreadFactory from apache commons-lang is also useful to provide the naming behavior. Instead of writing an anonymous inner class, you can use the Builder to name the threads as you want. Here's the example from the javadocs:

 // Create a factory that produces daemon threads with a naming pattern and
 // a priority
 BasicThreadFactory factory = new BasicThreadFactory.Builder()
     .namingPattern("workerthread-%d")
     .daemon(true)
     .priority(Thread.MAX_PRIORITY)
     .build();
 // Create an executor service for single-threaded execution
 ExecutorService exec = Executors.newSingleThreadExecutor(factory);

Query for documents where array size is greater than 1

I found this solution, to find items with an array field greater than certain length

db.allusers.aggregate([
  {$match:{username:{$exists:true}}},
  {$project: { count: { $size:"$locations.lat" }}},
  {$match:{count:{$gt:20}}}
])

The first $match aggregate uses an argument thats true for all the documents. If blank, i would get

"errmsg" : "exception: The argument to $size must be an Array, but was of type: EOO"

How to auto-remove trailing whitespace in Eclipse?

I used this command for git: git config --global core.whitespace cr-at-eol

It removes ^M characters that are trailing.

On postback, how can I check which control cause postback in Page_Init event

An addition to previous answers, to use Request.Params["__EVENTTARGET"] you have to set the option:

buttonName.UseSubmitBehavior = false;

How to deep copy a list?

@Sukrit Kalra

No.1: list(), [:], copy.copy() are all shallow copy. If an object is compound, they are all not suitable. You need to use copy.deepcopy().

No.2: b = a directly, a and b have the same reference, changing a is even as changing b.

$ python
Python 3.9.0 (tags/v3.9.0:9cf6752, Oct  5 2020, 15:34:40) [MSC v.1927 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> a = [[1, 2, 3], [4, 5, 6]]
>>> b = list(a)
>>> a
[[1, 2, 3], [4, 5, 6]]
>>> b
[[1, 2, 3], [4, 5, 6]]
>>> a[0] = 1
>>> a
[1, [4, 5, 6]]
>>> b
[[1, 2, 3], [4, 5, 6]]
>>> exit()

$ python
Python 3.9.0 (tags/v3.9.0:9cf6752, Oct  5 2020, 15:34:40) [MSC v.1927 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> a = [[1, 2, 3], [4, 5, 6]]
>>> b = a
>>> a
[[1, 2, 3], [4, 5, 6]]
>>> b
[[1, 2, 3], [4, 5, 6]]
>>> a[0] = 1
>>> a
[1, [4, 5, 6]]
>>> b
[1, [4, 5, 6]]
>>> exit()

Disable password authentication for SSH

Run

service ssh restart

instead of

/etc/init.d/ssh restart

This might work.

How to set menu to Toolbar in Android

In your activity override this method.

   @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main_menu, menu);
        return true;
    }

This will inflate your menu below:

 <?xml version="1.0" encoding="utf-8"?>
    <menu xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto">

        <item
            android:id="@+id/menu_main_setting"
            android:icon="@drawable/ic_settings"
            android:orderInCategory="100"
            app:showAsAction="always"
            android:actionLayout="@layout/toolbar"
            android:title="Setting" />

        <item
            android:id="@+id/menu_main_setting2"
            android:icon="@drawable/ic_settings"
            android:orderInCategory="200"
            app:showAsAction="always"
            android:actionLayout="@layout/toolbar"
            android:title="Setting" />

    </menu>

How can I get the DateTime for the start of the week?

This would give you the preceding Sunday (I think):

DateTime t = DateTime.Now;
t -= new TimeSpan ((int) t.DayOfWeek, 0, 0, 0);

Setting an image button in CSS - image:active

This is what worked for me.

<!DOCTYPE html> 
<form action="desired Link">
  <button>  <img src="desired image URL"/>
  </button>
</form>
<style> 

</style>

ASP.NET Background image

You can use this if you want to assign a background image on the backend:

divContent.Attributes.Add("style"," background-image:
url('images/icon_stock.gif');");

DateTime.Today.ToString("dd/mm/yyyy") returns invalid DateTime Value

use MM(months) instead of mm(minutes) :

DateTime.Now.ToString("dd/MM/yyyy");

check here for more format options.

How to determine if a point is in a 2D triangle?

C# version of the barycentric method posted by andreasdr and Perro Azul. I added a check to abandon the area calculation when s and t have opposite signs, since potentially avoiding one-third of the multiplication cost seems justified.

Also, even though the math here is firmly-established by now, I ran a thorough unit-test harness on this specific code for good measure anyway.

public static bool PointInTriangle(Point p, Point p0, Point p1, Point p2)
{
    var s = p0.Y * p2.X - p0.X * p2.Y + (p2.Y - p0.Y) * p.X + (p0.X - p2.X) * p.Y;
    var t = p0.X * p1.Y - p0.Y * p1.X + (p0.Y - p1.Y) * p.X + (p1.X - p0.X) * p.Y;

    if ((s < 0) != (t < 0))
        return false;

    var A = -p1.Y * p2.X + p0.Y * (p2.X - p1.X) + p0.X * (p1.Y - p2.Y) + p1.X * p2.Y;

    return A < 0 ?
            (s <= 0 && s + t >= A) :
            (s >= 0 && s + t <= A);
}

How do you update Xcode on OSX to the latest version?

  1. Open up App Store

    enter image description here

  2. Look in the top right for the updates section (may also be in lefthand column "Updates"..)

    enter image description here

  3. Find Xcode & click Update enter image description here

How to check if a file exists in the Documents directory in Swift?

An alternative/recommended Code Pattern in Swift 3 would be:

  1. Use URL instead of FileManager
  2. Use of exception handling

    func verifyIfSqliteDBExists(){
        let docsDir     : URL       = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
        let dbPath      : URL       = docsDir.appendingPathComponent("database.sqlite")
    
        do{
            let sqliteExists : Bool = try dbPath.checkResourceIsReachable()
            print("An sqlite database exists at this path :: \(dbPath.path)")
    
        }catch{
            print("SQLite NOT Found at :: \(strDBPath)")
        }
    }
    

Adding a user on .htpasswd

Exact same thing, just omit the -c option. Apache's docs on it here.

htpasswd /etc/apache2/.htpasswd newuser

Also, htpasswd typically isn't run as root. It's typically owned by either the web server, or the owner of the files being served. If you're using root to edit it instead of logging in as one of those users, that's acceptable (I suppose), but you'll want to be careful to make sure you don't accidentally create a file as root (and thus have root own it and no one else be able to edit it).

Uncaught TypeError: Cannot read property 'split' of undefined

ogdate is itself a string, why are you trying to access it's value property that it doesn't have ?

console.log(og_date.split('-'));

JSFiddle

How do I set a ViewModel on a window in XAML using DataContext property?

You might want to try Catel. It allows you to define a DataWindow class (instead of Window), and that class automatically creates the view model for you. This way, you can use the declaration of the ViewModel as you did in your original post, and the view model will still be created and set as DataContext.

See this article for an example.

Android Left to Right slide animation

Use this xml in res/anim/

This is for left to right animation:

<set xmlns:android="http://schemas.android.com/apk/res/android"
     android:shareInterpolator="false">
  <translate android:fromXDelta="-100%" android:toXDelta="0%"
             android:fromYDelta="0%" android:toYDelta="0%"
             android:duration="700"/>
</set>

This is for right to left animation:

<set xmlns:android="http://schemas.android.com/apk/res/android"
     android:shareInterpolator="false">
  <translate
     android:fromXDelta="0%" android:toXDelta="100%"
     android:fromYDelta="0%" android:toYDelta="0%"
     android:duration="700" />
</set>

In your coding use intent like for left to right:

this.overridePendingTransition(R.anim.animation_enter,
                   R.anim.animation_leave);

In your coding use intent like for right to left

this.overridePendingTransition(R.anim.animation_leave,
                               R.anim.animation_enter);

Using a Loop to add objects to a list(python)

The problem appears to be that you are reinitializing the list to an empty list in each iteration:

while choice != 0:
    ...
    a = []
    a.append(s)

Try moving the initialization above the loop so that it is executed only once.

a = []
while choice != 0:
    ...
    a.append(s)

How can I create a temp file with a specific extension with .NET?

In my opinion, most answers proposed here as sub-optimal. The one coming closest is the original one proposed initially by Brann.

A Temp Filename must be

  • Unique
  • Conflict-free (not already exist)
  • Atomic (Creation of Name & File in the same operation)
  • Hard to guess

Because of these requirements, it is not a godd idea to program such a beast on your own. Smart People writing IO Libraries worry about things like locking (if needed) etc. Therefore, I see no need to rewrite System.IO.Path.GetTempFileName().

This, even if it looks clumsy, should do the job:

//Note that this already *creates* the file
string filename1 = System.IO.Path.GetTempFileName()
// Rename and move
filename = filename.Replace(".tmp", ".csv");
File.Move(filename1 , filename);

What are public, private and protected in object oriented programming?

as above, but qualitatively:

private - least access, best encapsulation
protected - some access, moderate encapsulation
public - full access, no encapsulation

the less access you provide the fewer implementation details leak out of your objects. less of this sort of leakage means more flexibility (aka "looser coupling") in terms of changing how an object is implemented without breaking clients of the object. this is a truly fundamental thing to understand.

When do you use Java's @Override annotation and why?

i think it's best to code the @override whenever allowed. it helps for coding. however, to be noted, for ecipse Helios, either sdk 5 or 6, the @override annotation for implemented interface methods is allowed. as for Galileo, either 5 or 6, @override annotation is not allowed.

Docker can't connect to docker daemon

To fix this issue, I had to enable the docker service:

sudo systemctl enable /usr/lib/systemd/system/docker.service

How to make cross domain request

Do a cross-domain AJAX call

Your web-service must support method injection in order to do JSONP.

Your code seems fine and it should work if your web services and your web application hosted in the same domain.

When you do a $.ajax with dataType: 'jsonp' meaning that jQuery is actually adding a new parameter to the query URL.

For instance, if your URL is http://10.211.2.219:8080/SampleWebService/sample.do then jQuery will add ?callback={some_random_dynamically_generated_method}.

This method is more kind of a proxy actually attached in window object. This is nothing specific but does look something like this:

window.some_random_dynamically_generated_method = function(actualJsonpData) {
    //here actually has reference to the success function mentioned with $.ajax
    //so it just calls the success method like this: 
    successCallback(actualJsonData);
}

Check the following for more information

Make cross-domain ajax JSONP request with jQuery

How to increase font size in a plot in R?

Notice that "cex" does change things when the plot is made with text. For example, the plot of an agglomerative hierarchical clustering:

library(cluster)
data(votes.repub)
agn1 <- agnes(votes.repub, metric = "manhattan", stand = TRUE)
plot(agn1, which.plots=2)

will produce a plot with normal sized text:

enter image description here

and plot(agn1, which.plots=2, cex=0.5) will produce this one:

enter image description here

Find a value in DataTable

this question asked in 2009 but i want to share my codes:

    Public Function RowSearch(ByVal dttable As DataTable, ByVal searchcolumns As String()) As DataTable

    Dim x As Integer
    Dim y As Integer

    Dim bln As Boolean

    Dim dttable2 As New DataTable
    For x = 0 To dttable.Columns.Count - 1
        dttable2.Columns.Add(dttable.Columns(x).ColumnName)
    Next

    For x = 0 To dttable.Rows.Count - 1
        For y = 0 To searchcolumns.Length - 1
            If String.IsNullOrEmpty(searchcolumns(y)) = False Then
                If searchcolumns(y) = CStr(dttable.Rows(x)(y + 1) & "") & "" Then
                    bln = True
                Else
                    bln = False
                    Exit For
                End If
            End If
        Next
        If bln = True Then
            dttable2.Rows.Add(dttable.Rows(x).ItemArray)
        End If
    Next

    Return dttable2


End Function

How do I use su to execute the rest of the bash script as that user?

This worked for me

I split out my "provisioning" from my "startup".

 # Configure everything else ready to run 
  config.vm.provision :shell, path: "provision.sh"
  config.vm.provision :shell, path: "start_env.sh", run: "always"

then in my start_env.sh

#!/usr/bin/env bash

echo "Starting Server Env"
#java -jar /usr/lib/node_modules/selenium-server-standalone-jar/jar/selenium-server-standalone-2.40.0.jar  &
#(cd /vagrant_projects/myproj && sudo -u vagrant -H sh -c "nohup npm install 0<&- &>/dev/null &;bower install 0<&- &>/dev/null &")
cd /vagrant_projects/myproj
nohup grunt connect:server:keepalive 0<&- &>/dev/null &
nohup apimocker -c /vagrant_projects/myproj/mock_api_data/config.json 0<&- &>/dev/null &

Is there a way I can capture my iPhone screen as a video?

i guess it is so obvious now that no one has posted this but for the noobs.... note: iPhone 4S only

just airplay to an apple tv and video mirror then output the atv to a device that can record - like tivo, dvr etc. you can also use a video out cable on the iPad [1 and 2] now

not sure if the cable works on the iPhone 4S as I havent tested that myself

its clunky but there is no other way i can see atm.

PHP PDO with foreach and fetch

$users = $dbh->query($sql);
foreach ($users as $row) {
    print $row["name"] . "-" . $row["sex"] ."<br/>";
}
foreach ($users as $row) {
    print $row["name"] . "-" . $row["sex"] ."<br/>";
}

Here $users is a PDOStatement object over which you can iterate. The first iteration outputs all results, the second does nothing since you can only iterate over the result once. That's because the data is being streamed from the database and iterating over the result with foreach is essentially shorthand for:

while ($row = $users->fetch()) ...

Once you've completed that loop, you need to reset the cursor on the database side before you can loop over it again.

$users = $dbh->query($sql);
foreach ($users as $row) {
    print $row["name"] . "-" . $row["sex"] ."<br/>";
}
echo "<br/>";
$result = $users->fetch(PDO::FETCH_ASSOC);
foreach($result as $key => $value) {
    echo $key . "-" . $value . "<br/>";
}

Here all results are being output by the first loop. The call to fetch will return false, since you have already exhausted the result set (see above), so you get an error trying to loop over false.

In the last example you are simply fetching the first result row and are looping over it.

Counting the number of elements with the values of x in a vector

There is also count(numbers) from plyr package. Much more convenient than table in my opinion.

Remove a string from the beginning of a string

You can use regular expressions with the caret symbol (^) which anchors the match to the beginning of the string:

$str = preg_replace('/^bla_/', '', $str);

What is the difference between SAX and DOM?

I will provide general Q&A-oriented answer for this question:

Answer to Questions

Why do we need XML parser?

We need XML parser because we do not want to do everything in our application from scratch, and we need some "helper" programs or libraries to do something very low-level but very necessary to us. These low-level but necessary things include checking the well-formedness, validating the document against its DTD or schema (just for validating parsers), resolving character reference, understanding CDATA sections, and so on. XML parsers are just such "helper" programs and they will do all these jobs. With XML parser, we are shielded from a lot of these complexities and we could concentrate ourselves on just programming at high-level through the API's implemented by the parsers, and thus gain programming efficiency.

Which one is better, SAX or DOM ?

Both SAX and DOM parser have their advantages and disadvantages. Which one is better should depend on the characteristics of your application (please refer to some questions below).

Which parser can get better speed, DOM or SAX parsers?

SAX parser can get better speed.

What's the difference between tree-based API and event-based API?

A tree-based API is centered around a tree structure and therefore provides interfaces on components of a tree (which is a DOM document) such as Document interface,Node interface, NodeList interface, Element interface, Attr interface and so on. By contrast, however, an event-based API provides interfaces on handlers. There are four handler interfaces, ContentHandler interface, DTDHandler interface, EntityResolver interface and ErrorHandler interface.

What is the difference between a DOM Parser and a SAX Parser?

DOM parsers and SAX parsers work in different ways:

  • A DOM parser creates a tree structure in memory from the input document and then waits for requests from client. But a SAX parser does not create any internal structure. Instead, it takes the occurrences of components of a input document as events, and tells the client what it reads as it reads through the input document. A

  • DOM parser always serves the client application with the entire document no matter how much is actually needed by the client. But a SAX parser serves the client application always only with pieces of the document at any given time.

  • With DOM parser, method calls in client application have to be explicit and forms a kind of chain. But with SAX, some certain methods (usually overriden by the cient) will be invoked automatically (implicitly) in a way which is called "callback" when some certain events occur. These methods do not have to be called explicitly by the client, though we could call them explicitly.

How do we decide on which parser is good?

Ideally a good parser should be fast (time efficient),space efficient, rich in functionality and easy to use. But in reality, none of the main parsers have all these features at the same time. For example, a DOM Parser is rich in functionality (because it creates a DOM tree in memory and allows you to access any part of the document repeatedly and allows you to modify the DOM tree), but it is space inefficient when the document is huge, and it takes a little bit long to learn how to work with it. A SAX Parser, however, is much more space efficient in case of big input document (because it creates no internal structure). What's more, it runs faster and is easier to learn than DOM Parser because its API is really simple. But from the functionality point of view, it provides less functions which mean that the users themselves have to take care of more, such as creating their own data structures. By the way, what is a good parser? I think the answer really depends on the characteristics of your application.

What are some real world applications where using SAX parser is advantageous than using DOM parser and vice versa? What are the usual application for a DOM parser and for a SAX parser?

In the following cases, using SAX parser is advantageous than using DOM parser.

  • The input document is too big for available memory (actually in this case SAX is your only choice)
  • You can process the document in small contiguous chunks of input. You do not need the entire document before you can do useful work
  • You just want to use the parser to extract the information of interest, and all your computation will be completely based on the data structures created by yourself. Actually in most of our applications, we create data structures of our own which are usually not as complicated as the DOM tree. From this sense, I think, the chance of using a DOM parser is less than that of using a SAX parser.

In the following cases, using DOM parser is advantageous than using SAX parser.

  • Your application needs to access widely separately parts of the document at the same time.
  • Your application may probably use a internal data structure which is almost as complicated as the document itself.
  • Your application has to modify the document repeatedly.
  • Your application has to store the document for a significant amount of time through many method calls.

Example (Use a DOM parser or a SAX parser?):

Assume that an instructor has an XML document containing all the personal information of the students as well as the points his students made in his class, and he is now assigning final grades for the students using an application. What he wants to produce, is a list with the SSN and the grades. Also we assume that in his application, the instructor use no data structure such as arrays to store the student personal information and the points. If the instructor decides to give A's to those who earned the class average or above, and give B's to the others, then he'd better to use a DOM parser in his application. The reason is that he has no way to know how much is the class average before the entire document gets processed. What he probably need to do in his application, is first to look through all the students' points and compute the average, and then look through the document again and assign the final grade to each student by comparing the points he earned to the class average. If, however, the instructor adopts such a grading policy that the students who got 90 points or more, are assigned A's and the others are assigned B's, then probably he'd better use a SAX parser. The reason is, to assign each student a final grade, he do not need to wait for the entire document to be processed. He could immediately assign a grade to a student once the SAX parser reads the grade of this student. In the above analysis, we assumed that the instructor created no data structure of his own. What if he creates his own data structure, such as an array of strings to store the SSN and an array of integers to sto re the points ? In this case, I think SAX is a better choice, before this could save both memory and time as well, yet get the job done. Well, one more consideration on this example. What if what the instructor wants to do is not to print a list, but to save the original document back with the grade of each student updated ? In this case, a DOM parser should be a better choice no matter what grading policy he is adopting. He does not need to create any data structure of his own. What he needs to do is to first modify the DOM tree (i.e., set value to the 'grade' node) and then save the whole modified tree. If he choose to use a SAX parser instead of a DOM parser, then in this case he has to create a data structure which is almost as complicated as a DOM tree before he could get the job done.

An Example

Problem statement: Write a Java program to extract all the information about circles which are elements in a given XML document. We assume that each circle element has three child elements(i.e., x, y and radius) as well as a color attribute. A sample document is given below:

<?xml version="1.0"?> 
<!DOCTYPE shapes [
<!ELEMENT shapes (circle)*>
<!ELEMENT circle (x,y,radius)>
<!ELEMENT x (#PCDATA)>
<!ELEMENT y (#PCDATA)>
<!ELEMENT radius (#PCDATA)>
<!ATTLIST circle color CDATA #IMPLIED>
]>

<shapes> 
          <circle color="BLUE"> 
                <x>20</x>
                <y>20</y>
                <radius>20</radius> 
          </circle>
          <circle color="RED" >
                <x>40</x>
                <y>40</y>
                <radius>20</radius> 
          </circle>
</shapes> 

Program with DOMparser

import java.io.*;
import org.w3c.dom.*;
import org.apache.xerces.parsers.DOMParser;


public class shapes_DOM {
   static int numberOfCircles = 0;   // total number of circles seen
   static int x[] = new int[1000];   // X-coordinates of the centers
   static int y[] = new int[1000];   // Y-coordinates of the centers  
   static int r[] = new int[1000];   // radius of the circle
   static String color[] = new String[1000];  // colors of the circles 

   public static void main(String[] args) {   

      try{
         // create a DOMParser
         DOMParser parser=new DOMParser();
         parser.parse(args[0]);

         // get the DOM Document object
         Document doc=parser.getDocument();

         // get all the circle nodes
         NodeList nodelist = doc.getElementsByTagName("circle");
         numberOfCircles =  nodelist.getLength();

         // retrieve all info about the circles
         for(int i=0; i<nodelist.getLength(); i++) {

            // get one circle node
            Node node = nodelist.item(i);

            // get the color attribute 
            NamedNodeMap attrs = node.getAttributes();
            if(attrs.getLength() > 0)
               color[i]=(String)attrs.getNamedItem("color").getNodeValue();

            // get the child nodes of a circle node 
            NodeList childnodelist = node.getChildNodes();

            // get the x and y value 
            for(int j=0; j<childnodelist.getLength(); j++) {
               Node childnode = childnodelist.item(j);
               Node textnode = childnode.getFirstChild();//the only text node
               String childnodename=childnode.getNodeName(); 
               if(childnodename.equals("x")) 
                  x[i]= Integer.parseInt(textnode.getNodeValue().trim());
               else if(childnodename.equals("y")) 
                  y[i]= Integer.parseInt(textnode.getNodeValue().trim());
               else if(childnodename.equals("radius")) 
                  r[i]= Integer.parseInt(textnode.getNodeValue().trim());
            }

         }

         // print the result
         System.out.println("circles="+numberOfCircles);
         for(int i=0;i<numberOfCircles;i++) {
             String line="";
             line=line+"(x="+x[i]+",y="+y[i]+",r="+r[i]+",color="+color[i]+")";
             System.out.println(line);
         }

      }  catch (Exception e) {e.printStackTrace(System.err);}

    }

}

Program with SAXparser

import java.io.*;
import org.xml.sax.*;
import org.xml.sax.helpers.DefaultHandler;
import org.apache.xerces.parsers.SAXParser;


public class shapes_SAX extends DefaultHandler {

   static int numberOfCircles = 0;   // total number of circles seen
   static int x[] = new int[1000];   // X-coordinates of the centers
   static int y[] = new int[1000];   // Y-coordinates of the centers
   static int r[] = new int[1000];   // radius of the circle
   static String color[] = new String[1000];  // colors of the circles

   static int flagX=0;    //to remember what element has occurred
   static int flagY=0;    //to remember what element has occurred
   static int flagR=0;    //to remember what element has occurred

   // main method 
   public static void main(String[] args) {   
      try{
         shapes_SAX SAXHandler = new shapes_SAX (); // an instance of this class
         SAXParser parser=new SAXParser();          // create a SAXParser object 
         parser.setContentHandler(SAXHandler);      // register with the ContentHandler 
         parser.parse(args[0]);
      }  catch (Exception e) {e.printStackTrace(System.err);}  // catch exeptions
   }

   // override the startElement() method
   public void startElement(String uri, String localName, 
                       String rawName, Attributes attributes) {
         if(rawName.equals("circle"))                      // if a circle element is seen
            color[numberOfCircles]=attributes.getValue("color");  // get the color attribute 

         else if(rawName.equals("x"))      // if a x element is seen set the flag as 1 
            flagX=1;
         else if(rawName.equals("y"))      // if a y element is seen set the flag as 2
            flagY=1;
         else if(rawName.equals("radius")) // if a radius element is seen set the flag as 3 
            flagR=1;
   }

   // override the endElement() method
   public void endElement(String uri, String localName, String rawName) {
         // in this example we do not need to do anything else here
         if(rawName.equals("circle"))                       // if a circle element is ended 
            numberOfCircles +=  1;                          // increment the counter 
   }

   // override the characters() method
   public void characters(char characters[], int start, int length) {
         String characterData = 
             (new String(characters,start,length)).trim(); // get the text

         if(flagX==1) {        // indicate this text is for <x> element 
             x[numberOfCircles] = Integer.parseInt(characterData);
             flagX=0;
         }
         else if(flagY==1) {  // indicate this text is for <y> element 
             y[numberOfCircles] = Integer.parseInt(characterData);
             flagY=0;
         }
         else if(flagR==1) {  // indicate this text is for <radius> element 
             r[numberOfCircles] = Integer.parseInt(characterData);
             flagR=0;
         }
   }

   // override the endDocument() method
   public void endDocument() {
         // when the end of document is seen, just print the circle info 
         System.out.println("circles="+numberOfCircles);
         for(int i=0;i<numberOfCircles;i++) {
             String line="";
             line=line+"(x="+x[i]+",y="+y[i]+",r="+r[i]+",color="+color[i]+")";
             System.out.println(line);
         }
   }


}

How to launch an Activity from another Application in Android

If you want to open specific activity of another application we can use this.

Intent intent = new Intent(Intent.ACTION_MAIN, null);
intent.addCategory(Intent.CATEGORY_LAUNCHER);
final ComponentName cn = new ComponentName("com.android.settings", "com.android.settings.fuelgauge.PowerUsageSummary");
intent.setComponent(cn);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
try 
{
    startActivity(intent)
}catch(ActivityNotFoundException e){
    Toast.makeText(context,"Activity Not Found",Toast.LENGTH_SHORT).show()
}

If you must need other application, instead of showing Toast you can show a dialog. Using dialog you can bring the user to Play-Store to download required application.

Javascript Regular Expression Remove Spaces

I would recommend you use the literal notation, and the \s character class:

//..
return str.replace(/\s/g, '');
//..

There's a difference between using the character class \s and just ' ', this will match a lot more white-space characters, for example '\t\r\n' etc.., looking for ' ' will replace only the ASCII 32 blank space.

The RegExp constructor is useful when you want to build a dynamic pattern, in this case you don't need it.

Moreover, as you said, "[\s]+" didn't work with the RegExp constructor, that's because you are passing a string, and you should "double escape" the back-slashes, otherwise they will be interpreted as character escapes inside the string (e.g.: "\s" === "s" (unknown escape)).

Java Inheritance - calling superclass method

You can't call alpha's alphaMethod1() by using beta's object But you have two solutions:

solution 1: call alpha's alphaMethod1() from beta's alphaMethod1()

class Beta extends Alpha
{
  public void alphaMethod1()
  {
    super.alphaMethod1();
  }
}

or from any other method of Beta like:

class Beta extends Alpha
{
  public void foo()
  {
     super.alphaMethod1();
  }
}

class Test extends Beta 
{
   public static void main(String[] args)
   {
      Beta beta = new Beta();
      beta.foo();
   }
}

solution 2: create alpha's object and call alpha's alphaMethod1()

class Test extends Beta
{
   public static void main(String[] args)
   {
      Alpha alpha = new Alpha();
      alpha.alphaMethod1();
   }
}

Python SQL query string formatting

To avoid formatting entirely, I think a great solution is to use procedures.

Calling a procedure gives you the result of whatever query you want to put in this procedure. You can actually process multiple queries within a procedure. The call will just return the last query that was called.

MYSQL

DROP PROCEDURE IF EXISTS example;
 DELIMITER //
 CREATE PROCEDURE example()
   BEGIN
   SELECT 2+222+2222+222+222+2222+2222 AS this_is_a_really_long_string_test;
   END //
 DELIMITER;

#calling the procedure gives you the result of whatever query you want to put in this procedure. You can actually process multiple queries within a procedure. The call just returns the last query result
 call example;

Python

sql =('call example;')

how to set the background color of the whole page in css

I already wrote up the answer to this but it seems to have been deleted. The issue was that YUI added background-color:white to the HTML element. I overwrote that and everything was easy to handle from there.

shorthand If Statements: C#

Recently, I really enjoy shorthand if else statements as a swtich case replacement. In my opinion, this is better in read and take less place. Just take a look:

var redirectUrl =
      status == LoginStatusEnum.Success ? "/SecretPage"
    : status == LoginStatusEnum.Failure ? "/LoginFailed"
    : status == LoginStatusEnum.Sms ? "/2-StepSms"
    : status == LoginStatusEnum.EmailNotConfirmed ? "/EmailNotConfirmed"
    : "/404-Error";

instead of

string redirectUrl;
switch (status)
{
    case LoginStatusEnum.Success:
        redirectUrl = "/SecretPage";
        break;
    case LoginStatusEnum.Failure:
        redirectUrl = "/LoginFailed";
        break;
    case LoginStatusEnum.Sms:
        redirectUrl = "/2-StepSms";
        break;
    case LoginStatusEnum.EmailNotConfirmed:
        redirectUrl = "/EmailNotConfirmed";
        break;
    default:
        redirectUrl = "/404-Error";
        break;
}

Git error: src refspec master does not match any error: failed to push some refs

It doesn't recognize that you have a master branch, but I found a way to get around it. I found out that there's nothing special about a master branch, you can just create another branch and call it master branch and that's what I did.

To create a master branch:

git checkout -b master

And you can work off of that.

Objective-C for Windows

If you are comfortable with Visual Studio environment,

Small project: jGRASP with gcc Large project: Cocotron

I heard there are emulators, but I could find only Apple II Emulator http://virtualapple.org/. It looks like limited to games.

How to specify a port to run a create-react-app based project?

Just update a bit in webpack.config.js:

devServer: {
    historyApiFallback: true,
    contentBase: './',
    port: 3000 // <--- Add this line and choose your own port number
}

then run npm start again.

Javascript decoding html entities

var text = '&lt;p&gt;name&lt;/p&gt;&lt;p&gt;&lt;span style="font-size:xx-small;"&gt;ajde&lt;/span&gt;&lt;/p&gt;&lt;p&gt;&lt;em&gt;da&lt;/em&gt;&lt;/p&gt;';
var decoded = $('<textarea/>').html(text).text();
alert(decoded);

This sets the innerHTML of a new element (not appended to the page), causing jQuery to decode it into HTML, which is then pulled back out with .text().

Live demo.

How many threads can a Java VM support?

Maximum number of threads depends on following things:

  • Hardware Configuration like microprocessor, RAM.
  • Operating System like whether it is 32-bit or 64-bit
  • Code inside the run method. If code inside the run method is huge then single thread object will have more memory requirement
  • 'uint32_t' does not name a type

    I had tha same problem trying to compile a lib I download from the internet. In my case, there was already a #include <cstdint> in the code. I solved it adding a:

    using std::uint32_t;
    

    TestNG ERROR Cannot find class in classpath

    I ran into the same issue. Whenever I ran my test, it kept saying classes not found in the classpath. I tried to fix the testng.xml file, clean up the project and pretty much everything the answers say here, but none worked. Finally I checked my referenced libraries in build path and there were 34 invalid libraries, turns out I had renamed one of the folders from the path that I had taken the jar files from. I fixed the path and the test ran successfully.

    So it might be fruitful to check if there are any errors in the referenced jar files before trying the other methods to fix this issue.

    How do you make Git work with IntelliJ?

    For Linux users, check the value of GIT_HOME in your .env file in the home directory.

    1. Open terminal
    2. Type cd home/<username>/
    3. Open the .env file and check the value of GIT_HOME and select the git path appropriately

    PS: If you are not able to find the .env file, click on View on the formatting tool bar, select Show hidden files. You should be able to find the .env file now.

    Android emulator: could not get wglGetExtensionsStringARB error

    First of all, use INTEL x86... this as CPU/ABI. Secondly, uncheck Snapshot if it is checked. Keep the Target upto Android 4.2.2

    How to skip the OPTIONS preflight request?

    Preflight is a web security feature implemented by the browser. For Chrome you can disable all web security by adding the --disable-web-security flag.

    For example: "C:\Program Files\Google\Chrome\Application\chrome.exe" --disable-web-security --user-data-dir="C:\newChromeSettingsWithoutSecurity" . You can first create a new shortcut of chrome, go to its properties and change the target as above. This should help!

    Browserslist: caniuse-lite is outdated. Please run next command `npm update caniuse-lite browserslist`

    I did downgrade the node version from 12 to 10

    EDIT

    This error occurred with me because I was using node version 12. When I downgrade to version 10.16.5 this error stops. This error happened in my local env, but in prod and staging, it not happens. In prod and staging node version is 10.x so I just do this and I didn't need to update any package in my package.json

    How to my "exe" from PyCharm project

    You cannot directly save a Python file as an exe and expect it to work -- the computer cannot automatically understand whatever code you happened to type in a text file. Instead, you need to use another program to transform your Python code into an exe.

    I recommend using a program like Pyinstaller. It essentially takes the Python interpreter and bundles it with your script to turn it into a standalone exe that can be run on arbitrary computers that don't have Python installed (typically Windows computers, since Linux tends to come pre-installed with Python).

    To install it, you can either download it from the linked website or use the command:

    pip install pyinstaller
    

    ...from the command line. Then, for the most part, you simply navigate to the folder containing your source code via the command line and run:

    pyinstaller myscript.py
    

    You can find more information about how to use Pyinstaller and customize the build process via the documentation.


    You don't necessarily have to use Pyinstaller, though. Here's a comparison of different programs that can be used to turn your Python code into an executable.

    Good way of getting the user's location in Android

    Answering the first two points:

    • GPS will always give you a more precise location, if it is enabled and if there are no thick walls around.

    • If location did not change, then you can call getLastKnownLocation(String) and retrieve the location immediately.

    Using an alternative approach:

    You can try getting the cell id in use or all the neighboring cells

    TelephonyManager mTelephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
    GsmCellLocation loc = (GsmCellLocation) mTelephonyManager.getCellLocation(); 
    Log.d ("CID", Integer.toString(loc.getCid()));
    Log.d ("LAC", Integer.toString(loc.getLac()));
    // or 
    List<NeighboringCellInfo> list = mTelephonyManager.getNeighboringCellInfo ();
    for (NeighboringCellInfo cell : list) {
        Log.d ("CID", Integer.toString(cell.getCid()));
        Log.d ("LAC", Integer.toString(cell.getLac()));
    }
    

    You can refer then to cell location through several open databases (e.g., http://www.location-api.com/ or http://opencellid.org/ )


    The strategy would be to read the list of tower IDs when reading the location. Then, in next query (10 minutes in your app), read them again. If at least some towers are the same, then it's safe to use getLastKnownLocation(String). If they're not, then wait for onLocationChanged(). This avoids the need of a third party database for the location. You can also try this approach.

    How to delete a row from GridView?

    hi how to delete from datagridview

    1.make query delete by id
    2.type

    tabletableadaptor.delete
    query(datagridwiewX1.selectedrows[0].cell[0].value.tostring);
    

    Python subprocess.Popen "OSError: [Errno 12] Cannot allocate memory"

    Looking at the output of free -m it seems to me that you actually do not have swap memory available. I am not sure if in Linux the swap always will be available automatically on demand, but I was having the same problem and none of the answers here really helped me. Adding some swap memory however, fixed the problem in my case so since this might help other people facing the same problem, I post my answer on how to add a 1GB swap (on Ubuntu 12.04 but it should work similarly for other distributions.)

    You can first check if there is any swap memory enabled.

    $sudo swapon -s
    

    if it is empty, it means you don't have any swap enabled. To add a 1GB swap:

    $sudo dd if=/dev/zero of=/swapfile bs=1024 count=1024k
    $sudo mkswap /swapfile
    $sudo swapon /swapfile
    

    Add the following line to the fstab to make the swap permanent.

    $sudo vim /etc/fstab
    
         /swapfile       none    swap    sw      0       0 
    

    Source and more information can be found here.

    what's the differences between r and rb in fopen

    use "rb" to open a binary file. Then the bytes of the file won't be encoded when you read them

    Passing arguments to angularjs filters

    You can simply use | filter:yourFunction:arg

    <div ng-repeat="group in groups | filter:weDontLike:group">...</div>
    

    And in js

    $scope.weDontLike = function(group) {
    //here your condition/criteria
    return !!group 
    }
    

    Can't start hostednetwork

    I encountered this problem on my laptop. I found the solution for this problem.

    1. Test this command in the command prompt "netsh wlan show driver".
    2. See Hosted network supported.
    3. If it is no,

    Then do this

    1. Go to device manager.
    2. Click on view and press on "show hidden devices".
    3. Go down to the list of devices and expand the node "Network Devices" .
    4. Find an adapter with the name "Microsoft Hosted Network Virtual Adapter" and then right click on it.
    5. Select Enable
    6. This will enable the AdHoc created connection, it should appear in the network connections in Network and Sharing Center, if the AdHoc network connection is not appear then open elevated command prompt and apply this command "netsh wlan stop hostednetwork" without quotations.
    7. After this, the connection should appear. Then try starting your connection. It should work fine.

    Location of hibernate.cfg.xml in project?

    Using configure() method two times is responsible the problem for me. Instead of using like this :

        Configuration configuration = new Configuration().configure();
        configuration.configure("/main/resources/hibernate.cfg.xml");
    

    Now, I am using like this, problem does not exist anymore.

        Configuration configuration = new Configuration();
        configuration.configure("/main/resources/hibernate.cfg.xml");
    

    P.S: My hibernate.cfg.xml file is located at "src/main/resources/hibernate.cfg.xml",too. The code belove works for me. at hibernate-5

    public class HibernateUtil {
    
     private static SessionFactory sessionFactory ;
    
    
     static {
         try{
        Configuration configuration = new Configuration();
        configuration.configure("/main/resources/hibernate.cfg.xml");
        StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties());
        sessionFactory = configuration.buildSessionFactory(builder.build());
     }
         catch(Exception e){
             e.printStackTrace();
         }
         }
    
    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }
    }  
    

    SQL Server: Cannot insert an explicit value into a timestamp column

    You can't insert the values into timestamp column explicitly. It is auto-generated. Do not use this column in your insert statement. Refer http://msdn.microsoft.com/en-us/library/ms182776(SQL.90).aspx for more details.

    You could use a datetime instead of a timestamp like this:

    create table demo (
        ts datetime
    )
    
    insert into demo select current_timestamp
    
    select ts from demo
    

    Returns:

    2014-04-04 09:20:01.153
    

    Do Facebook Oauth 2.0 Access Tokens Expire?

    check the following things when you interact with facebook graph api.

    1) Application connect URL should be the base of your "redirect_uri" connect URL:- www.x-minds.org/fb/connect/ redirect_uri - www.x-minds.org/fb/connect/redirect 2) Your "redirect_uri" should be same in the both case (when you request for a verification code and request for an access_token) redirect_uri - www.x-minds.org/fb/connect/redirect 3) you should encode the the argument when you request for an access_token 4) shouldn't pass the argument (type=client_cred) when you request for an access_token. the authorization server will issue a token without session part. we can't use this token with "me" alias in graph api. This token will have length of (40) but a token with session part will have a length of(81). An access token without session part will work with some cases

    eg: -https://graph.facebook.com/?access_token=116122545078207|EyWJJYqrdgQgV1bfueck320z7MM. But Graph API with "me" alias will work with only token with session part.

    How to listen to route changes in react router v4?

    I just dealt with this problem, so I'll add my solution as a supplement on other answers given.

    The problem here is that useEffect doesn't really work as you would want it to, since the call only gets triggered after the first render so there is an unwanted delay.
    If you use some state manager like redux, chances are that you will get a flicker on the screen because of lingering state in the store.

    What you really want is to use useLayoutEffect since this gets triggered immediately.

    So I wrote a small utility function that I put in the same directory as my router:

    export const callApis = (fn, path) => {
        useLayoutEffect(() => {
          fn();
        }, [path]);
    };
    

    Which I call from within the component HOC like this:

    callApis(() => getTopicById({topicId}), path);
    

    path is the prop that gets passed in the match object when using withRouter.

    I'm not really in favour of listening / unlistening manually on history. That's just imo.

    Default Activity not found in Android Studio

    I ran into the same issue today and was going through the answers here.

    For me the difference was that yesterday it worked fine, so I figured it could not really be a configuration issue, neither configuration nor Version of Android Studio changed.

    Fortunately, I tried a restart of Android Studio before trying any of the other answers, and luckily that solved the issue.

    So for all people out there who run into this: first thing to try is to restart Android Studio and only if that does not solve the issue try the other answers here.

    Get checkbox value in jQuery

    Here is how to get the value of all checked checkboxes as an array:

    var values = (function() {
                    var a = [];
                    $(".checkboxes:checked").each(function() {
                        a.push(this.value);
                    });
                    return a;
                })()
    

    Could not load file or assembly or one of its dependencies. Access is denied. The issue is random, but after it happens once, it continues

    For me, the following hack worked; Go to IIS -> Application Pools -> Advance Settings -> Process Model -> Identity Changed from Built-in Account (ApplicationPoolIdentity) to Custom Account (My Domain User)

    Simple argparse example wanted: 1 argument, 3 results

    To add to what others have stated:

    I usually like to use the 'dest' parameter to specify a variable name and then use 'globals().update()' to put those variables in the global namespace.

    Usage:

    $ python script.py -i "Hello, World!"
    

    Code:

    ...
    parser.add_argument('-i', '--input', ..., dest='inputted_variable',...)
    globals().update(vars(parser.parse_args()))
    ...
    print(inputted_variable) # Prints "Hello, World!"
    

    1 = false and 0 = true?

    It is common for comparison functions to return 0 on "equals", so that they can also return a negative number for "less than" and a positive number for "greater than". strcmp() and memcmp() work like this.

    It is, however, idiomatic for zero to be false and nonzero to be true, because this is how the C flow control and logical boolean operators work. So it might be that the return values chosen for this function are fine, but it is the function's name that is in error (it should really just be called compare() or similar).

    Setting environment variables via launchd.conf no longer works in OS X Yosemite/El Capitan/macOS Sierra/Mojave?

    It is possible to set environment variables on Mac OS X 10.10 Yosemite with 3 files + 2 commands.

    Main file with environment variables definition:

    $ ls -la /etc/environment 
    -r-xr-xr-x  1 root  wheel  369 Oct 21 04:42 /etc/environment
    $ cat /etc/environment
    #!/bin/sh
    
    set -e
    
    syslog -s -l warn "Set environment variables with /etc/environment $(whoami) - start"
    
    launchctl setenv JAVA_HOME      /usr/local/jdk1.7
    launchctl setenv MAVEN_HOME     /opt/local/share/java/maven3
    
    if [ -x /usr/libexec/path_helper ]; then
        export PATH=""
        eval `/usr/libexec/path_helper -s`
        launchctl setenv PATH $PATH
    fi
    
    osascript -e 'tell app "Dock" to quit'
    
    syslog -s -l warn "Set environment variables with /etc/environment $(whoami) - complete"
    

    Service definition to load environment variables for user applications (terminal, IDE, ...):

    $ ls -la /Library/LaunchAgents/environment.user.plist
    -rw-------  1 root  wheel  504 Oct 21 04:37 /Library/LaunchAgents/environment.user.plist
    $ sudo cat /Library/LaunchAgents/environment.user.plist
    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
    <plist version="1.0">
    <dict>
        <key>Label</key>
        <string>environment.user</string>
        <key>ProgramArguments</key>
        <array>
                <string>/etc/environment</string>
        </array>
        <key>KeepAlive</key>
        <false/>
        <key>RunAtLoad</key>
        <true/>
        <key>WatchPaths</key>
        <array>
            <string>/etc/environment</string>
        </array>
    </dict>
    </plist>
    

    The same service definition for root user applications:

    $ ls -la /Library/LaunchDaemons/environment.plist
    -rw-------  1 root  wheel  499 Oct 21 04:38 /Library/LaunchDaemons/environment.plist
    $ sudo cat /Library/LaunchDaemons/environment.plist
    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
    <plist version="1.0">
    <dict>
        <key>Label</key>
        <string>environment</string>
        <key>ProgramArguments</key>
        <array>
                <string>/etc/environment</string>
        </array>
        <key>KeepAlive</key>
        <false/>
        <key>RunAtLoad</key>
        <true/>
        <key>WatchPaths</key>
        <array>
            <string>/etc/environment</string>
        </array>
    </dict>
    </plist>
    

    And finally we should register these services:

    $ launchctl load -w /Library/LaunchAgents/environment.user.plist
    $ sudo launchctl load -w /Library/LaunchDaemons/environment.plist
    

    What we get:

    1. The only place to declare system environment variables: /etc/environment
    2. Instant auto-update of environment variables after modification of /etc/environment file - just relaunch your application

    Issues / problems:

    In order your env variables were correctly taken by applications after system reboot you will need:

    • either login twice: login => logout => login
    • or close & re-open applications manually, where env variables should be taken
    • or do NOT use feature "Reopen windows when logging back".

    This happens due to Apple denies explicit ordering of loaded services, so env variables are registered in parallel with processing of the "reopen queue".

    But actually, I reboot my system only several times per year (on big updates), so it is not a big deal.

    C# - Print dictionary

    There's more than one way to skin this problem so here's my solution:

    1. Use Select() to convert the key-value pair to a string;
    2. Convert to a list of strings;
    3. Write out to the console using ForEach().
    dict.Select(i => $"{i.Key}: {i.Value}").ToList().ForEach(Console.WriteLine);
    

    Algorithm to return all combinations of k elements from n

    And here's a Clojure version that uses the same algorithm I describe in my OCaml implementation answer:

    (defn select
      ([items]
         (select items 0 (inc (count items))))
      ([items n1 n2]
         (reduce concat
                 (map #(select % items)
                      (range n1 (inc n2)))))
      ([n items]
         (let [
               lmul (fn [a list-of-lists-of-bs]
                         (map #(cons a %) list-of-lists-of-bs))
               ]
           (if (= n (count items))
             (list items)
             (if (empty? items)
               items
               (concat
                (select n (rest items))
                (lmul (first items) (select (dec n) (rest items))))))))) 
    

    It provides three ways to call it:

    (a) for exactly n selected items as the question demands:

      user=> (count (select 3 "abcdefgh"))
      56
    

    (b) for between n1 and n2 selected items:

    user=> (select '(1 2 3 4) 2 3)
    ((3 4) (2 4) (2 3) (1 4) (1 3) (1 2) (2 3 4) (1 3 4) (1 2 4) (1 2 3))
    

    (c) for between 0 and the size of the collection selected items:

    user=> (select '(1 2 3))
    (() (3) (2) (1) (2 3) (1 3) (1 2) (1 2 3))
    

    Getting selected value of a combobox

    Try this:

    private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
    {
        ComboBox cmb = (ComboBox)sender;
        int selectedIndex = cmb.SelectedIndex;
        int selectedValue = (int)cmb.SelectedValue;
    
        ComboboxItem selectedCar = (ComboboxItem)cmb.SelectedItem;
        MessageBox.Show(String.Format("Index: [{0}] CarName={1}; Value={2}", selectedIndex, selectedCar.Text, selecteVal));        
    }
    

    How to make a JSONP request from Javascript without JQuery?

    Lightweight example (with support for onSuccess and onTimeout). You need to pass callback name within URL if you need it.

    var $jsonp = (function(){
      var that = {};
    
      that.send = function(src, options) {
        var callback_name = options.callbackName || 'callback',
          on_success = options.onSuccess || function(){},
          on_timeout = options.onTimeout || function(){},
          timeout = options.timeout || 10; // sec
    
        var timeout_trigger = window.setTimeout(function(){
          window[callback_name] = function(){};
          on_timeout();
        }, timeout * 1000);
    
        window[callback_name] = function(data){
          window.clearTimeout(timeout_trigger);
          on_success(data);
        }
    
        var script = document.createElement('script');
        script.type = 'text/javascript';
        script.async = true;
        script.src = src;
    
        document.getElementsByTagName('head')[0].appendChild(script);
      }
    
      return that;
    })();
    

    Sample usage:

    $jsonp.send('some_url?callback=handleStuff', {
        callbackName: 'handleStuff',
        onSuccess: function(json){
            console.log('success!', json);
        },
        onTimeout: function(){
            console.log('timeout!');
        },
        timeout: 5
    });
    

    At GitHub: https://github.com/sobstel/jsonp.js/blob/master/jsonp.js

    Build Android Studio app via command line

    enter code hereCreate script file with below gradle and adb command, Execute script file

    ./gradlew clean
    

    ./gradlew assembleDebug ./gradlew installDebug

    adb shell am start -n applicationID/full path of launcher activity

    How do you remove a Cookie in a Java Servlet

    In my environment, following code works. Although looks redundant at first glance, cookies[i].setValue(""); and cookies[i].setPath("/"); are necessary to clear the cookie properly.

    private void eraseCookie(HttpServletRequest req, HttpServletResponse resp) {
        Cookie[] cookies = req.getCookies();
        if (cookies != null)
            for (Cookie cookie : cookies) {
                cookie.setValue("");
                cookie.setPath("/");
                cookie.setMaxAge(0);
                resp.addCookie(cookie);
            }
    }
    

    How do I print output in new line in PL/SQL?

    dbms_output.put_line('Hi,');
    dbms_output.put_line('good');
    dbms_output.put_line('morning');
    dbms_output.put_line('friends');
    

    or

    DBMS_OUTPUT.PUT_LINE('Hi, ' || CHR(13) || CHR(10) || 
                         'good' || CHR(13) || CHR(10) ||
                         'morning' || CHR(13) || CHR(10) ||
                         'friends' || CHR(13) || CHR(10) ||);
    

    try it.

    No Exception while type casting with a null in java

    This is by design. You can cast null to any reference type. Otherwise you wouldn't be able to assign it to reference variables.

    Calculate date/time difference in java

    Date startTime = new Date();
    //...
    //... lengthy jobs
    //...
    Date endTime = new Date();
    long diff = endTime.getTime() - startTime.getTime();
    String hrDateText = DurationFormatUtils.formatDuration(diff, "d 'day(s)' H 'hour(s)' m 'minute(s)' s 'second(s)' ");
    System.out.println("Duration : " + hrDateText);
    


    You can use Apache Commons Duration Format Utils. It formats like SimpleDateFormatter

    Output:

    0 days(s) 0 hour(s) 0 minute(s) 1 second(s)

    Could not resolve com.android.support:appcompat-v7:26.1.0 in Android Studio new project

    Your android studio may be forgot to put : buildToolsVersion "26.0.0" you need 'buildTools' to develop related design and java file. And if there is no any buildTools are installed in Android->sdk->build-tools directory then download first.

    Add new item in existing array in c#.net

    Very old question, but still wanted to add this.

    If you're looking for a one-liner, you can use the code below. It combines the list constructor that accepts an enumerable and the "new" (since question raised) initializer syntax.

    myArray = new List<string>(myArray) { "add this" }.ToArray();
    

    UEFA/FIFA scores API

    UEFA internally provides their own LIVEX Api for their Broadcasting Partners. That one is perfect enough to develop the Applications by their partners for themselves.

    instantiate a class from a variable in PHP?

    I would recommend the call_user_func() or call_user_func_arrayphp methods. You can check them out here (call_user_func_array , call_user_func).

    example

    class Foo {
    static public function test() {
        print "Hello world!\n";
    }
    }
    
     call_user_func('Foo::test');//FOO is the class, test is the method both separated by ::
     //or
     call_user_func(array('Foo', 'test'));//alternatively you can pass the class and method as an array
    

    If you have arguments you are passing to the method , then use the call_user_func_array() function.

    example.

    class foo {
    function bar($arg, $arg2) {
        echo __METHOD__, " got $arg and $arg2\n";
    }
    }
    
    // Call the $foo->bar() method with 2 arguments
    call_user_func_array(array("foo", "bar"), array("three", "four"));
    //or
    //FOO is the class, bar is the method both separated by ::
    call_user_func_array("foo::bar"), array("three", "four"));
    

    $(document).ready(function() is not working

    I found we need to use noConflict sometimes:

    jQuery.noConflict()(function ($) { // this was missing for me
        $(document).ready(function() { 
    
           other code here....
    
        });
    });
    

    From the docs:

    Many JavaScript libraries use $ as a function or variable name, just as jQuery does. In jQuery's case, $ is just an alias for jQuery, so all functionality is available without using $. If you need to use another JavaScript library alongside jQuery, return control of $ back to the other library with a call to $.noConflict(). Old references of $ are saved during jQuery initialization; noConflict() simply restores them.

    jQuery make global variable

    Your code looks fine except the possibility that if the variable declaration is inside a dom read handler then it will not be a global variable... it will be a closure variable

    jQuery(function(){
        //here it is a closure variable
        var a_href;
        $('sth a').on('click', function(e){
            a_href = $(this).attr('href');
    
              console.log(a_href);  
             //output is "home"
    
            e.preventDefault();
        }
    })
    

    To make the variable global, one solution is to declare the variable in global scope

    var a_href;
    jQuery(function(){
        $('sth a').on('click', function(e){
            a_href = $(this).attr('href');
    
              console.log(a_href);  
             //output is "home"
    
            e.preventDefault();
        }
    })
    

    another is to set the variable as a property of the window object

    window.a_href = $(this).attr('href')
    

    Why console printing undefined

    You are getting the output as undefined because even though the variable is declared, you have not initialized it with a value, the value of the variable is set only after the a element is clicked till that time the variable will have the value undefined. If you are not declaring the variable it will throw a ReferenceError

    How to add Python to Windows registry

    When installing Python 3.4 the "Add python.exe to Path" came up unselected. Re-installed with this selected and problem resolved.

    Fastest way to check a string is alphanumeric in Java

    A regex will probably be quite efficient, because you would specify ranges: [0-9a-zA-Z]. Assuming the implementation code for regexes is efficient, this would simply require an upper and lower bound comparison for each range. Here's basically what a compiled regex should do:

    boolean isAlphanumeric(String str) {
        for (int i=0; i<str.length(); i++) {
            char c = str.charAt(i);
            if (c < 0x30 || (c >= 0x3a && c <= 0x40) || (c > 0x5a && c <= 0x60) || c > 0x7a)
                return false;
        }
    
        return true;
    }
    

    I don't see how your code could be more efficient than this, because every character will need to be checked, and the comparisons couldn't really be any simpler.

    How can I find the version of php that is running on a distinct domain name?

    I suggest you much easier and platform independent solution to the problem - wappalyzer for Google Chrome:

    See here

    What is the "__v" field in Mongoose

    For remove in NestJS need to add option to Shema() decorator

    @Schema({ versionKey: false })
    

    Retrieve a Fragment from a ViewPager

    Hey I have answered this question here. Basically, you need to override

    public Object instantiateItem(ViewGroup container, int position)

    method of FragmentStatePagerAdapter.

    Why is semicolon allowed in this python snippet?

    Python does not require semi-colons to terminate statements. Semi colons can be used to delimit statements if you wish to put multiple statements on the same line.

    Now, why is this allowed? It's a simple design decision. I don't think Python needs this semi-colon thing, but somebody thought it would be nice to have and added it to the language.

    What's the difference between <b> and <strong>, <i> and <em>?

    You should generally try to avoid <b> and <i>. They were introduced for layouting the page (changing the way how it looks) in early HMTL versions prior to the creation of CSS, like the meanwhile removed font tag, and were mainly kept for backward compatibility and because some forums allow inline HTML and that's an easy way to change the look of text (like BBCode using [i], you can use <i> and so on).

    Since the creation of CSS, layouting is actually nothing that should be done in HTML anymore, that's why CSS has been created in the first place (HTML == Structure, CSS == Layout). These tags may as well vanish in the future, after all you can just use CSS and span tags to make text bold/italic if you need a "meaningless" font variation. HTML 5 still allows them but declares that marking text that way has no meaning.

    <em> and <strong> on the other hand only says that something is "emphasized" or "strongly emphasized", it leaves it completely open to the browser how to render it. Most browsers will render em as italic and strong as bold as the standard suggests by default, but they are not forced to do that (they may use different colors, font sizes, fonts, whatever). You can use CSS to change the behavior the way you desire. You can make em bold if you like and strong bold and red, for example.

    Python convert set to string and vice versa

    Try like this,

    >>> s = set([1,2,3])
    >>> s = list(s)
    >>> s
    [1, 2, 3]
    
    >>> str = ', '.join(str(e) for e in s)
    >>> str = 'set(%s)' % str
    >>> str
    'set(1, 2, 3)'
    

    What are the advantages and disadvantages of recursion?

    Any algorithm implemented using recursion can also be implemented using iteration.

    Why not to use recursion

    1. It is usually slower due to the overhead of maintaining the stack.
    2. It usually uses more memory for the stack.

    Why to use recursion

    1. Recursion adds clarity and (sometimes) reduces the time needed to write and debug code (but doesn't necessarily reduce space requirements or speed of execution).
    2. Reduces time complexity.
    3. Performs better in solving problems based on tree structures.

    For example, the Tower of Hanoi problem is more easily solved using recursion as opposed to iteration.

    Why maven settings.xml file is not there?

    The settings.xml file is not created by itself, you need to manually create it. Here is a sample:

      <settings xmlns="http://maven.apache.org/SETTINGS/1.0.0"
          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0
                              https://maven.apache.org/xsd/settings-1.0.0.xsd">
          <localRepository/>
          <interactiveMode/>
          <offline/>
          <pluginGroups/>
          <servers/>
          <mirrors/>
          <proxies/>
          <profiles/>
          <activeProfiles/>
       </settings>
    

    How to compare two java objects

    You need to provide your own implementation of equals() in MyClass.

    @Override
    public boolean equals(Object other) {
        if (!(other instanceof MyClass)) {
            return false;
        }
    
        MyClass that = (MyClass) other;
    
        // Custom equality check here.
        return this.field1.equals(that.field1)
            && this.field2.equals(that.field2);
    }
    

    You should also override hashCode() if there's any chance of your objects being used in a hash table. A reasonable implementation would be to combine the hash codes of the object's fields with something like:

    @Override
    public int hashCode() {
        int hashCode = 1;
    
        hashCode = hashCode * 37 + this.field1.hashCode();
        hashCode = hashCode * 37 + this.field2.hashCode();
    
        return hashCode;
    }
    

    See this question for more details on implementing a hash function.

    How to make an app's background image repeat

    // Prepared By Muhammad Mubashir.
    // 26, August, 2011.
    // Chnage Back Ground Image of Activity.
    
    package com.ChangeBg_01;
    
    import com.ChangeBg_01.R;
    
    import android.R.color;
    import android.app.Activity;
    import android.os.Bundle;
    import android.os.Handler;
    import android.view.View;
    import android.widget.ImageView;
    import android.widget.TextView;
    
    public class ChangeBg_01Activity extends Activity
    {
        TextView tv;
        int[] arr = new int[2];
        int i=0;
    
        /** Called when the activity is first created. */
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);
    
            tv = (TextView)findViewById(R.id.tv);
            arr[0] = R.drawable.icon1;
            arr[1] = R.drawable.icon;
    
         // Load a background for the current screen from a drawable resource
            //getWindow().setBackgroundDrawableResource(R.drawable.icon1) ;
    
            final Handler handler=new Handler();
            final Runnable r = new Runnable()
            {
                public void run() 
                {
                    //tv.append("Hello World");
                    if(i== 2){
                        i=0;            
                    }
    
                    getWindow().setBackgroundDrawableResource(arr[i]);
                    handler.postDelayed(this, 1000);
                    i++;
                }
            };
    
            handler.postDelayed(r, 1000);
            Thread thread = new Thread()
            {
                @Override
                public void run() {
                    try {
                        while(true) 
                        {
                            if(i== 2){
                                //finish();
                                i=0;
                            }
                            sleep(1000);
                            handler.post(r);
                            //i++;
                        }
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            };
    
    
        }
    }
    
    /*android:background="#FFFFFF"*/
    /*
    ImageView imageView = (ImageView) findViewById(R.layout.main);
    imageView.setImageResource(R.drawable.icon);*/
    
    // Now get a handle to any View contained 
    // within the main layout you are using
    /*        View someView = (View)findViewById(R.layout.main);
    
    // Find the root view
    View root = someView.getRootView();*/
    
    // Set the color
    /*root.setBackgroundColor(color.darker_gray);*/
    

    Using .text() to retrieve only text not nested in child tags

    isn't the code:

    var text  =  $('#listItem').clone().children().remove().end().text();
    

    just becoming jQuery for jQuery's sake? When simple operations involve that many chained commands & that much (unnecessary) processing, perhaps it is time to write a jQuery extension:

    (function ($) {
        function elementText(el, separator) {
            var textContents = [];
            for(var chld = el.firstChild; chld; chld = chld.nextSibling) {
                if (chld.nodeType == 3) { 
                    textContents.push(chld.nodeValue);
                }
            }
            return textContents.join(separator);
        }
        $.fn.textNotChild = function(elementSeparator, nodeSeparator) {
        if (arguments.length<2){nodeSeparator="";}
        if (arguments.length<1){elementSeparator="";}
            return $.map(this, function(el){
                return elementText(el,nodeSeparator);
            }).join(elementSeparator);
        }
    } (jQuery));
    

    to call:

    var text = $('#listItem').textNotChild();
    

    the arguments are in case a different scenario is encountered, such as

    <li>some text<a>more text</a>again more</li>
    <li>second text<a>more text</a>again more</li>
    
    var text = $("li").textNotChild(".....","<break>");
    

    text will have value:

    some text<break>again more.....second text<break>again more
    

    How can I delete multiple lines in vi?

    d5d "cuts" five lines

    I usually just throw the number in the middle like:

    d7l = delete 7 letters

    Deny all, allow only one IP through htaccess

    ErrorDocument 403 /maintenance.html
    Order Allow,Deny
    Allow from #:#:#:#:#:#
    
    

    For me, this seems to work (Using IPv6 rather than IPv4) I don't know if this is different for some websites but for mine this works.

    How to keep Docker container running after starting services?

    Make sure that you add daemon off; to you nginx.conf or run it with CMD ["nginx", "-g", "daemon off;"] as per the official nginx image

    Then use the following to run both supervisor as service and nginx as foreground process that will prevent the container from exiting

    service supervisor start && nginx

    In some cases you will need to have more than one process in your container, so forcing the container to have exactly one process won't work and can create more problems in deployment.

    So you need to understand the trade-offs and make your decision accordingly.

    ERROR 1452: Cannot add or update a child row: a foreign key constraint fails

    In my case the tables were perfectly consistent.

    Anyway I was getting this error because I created (by accident) more than one FK constraint on the same field.

    I run the following query to show all the keys:

    SELECT *
    FROM information_schema.table_constraints
    WHERE constraint_schema = 'my_db_name'
    

    and I deleted the wrong ones with the following query:

    ALTER TABLE my_table
    DROP FOREIGN KEY wrong_fk_constraint; 
    

    You can check it also running this query:

    SHOW CREATE TABLE my_table;
    

    Place API key in Headers or URL

    If you want an argument that might appeal to a boss: Think about what a URL is. URLs are public. People copy and paste them. They share them, they put them on advertisements. Nothing prevents someone (knowingly or not) from mailing that URL around for other people to use. If your API key is in that URL, everybody has it.

    How to Programmatically Add Views to Views

    Calling addView is the correct answer, but you need to do a little more than that to get it to work.

    If you create a View via a constructor (e.g., Button myButton = new Button();), you'll need to call setLayoutParams on the newly constructed view, passing in an instance of the parent view's LayoutParams inner class, before you add your newly constructed child to the parent view.

    For example, you might have the following code in your onCreate() function assuming your LinearLayout has id R.id.main:

    LinearLayout myLayout = findViewById(R.id.main);
    
    Button myButton = new Button(this);
    myButton.setLayoutParams(new LinearLayout.LayoutParams(
                                         LinearLayout.LayoutParams.MATCH_PARENT,
                                         LinearLayout.LayoutParams.MATCH_PARENT));
    
    myLayout.addView(myButton);
    

    Making sure to set the LayoutParams is important. Every view needs at least a layout_width and a layout_height parameter. Also getting the right inner class is important. I struggled with getting Views added to a TableRow to display properly until I figured out that I wasn't passing an instance of TableRow.LayoutParams to the child view's setLayoutParams.

    jQuery Validate Plugin - How to create a simple custom rule?

    You can create a simple rule by doing something like this:

    jQuery.validator.addMethod("greaterThanZero", function(value, element) {
        return this.optional(element) || (parseFloat(value) > 0);
    }, "* Amount must be greater than zero");
    

    And then applying this like so:

    $('validatorElement').validate({
        rules : {
            amount : { greaterThanZero : true }
        }
    });
    

    Just change the contents of the 'addMethod' to validate your checkboxes.

    R barplot Y-axis scale too short

    Simplest solution seems to be specifying the ylim range. Here is some code to do this automatically (left default, right - adjusted):

    # default y-axis
    barplot(dat, beside=TRUE)
    
    # automatically adjusted y-axis
    barplot(dat, beside=TRUE, ylim=range(pretty(c(0, dat))))
    

    img

    The trick is to use pretty() which returns a list of interval breaks covering all values of the provided data. It guarantees that the maximum returned value is 1) a round number 2) greater than maximum value in the data.

    In the example 0 was also added pretty(c(0, dat)) which makes sure that axis starts from 0.

    How to get a variable name as a string in PHP?

    You could use compact() to achieve this.

    $FooBar = "a string";
    
    $newArray = compact('FooBar');
    

    This would create an associative array with the variable name as the key. You could then loop through the array using the key name where you needed it.

    foreach($newarray as $key => $value) {
        echo $key;
    }
    

    In Java, how do I get the difference in seconds between 2 dates?

    Use this method:

    private Long secondsBetween(Date first, Date second){
        return (second.getTime() - first.getTime())/1000;
    }
    

    Pass multiple parameters to rest API - Spring

    Multiple parameters can be given like below,

        @RequestMapping(value = "/mno/{objectKey}", method = RequestMethod.GET, produces = "application/json")
        public List<String> getBook(HttpServletRequest httpServletRequest, @PathVariable(name = "objectKey") String objectKey
          , @RequestParam(value = "id", defaultValue = "false")String id,@RequestParam(value = "name", defaultValue = "false") String name) throws Exception {
                   //logic
    }
    

    Python recursive folder read

    This worked for me:

    import glob
    
    root_dir = "C:\\Users\\Scott\\" # Don't forget trailing (last) slashes    
    for filename in glob.iglob(root_dir + '**/*.jpg', recursive=True):
         print(filename)
         # do stuff
    

    jQuery UI Color Picker

    Perhaps I am very late, but as of now there's another way to use it using the jquery ui slider.

    Here's how its shown in the jquery ui docs:

    _x000D_
    _x000D_
    function hexFromRGB(r, g, b) {_x000D_
        var hex = [_x000D_
          r.toString( 16 ),_x000D_
          g.toString( 16 ),_x000D_
          b.toString( 16 )_x000D_
        ];_x000D_
        $.each( hex, function( nr, val ) {_x000D_
          if ( val.length === 1 ) {_x000D_
            hex[ nr ] = "0" + val;_x000D_
          }_x000D_
        });_x000D_
        return hex.join( "" ).toUpperCase();_x000D_
      }_x000D_
      function refreshSwatch() {_x000D_
        var red = $( "#red" ).slider( "value" ),_x000D_
          green = $( "#green" ).slider( "value" ),_x000D_
          blue = $( "#blue" ).slider( "value" ),_x000D_
          hex = hexFromRGB( red, green, blue );_x000D_
        $( "#swatch" ).css( "background-color", "#" + hex );_x000D_
      }_x000D_
      $(function() {_x000D_
        $( "#red, #green, #blue" ).slider({_x000D_
          orientation: "horizontal",_x000D_
          range: "min",_x000D_
          max: 255,_x000D_
          value: 127,_x000D_
          slide: refreshSwatch,_x000D_
          change: refreshSwatch_x000D_
        });_x000D_
        $( "#red" ).slider( "value", 255 );_x000D_
        $( "#green" ).slider( "value", 140 );_x000D_
        $( "#blue" ).slider( "value", 60 );_x000D_
      });
    _x000D_
    #red, #green, #blue {_x000D_
    float: left;_x000D_
    clear: left;_x000D_
    width: 300px;_x000D_
    margin: 15px;_x000D_
    }_x000D_
    #swatch {_x000D_
    width: 120px;_x000D_
    height: 100px;_x000D_
    margin-top: 18px;_x000D_
    margin-left: 350px;_x000D_
    background-image: none;_x000D_
    }_x000D_
    #red .ui-slider-range { background: #ef2929; }_x000D_
    #red .ui-slider-handle { border-color: #ef2929; }_x000D_
    #green .ui-slider-range { background: #8ae234; }_x000D_
    #green .ui-slider-handle { border-color: #8ae234; }_x000D_
    #blue .ui-slider-range { background: #729fcf; }_x000D_
    #blue .ui-slider-handle { border-color: #729fcf; }
    _x000D_
    <link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">_x000D_
    _x000D_
    <script src="//code.jquery.com/jquery-1.10.2.js"></script>_x000D_
    <script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>_x000D_
    <p class="ui-state-default ui-corner-all ui-helper-clearfix" style="padding:4px;">_x000D_
      <span class="ui-icon ui-icon-pencil" style="float:left; margin:-2px 5px 0 0;"></span>_x000D_
      Simple Colorpicker_x000D_
    </p>_x000D_
     _x000D_
    <div id="red"></div>_x000D_
    <div id="green"></div>_x000D_
    <div id="blue"></div>_x000D_
     _x000D_
    <div id="swatch" class="ui-widget-content ui-corner-all"></div>
    _x000D_
    _x000D_
    _x000D_

    Count indexes using "for" in Python

    Just use

    for i in range(0, 5):
        print i
    

    to iterate through your data set and print each value.

    For large data sets, you want to use xrange, which has a very similar signature, but works more effectively for larger data sets. http://docs.python.org/library/functions.html#xrange

    Is there a decorator to simply cache function return values?

    Ah, just needed to find the right name for this: "Lazy property evaluation".

    I do this a lot too; maybe I'll use that recipe in my code sometime.

    Should I use string.isEmpty() or "".equals(string)?

    I wrote a Tester class which can test the performance:

    public class Tester
    {
        public static void main(String[] args)
        {
            String text = "";
    
            int loopCount = 10000000;
            long startTime, endTime, duration1, duration2;
    
            startTime = System.nanoTime();
            for (int i = 0; i < loopCount; i++) {
                text.equals("");
            }
            endTime = System.nanoTime();
            duration1 = endTime - startTime;
            System.out.println(".equals(\"\") duration " +": \t" + duration1);
    
            startTime = System.nanoTime();
            for (int i = 0; i < loopCount; i++) {
                text.isEmpty();
            }
            endTime = System.nanoTime();
            duration2 = endTime - startTime;
            System.out.println(".isEmpty() duration "+": \t\t" + duration2);
    
            System.out.println("isEmpty() to equals(\"\") ratio: " + ((float)duration2 / (float)duration1));
        }
    }
    

    I found that using .isEmpty() took around half the time of .equals("").

    How to set image for bar button with swift?

    If you have set up your UIBarButtonItem with an image in the storyboard, one small hack to change the renderingMode is to add the following code to your viewDidLoad(). This way you don't have to resort to adding the entire button and image in code.

    if let navButton = self.navigationItem.leftBarButtonItem, let buttonImage = navButton.image {
        navButton.image = buttonImage.withRenderingMode(.alwaysOriginal)
    }
    

    Converting Python dict to kwargs?

    Use the double-star (aka double-splat?) operator:

    func(**{'type':'Event'})
    

    is equivalent to

    func(type='Event')
    

    How do I POST urlencoded form data with $http without jQuery?

    All of these look like overkill (or don't work)... just do this:

    $http.post(loginUrl, `username=${ encodeURIComponent(username) }` +
                         `&password=${ encodeURIComponent(password) }` +
                         '&grant_type=password'
    ).success(function (data) {
    

    Convert Map<String,Object> to Map<String,String>

    Now that we have Java 8/streams, we can add one more possible answer to the list:

    Assuming that each of the values actually are String objects, the cast to String should be safe. Otherwise some other mechanism for mapping the Objects to Strings may be used.

    Map<String,Object> map = new HashMap<>();
    Map<String,String> newMap = map.entrySet().stream()
         .collect(Collectors.toMap(Map.Entry::getKey, e -> (String)e.getValue()));
    

    How can I change column types in Spark SQL's DataFrame?

    Why not just do as described under http://spark.apache.org/docs/latest/api/python/pyspark.sql.html#pyspark.sql.Column.cast

    df.select(df.year.cast("int"),"make","model","comment","blank")
    

    Transfer data between iOS and Android via Bluetooth?

    Maybe a bit delayed, but technologies have evolved since so there is certainly new info around which draws fresh light on the matter...

    As iOS has yet to open up an API for WiFi Direct and Multipeer Connectivity is iOS only, I believe the best way to approach this is to use BLE, which is supported by both platforms (some better than others).

    On iOS a device can act both as a BLE Central and BLE Peripheral at the same time, on Android the situation is more complex as not all devices support the BLE Peripheral state. Also the Android BLE stack is very unstable (to date).

    If your use case is feature driven, I would suggest to look at Frameworks and Libraries that can achieve cross platform communication for you, without you needing to build it up from scratch.

    For example: http://p2pkit.io or google nearby

    Disclaimer: I work for Uepaa, developing p2pkit.io for Android and iOS.

    Tomcat 7 is not running on browser(http://localhost:8080/ )

    Many of us get this error after setting up the eclipse and server for first time. This solution is -

    1. go to server tab

    2. select the properties option of your respective server and expand it

    3. in the properties window , select general tab -> click Switch Location -> click apply ->click ok.

    This may work .

    How should strace be used?

    I liked some of the answers where it reads strace checks how you interacts with your operating system.

    This is exactly what we can see. The system calls. If you compare strace and ltrace the difference is more obvious.

    $>strace -c cd
    Desktop  Documents  Downloads  examples.desktop  Music  Pictures  Public  Templates  Videos
    % time     seconds  usecs/call     calls    errors syscall
    ------ ----------- ----------- --------- --------- ----------------
      0.00    0.000000           0         7           read
      0.00    0.000000           0         1           write
      0.00    0.000000           0        11           close
      0.00    0.000000           0        10           fstat
      0.00    0.000000           0        17           mmap
      0.00    0.000000           0        12           mprotect
      0.00    0.000000           0         1           munmap
      0.00    0.000000           0         3           brk
      0.00    0.000000           0         2           rt_sigaction
      0.00    0.000000           0         1           rt_sigprocmask
      0.00    0.000000           0         2           ioctl
      0.00    0.000000           0         8         8 access
      0.00    0.000000           0         1           execve
      0.00    0.000000           0         2           getdents
      0.00    0.000000           0         2         2 statfs
      0.00    0.000000           0         1           arch_prctl
      0.00    0.000000           0         1           set_tid_address
      0.00    0.000000           0         9           openat
      0.00    0.000000           0         1           set_robust_list
      0.00    0.000000           0         1           prlimit64
    ------ ----------- ----------- --------- --------- ----------------
    100.00    0.000000                    93        10 total
    

    On the other hand there is ltrace that traces functions.

    $>ltrace -c cd
    Desktop  Documents  Downloads  examples.desktop  Music  Pictures  Public  Templates  Videos
    % time     seconds  usecs/call     calls      function
    ------ ----------- ----------- --------- --------------------
     15.52    0.004946         329        15 memcpy
     13.34    0.004249          94        45 __ctype_get_mb_cur_max
     12.87    0.004099        2049         2 fclose
     12.12    0.003861          83        46 strlen
     10.96    0.003491         109        32 __errno_location
     10.37    0.003303         117        28 readdir
      8.41    0.002679         133        20 strcoll
      5.62    0.001791         111        16 __overflow
      3.24    0.001032         114         9 fwrite_unlocked
      1.26    0.000400         100         4 __freading
      1.17    0.000372          41         9 getenv
      0.70    0.000222         111         2 fflush
      0.67    0.000214         107         2 __fpending
      0.64    0.000203         101         2 fileno
      0.62    0.000196         196         1 closedir
      0.43    0.000138         138         1 setlocale
      0.36    0.000114         114         1 _setjmp
      0.31    0.000098          98         1 realloc
      0.25    0.000080          80         1 bindtextdomain
      0.21    0.000068          68         1 opendir
      0.19    0.000062          62         1 strrchr
      0.18    0.000056          56         1 isatty
      0.16    0.000051          51         1 ioctl
      0.15    0.000047          47         1 getopt_long
      0.14    0.000045          45         1 textdomain
      0.13    0.000042          42         1 __cxa_atexit
    ------ ----------- ----------- --------- --------------------
    100.00    0.031859                   244 total
    

    Although I checked the manuals several time, I haven't found the origin of the name strace but it is likely system-call trace, since this is obvious.

    There are three bigger notes to say about strace.

    Note 1: Both these functions strace and ltrace are using the system call ptrace. So ptrace system call is effectively how strace works.

    The ptrace() system call provides a means by which one process (the "tracer") may observe and control the execution of another process (the "tracee"), and examine and change the tracee's memory and registers. It is primarily used to implement breakpoint debugging and system call tracing.

    Note 2: There are different parameters you can use with strace, since strace can be very verbose. I like to experiment with -c which is like a summary of things. Based on -c you can select one system-call like -e trace=open where you will see only that call. This can be interesting if you are examining what files will be opened during the command you are tracing. And of course, you can use the grep for the same purpose but note you need to redirect like this 2>&1 | grep etc to understand that config files are referenced when the command was issued.

    Note 3: I find this very important note. You are not limited to a specific architecture. strace will blow you mind, since it can trace over binaries of different architectures. enter image description here

    How can I get the current array index in a foreach loop?

    You could get the first element in the array_keys() function as well. Or array_search() the keys for the "index" of a key. If you are inside a foreach loop, the simple incrementing counter (suggested by kip or cletus) is probably your most efficient method though.

    <?php
       $array = array('test', '1', '2');
       $keys = array_keys($array);
       var_dump($keys[0]); // int(0)
    
       $array = array('test'=>'something', 'test2'=>'something else');
       $keys = array_keys($array);
    
       var_dump(array_search("test2", $keys)); // int(1)     
       var_dump(array_search("test3", $keys)); // bool(false)
    

    issue ORA-00001: unique constraint violated coming in INSERT/UPDATE

    The error message will include the name of the constraint that was violated (there may be more than one unique constraint on a table). You can use that constraint name to identify the column(s) that the unique constraint is declared on

    SELECT column_name, position
      FROM all_cons_columns
     WHERE constraint_name = <<name of constraint from the error message>>
       AND owner           = <<owner of the table>>
       AND table_name      = <<name of the table>>
    

    Once you know what column(s) are affected, you can compare the data you're trying to INSERT or UPDATE against the data already in the table to determine why the constraint is being violated.

    How to trace the path in a Breadth-First Search?

    I liked qiao's first answer very much! The only thing missing here is to mark the vertexes as visited.

    Why we need to do it?
    Lets imagine that there is another node number 13 connected from node 11. Now our goal is to find node 13.
    After a little bit of a run the queue will look like this:

    [[1, 2, 6], [1, 3, 10], [1, 4, 7], [1, 4, 8], [1, 2, 5, 9], [1, 2, 5, 10]]
    

    Note that there are TWO paths with node number 10 at the end.
    Which means that the paths from node number 10 will be checked twice. In this case it doesn't look so bad because node number 10 doesn't have any children.. But it could be really bad (even here we will check that node twice for no reason..)
    Node number 13 isn't in those paths so the program won't return before reaching to the second path with node number 10 at the end..And we will recheck it..

    All we are missing is a set to mark the visited nodes and not to check them again..
    This is qiao's code after the modification:

    graph = {
        1: [2, 3, 4],
        2: [5, 6],
        3: [10],
        4: [7, 8],
        5: [9, 10],
        7: [11, 12],
        11: [13]
    }
    
    
    def bfs(graph_to_search, start, end):
        queue = [[start]]
        visited = set()
    
        while queue:
            # Gets the first path in the queue
            path = queue.pop(0)
    
            # Gets the last node in the path
            vertex = path[-1]
    
            # Checks if we got to the end
            if vertex == end:
                return path
            # We check if the current node is already in the visited nodes set in order not to recheck it
            elif vertex not in visited:
                # enumerate all adjacent nodes, construct a new path and push it into the queue
                for current_neighbour in graph_to_search.get(vertex, []):
                    new_path = list(path)
                    new_path.append(current_neighbour)
                    queue.append(new_path)
    
                # Mark the vertex as visited
                visited.add(vertex)
    
    
    print bfs(graph, 1, 13)
    

    The output of the program will be:

    [1, 4, 7, 11, 13]
    

    Without the unneccecery rechecks..

    sql delete statement where date is greater than 30 days

    Use DATEADD in your WHERE clause:

    ...
    WHERE date < DATEADD(day, -30, GETDATE())
    

    You can also use abbreviation d or dd instead of day.

    PHP fwrite new line

    You append a newline to both the username and the password, i.e. the output would be something like

    Sebastian
    password
    John
    hfsjaijn
    

    use fwrite($fh,$user." ".$password."\n"); instead to have them both on one line.
    Or use fputcsv() to write the data and fgetcsv() to fetch it. This way you would at least avoid encoding problems like e.g. with $username='Charles, III';

    ...i.e. setting aside all the things that are wrong about storing plain passwords in plain files and using _GET for this type of operation (use _POST instead) ;-)

    The target principal name is incorrect. Cannot generate SSPI context

    I have tried all the solutions here and none of them have worked yet. A workaround that is working is to Click Connect, enter the server name, select Options, Connection Properties tab. Set the "Network protocol" to "Named Pipes". This allows users to remote connect using their network credentials. I'll post an update when I get a fix.

    How to select where ID in Array Rails ActiveRecord without exception

    Update: This answer is more relevant for Rails 4.x

    Do this:

    current_user.comments.where(:id=>[123,"456","Michael Jackson"])
    

    The stronger side of this approach is that it returns a Relation object, to which you can join more .where clauses, .limit clauses, etc., which is very helpful. It also allows non-existent IDs without throwing exceptions.

    The newer Ruby syntax would be:

    current_user.comments.where(id: [123, "456", "Michael Jackson"])
    

    Search and get a line in Python

    With regular expressions

    import re
    s="""
        qwertyuiop
        asdfghjkl
    
        zxcvbnm
        token qwerty
    
        asdfghjklñ
    """
    >>> items=re.findall("token.*$",s,re.MULTILINE)
    >>> for x in items:
    ...     print x
    ...
    token qwerty
    

    How to git clone a specific tag

    Use the command

    git clone --help
    

    to see whether your git supports the command

    git clone --branch tag_name
    

    If not, just do the following:

    git clone repo_url 
    cd repo
    git checkout tag_name
    

    Android: why is there no maxHeight for a View?

    If anyone is considering using exact value for LayoutParams e.g.

    setLayoutParams(new LayoutParams(Y, X );
    

    Do remember to take into account the density of the device display otherwise you might get very odd behaviour on different devices. E.g:

    Display display = getWindowManager().getDefaultDisplay();
    DisplayMetrics d = new DisplayMetrics();
    display.getMetrics(d);
    setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, (int)(50*d.density) ));
    

    Installing jdk8 on ubuntu- "unable to locate package" update doesn't fix

    If you get a

    sudo: add-apt-repository: command not found

    then you need to run the following command

    sudo apt-get install software-properties-common python-software-properties

    How to place object files in separate subdirectory

    In general, you either have to specify $(OBJDIR) on the left hand side of all the rules that place files in $(OBJDIR), or you can run make from $(OBJDIR). VPATH is for sources, not for objects.

    Take a look at these two links for more explanation, and a "clever" workaround.

    What is the meaning of prepended double colon "::"?

    :: is a operator of defining the namespace.

    For example, if you want to use cout without mentioning using namespace std; in your code you write this:

    std::cout << "test";
    

    When no namespace is mentioned, that it is said that class belongs to global namespace.

    Instance member cannot be used on type

    Just in case someone really needs a closure like that, it can be done in the following way:

    var categoriesPerPage = [[Int]]()
    var numPagesClosure: ()->Int {
        return {
            return self.categoriesPerPage.count
        }
    }
    

    How to drop all stored procedures at once in SQL Server database?

    To get drop statements for all stored procedures in a database SELECT 'DROP PROCEDURE' + ' ' + F.NAME + ';' FROM SYS.objects AS F where type='P'

    Error 5 : Access Denied when starting windows service

    if you are a having an access denied error code 5. then probably in your code your service is trying to interact with some files in the system like writing to a log file

    open the services properties select log on tab and check option to allow service to interact with the desktop, click allow service to interact with desktop

    How can I bring my application window to the front?

    Before stumbling onto this post, I came up with this solution - to toggle the TopMost property:

    this.TopMost = true;
    this.TopMost = false;
    

    I have this code in my form's constructor, eg:

    public MyForm()
    {
        //...
    
        // Brint-to-front hack
        this.TopMost = true;
        this.TopMost = false;
    
        //...
    }
    

    How to change status bar color in Flutter?

    This one will also work

    SystemChrome.setSystemUIOverlayStyle(SystemUiOverlayStyle.dark);
    SystemChrome.setSystemUIOverlayStyle(SystemUiOverlayStyle.light);
    

    Compare and contrast REST and SOAP web services?

    SOAP uses WSDL for communication btw consumer and provider, whereas REST just uses XML or JSON to send and receive data

    WSDL defines contract between client and service and is static by its nature. In case of REST contract is somewhat complicated and is defined by HTTP, URI, Media Formats and Application Specific Coordination Protocol. It's highly dynamic unlike WSDL.

    SOAP doesn't return human readable result, whilst REST result is readable with is just plain XML or JSON

    This is not true. Plain XML or JSON are not RESTful at all. None of them define any controls(i.e. links and link relations, method information, encoding information etc...) which is against REST as far as messages must be self contained and coordinate interaction between agent/client and service.

    With links + semantic link relations clients should be able to determine what is next interaction step and follow these links and continue communication with service.

    It is not necessary that messages be human readable, it's possible to use cryptic format and build perfectly valid REST applications. It doesn't matter whether message is human readable or not.

    Thus, plain XML(application/xml) or JSON(application/json) are not sufficient formats for building REST applications. It's always reasonable to use subset of these generic media types which have strong semantic meaning and offer enough control information(links etc...) to coordinate interactions between client and server.

    REST is over only HTTP

    Not true, HTTP is most widely used and when we talk about REST web services we just assume HTTP. HTTP defines interface with it's methods(GET, POST, PUT, DELETE, PATCH etc) and various headers which can be used uniformly for interacting with resources. This uniformity can be achieved with other protocols as well.

    P.S. Very simple, yet very interesting explanation of REST: http://www.looah.com/source/view/2284

    How to create Select List for Country and States/province in MVC

    So many ways to do this... for #NetCore use Lib..

        using System;
        using System.Collections.Generic;
        using System.Linq; // only required when .AsEnumerable() is used
        using System.ComponentModel.DataAnnotations;
        using Microsoft.AspNetCore.Mvc.Rendering;
    

    Model...

    namespace MyProject.Models
    {
      public class MyModel
      {
        [Required]
        [Display(Name = "State")]
        public string StatePick { get; set; }
        public string state { get; set; }
        [StringLength(35, ErrorMessage = "State cannot be longer than 35 characters.")]
        public SelectList StateList { get; set; }
      }
    }
    

    Controller...

    namespace MyProject.Controllers
    {
        /// <summary>
        /// create SelectListItem from strings
        /// </summary>
        /// <param name="isValue">defaultValue is SelectListItem.Value is true, SelectListItem.Text if false</param>
        /// <returns></returns>
        private SelectListItem newItem(string value, string text, string defaultValue = "", bool isValue = false)
        {
            SelectListItem ss = new SelectListItem();
            ss.Text = text;
            ss.Value = value;
    
            // select default by Value or Text
            if (isValue && ss.Value == defaultValue || !isValue && ss.Text == defaultValue)
            {
                ss.Selected = true;
            }
    
            return ss;
        }
    
        /// <summary>
        /// this pulls the state name from _context and sets it as the default for the selectList
        /// </summary>
        /// <param name="myState">sets default value for list of states</param>
        /// <returns></returns>
        private SelectList getStateList(string myState = "")
        {
            List<SelectListItem> states = new List<SelectListItem>();
            SelectListItem chosen = new SelectListItem();
    
            // set default selected state to OHIO
            string defaultValue = "OH";
            if (!string.IsNullOrEmpty(myState))
            {
                defaultValue = myState;
            }
    
            try
            {
                states.Add(newItem("AL", "Alabama", defaultValue, true));
                states.Add(newItem("AK", "Alaska", defaultValue, true));
                states.Add(newItem("AZ", "Arizona", defaultValue, true));
                states.Add(newItem("AR", "Arkansas", defaultValue, true));
                states.Add(newItem("CA", "California", defaultValue, true));
                states.Add(newItem("CO", "Colorado", defaultValue, true));
                states.Add(newItem("CT", "Connecticut", defaultValue, true));
                states.Add(newItem("DE", "Delaware", defaultValue, true));
                states.Add(newItem("DC", "District of Columbia", defaultValue, true));
                states.Add(newItem("FL", "Florida", defaultValue, true));
                states.Add(newItem("GA", "Georgia", defaultValue, true));
                states.Add(newItem("HI", "Hawaii", defaultValue, true));
                states.Add(newItem("ID", "Idaho", defaultValue, true));
                states.Add(newItem("IL", "Illinois", defaultValue, true));
                states.Add(newItem("IN", "Indiana", defaultValue, true));
                states.Add(newItem("IA", "Iowa", defaultValue, true));
                states.Add(newItem("KS", "Kansas", defaultValue, true));
                states.Add(newItem("KY", "Kentucky", defaultValue, true));
                states.Add(newItem("LA", "Louisiana", defaultValue, true));
                states.Add(newItem("ME", "Maine", defaultValue, true));
                states.Add(newItem("MD", "Maryland", defaultValue, true));
                states.Add(newItem("MA", "Massachusetts", defaultValue, true));
                states.Add(newItem("MI", "Michigan", defaultValue, true));
                states.Add(newItem("MN", "Minnesota", defaultValue, true));
                states.Add(newItem("MS", "Mississippi", defaultValue, true));
                states.Add(newItem("MO", "Missouri", defaultValue, true));
                states.Add(newItem("MT", "Montana", defaultValue, true));
                states.Add(newItem("NE", "Nebraska", defaultValue, true));
                states.Add(newItem("NV", "Nevada", defaultValue, true));
                states.Add(newItem("NH", "New Hampshire", defaultValue, true));
                states.Add(newItem("NJ", "New Jersey", defaultValue, true));
                states.Add(newItem("NM", "New Mexico", defaultValue, true));
                states.Add(newItem("NY", "New York", defaultValue, true));
                states.Add(newItem("NC", "North Carolina", defaultValue, true));
                states.Add(newItem("ND", "North Dakota", defaultValue, true));
                states.Add(newItem("OH", "Ohio", defaultValue, true));
                states.Add(newItem("OK", "Oklahoma", defaultValue, true));
                states.Add(newItem("OR", "Oregon", defaultValue, true));
                states.Add(newItem("PA", "Pennsylvania", defaultValue, true));
                states.Add(newItem("RI", "Rhode Island", defaultValue, true));
                states.Add(newItem("SC", "South Carolina", defaultValue, true));
                states.Add(newItem("SD", "South Dakota", defaultValue, true));
                states.Add(newItem("TN", "Tennessee", defaultValue, true));
                states.Add(newItem("TX", "Texas", defaultValue, true));
                states.Add(newItem("UT", "Utah", defaultValue, true));
                states.Add(newItem("VT", "Vermont", defaultValue, true));
                states.Add(newItem("VA", "Virginia", defaultValue, true));
                states.Add(newItem("WA", "Washington", defaultValue, true));
                states.Add(newItem("WV", "West Virginia", defaultValue, true));
                states.Add(newItem("WI", "Wisconsin", defaultValue, true));
                states.Add(newItem("WY", "Wyoming", defaultValue, true));
    
                foreach (SelectListItem state in states)
                {
                    if (state.Selected)
                    {
                        chosen = state;
                        break;
                    }
                }
            }
            catch (Exception err)
            {
                string ss = "ERR!   " + err.Source + "   " + err.GetType().ToString() + "\r\n" + err.Message.Replace("\r\n", "   ");
                ss = this.sendError("Online getStateList Request", ss, _errPassword);
                // return error
            }
    
            // .AsEnumerable() is not required in the pass.. it is an extension of Linq
            SelectList myList = new SelectList(states.AsEnumerable(), "Value", "Text", chosen);
    
            object val = myList.SelectedValue;
    
            return myList;
        }
    
        public ActionResult pickState(MyModel pData)
        {
            if (pData.StateList == null)
            {
                if (String.IsNullOrEmpty(pData.StatePick)) // state abbrev, value collected onchange
                {
                    pData.StateList = getStateList();
                }
                else
                {
                    pData.StateList = getStateList(pData.StatePick);
                }
    
                // assign values to state list items
                try
                {
                    SelectListItem si = (SelectListItem)pData.StateList.SelectedValue;
                    pData.state = si.Value;
                    pData.StatePick = si.Value;
                }
                catch { }
            } 
        return View(pData);
        }
    }
    

    pickState.cshtml...

    @model MyProject.Models.MyModel
    
    @{
    ViewBag.Title = "United States of America";
    Layout = "~/Views/Shared/_Layout.cshtml";
    }
    <h2>@ViewBag.Title - Where are you...</h2>
    
    @using (Html.BeginForm()) {
    @Html.AntiForgeryToken()
    @Html.ValidationSummary(true)
    
    <fieldset>
    
        <div class="editor-label">
            @Html.DisplayNameFor(model => model.state)
        </div>
        <div class="display-field">            
            @Html.DropDownListFor(m => m.StatePick, Model.StateList, new { OnChange = "state.value = this.value;" })
            @Html.EditorFor(model => model.state)
            @Html.ValidationMessageFor(model => model.StateList)
        </div>         
    </fieldset>
    }
    
    <div>
    @Html.ActionLink("Back to List", "Index")
    </div>
    

    "Fatal error: Unable to find local grunt." when running "grunt" command

    if you are a exists project, maybe should execute npm install.

    guntjs getting started step 2.

    Spring Security exclude url patterns in security annotation configurartion

    When you say adding antMatchers doesnt help - what do you mean? antMatchers is exactly how you do it. Something like the following should work (obviously changing your URL appropriately):

    @Override
        public void configure(HttpSecurity http) throws Exception {
            http.authorizeRequests()
                    .antMatchers("/authFailure").permitAll()
                    .antMatchers("/resources/**").permitAll()
                    .anyRequest().authenticated()
    

    If you are still not having any joy, then you will need to provide more details/stacktrace etc.

    Details of XML to Java config switch is here

    SQL WHERE condition is not equal to?

    I was just solving this problem. If you use <> or is not in on a variable, that is null, it will result in false. So instead of <> 1, you must check it like this:

     AND (isdelete is NULL or isdelete = 0)
    

    YouTube URL in Video Tag

    The most straight forward answer to this question is: You can't.

    Youtube doesn't output their video's in the right format, thus they can't be embedded in a
    <video/> element.

    There are a few solutions posted using javascript, but don't trust on those, they all need a fallback, and won't work cross-browser.

    How do I disable Git Credential Manager for Windows?

    and if :wq doesn't work like my case use ctrl+z for abort and quit but these will probably make multiple backup file to work with later – Adeem Jan 19 at 9:14

    Also be sure to run Git as Administrator! Otherwise the file won't be saved (in my case).

    Easy way to export multiple data.frame to multiple Excel worksheets

    You can also use the openxlsx library to export multiple datasets to multiple sheets in a single workbook.The advantage of openxlsx over xlsx is that openxlsx removes the dependencies on java libraries.

    Write a list of data.frames to individual worksheets using list names as worksheet names.

    require(openxlsx)
    list_of_datasets <- list("Name of DataSheet1" = dataframe1, "Name of Datasheet2" = dataframe2)
    write.xlsx(list_of_datasets, file = "writeXLSX2.xlsx")
    

    How do I get IntelliJ to recognize common Python modules?

    I got it to work after I unchecked the following options in the Run/Debug Configurations for main.py

    Add content roots to PYTHONPATH

    Add source roots to PYTHONPATH

    This is after I had invalidated the cache and restarted.

    Convert 24 Hour time to 12 Hour plus AM/PM indication Oracle SQL

    For the 24-hour time, you need to use HH24 instead of HH.

    For the 12-hour time, the AM/PM indicator is written as A.M. (if you want periods in the result) or AM (if you don't). For example:

    SELECT invoice_date,
           TO_CHAR(invoice_date, 'DD-MM-YYYY HH24:MI:SS') "Date 24Hr",
           TO_CHAR(invoice_date, 'DD-MM-YYYY HH:MI:SS AM') "Date 12Hr"
      FROM invoices
    ;
    

    For more information on the format models you can use with TO_CHAR on a date, see http://docs.oracle.com/cd/E16655_01/server.121/e17750/ch4datetime.htm#NLSPG004.

    Getting "TypeError: failed to fetch" when the request hasn't actually failed

    Note that there is an unrelated issue in your code but that could bite you later: you should return res.json() or you will not catch any error occurring in JSON parsing or your own function processing data.

    Back to your error: You cannot have a TypeError: failed to fetch with a successful request. You probably have another request (check your "network" panel to see all of them) that breaks and causes this error to be logged. Also, maybe check "Preserve log" to be sure the panel is not cleared by any indelicate redirection. Sometimes I happen to have a persistent "console" panel, and a cleared "network" panel that leads me to have error in console which is actually unrelated to the visible requests. You should check that.

    Or you (but that would be vicious) actually have a hardcoded console.log('TypeError: failed to fetch') in your final .catch ;) and the error is in reality in your .then() but it's hard to believe.

    How to remove focus from single editText

    Just find another view and give it focus instead.

    var refresher = FindViewById<MvxSwipeRefreshLayout>(Resource.Id.refresher);
    
    refresher.RequestFocus();
    

    How to set minDate to current date in jQuery UI Datepicker?

    minDate property for current date works on for both -> minDate:"yy-mm-dd" or minDate:0

    node.js Error: connect ECONNREFUSED; response from server

    I got this error because my AdonisJS server was not running before I ran the test. Running the server first fixed it.

    Unable to find the wrapper "https" - did you forget to enable it when you configured PHP?

    For those using Winginx (nginx based instead of Apache based), I fixed it with these 4 steps:

    1. On the Tools menu hit the Winginx PHP5 Config (never mind the 5 in the name...):

      Winginx PHP5 Config

    2. Select the PHP version you want the php.ini to change:

      PHP version selection

    3. On the PHP Extensions tab select the php_openssl extension and hit the Save button:

      php_openssl selection

    4. restart the appropriate PHP service through the taskbar (Stop and Start):

      Restart PHP service

    Where is Ubuntu storing installed programs?

    If you installed the package with the Ubuntu package manager (apt, synaptic, dpkg or similar), you can get information about the installed package with

    dpkg -L <package_name>
    

    AppFabric installation failed because installer MSI returned with error code : 1603

    For me the following method worked, Firstly ensure that windows update service is running from services.msc or you can run this command in an administrator Command Prompt -

    net start wuauserv
    

    Next edit the following registry from regedit -> HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\InetStp -> MajorVersion -> Change this value from 10 to 9.

    Then try installing the AppFabric and it should work. Note :- revert back to registry value changes you made to ensure there are no problems in future if any.

    What's NSLocalizedString equivalent in Swift?

    Actually, you can use two phases to translate your texts in Swift projects:

    1) The first phase is using the old way to create all your translatable strings:

    NSLocalisedString("Text to translate", comment: "Comment to comment")
    

    1.1) Then you should use genstrings to generate Localizable.strings:

    $ genstrings *swift
    

    2) Afterwards, you should use this answer.

    2.1) Use your XCode "Find and Replace" option based on the regular expression. As for the given example (if you have no comments) the regular expression will be:

    NSLocalizedString\((.*)\, comment:\ \"\"\) 
    

    and replace it with

    $1.localized
    

    or (if you have comments)

    NSLocalizedString\((.*)\, comment:\ (.*)\)
    

    and replace it with

    $1.localizedWithComment(comment: $2)
    

    You are free to play with regex and different extension combinations as you wish. The general way is splitting the whole process in two phases. Hope that helps.

    Calling async method on button click

    You're the victim of the classic deadlock. task.Wait() or task.Result is a blocking call in UI thread which causes the deadlock.

    Don't block in the UI thread. Never do it. Just await it.

    private async void Button_Click(object sender, RoutedEventArgs 
    {
          var task = GetResponseAsync<MyObject>("my url");
          var items = await task;
    }
    

    Btw, why are you catching the WebException and throwing it back? It would be better if you simply don't catch it. Both are same.

    Also I can see you're mixing the asynchronous code with synchronous code inside the GetResponse method. StreamReader.ReadToEnd is a blocking call --you should be using StreamReader.ReadToEndAsync.

    Also use "Async" suffix to methods which returns a Task or asynchronous to follow the TAP("Task based Asynchronous Pattern") convention as Jon says.

    Your method should look something like the following when you've addressed all the above concerns.

    public static async Task<List<T>> GetResponseAsync<T>(string url)
    {
        HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
        var response = (HttpWebResponse)await Task.Factory.FromAsync<WebResponse>(request.BeginGetResponse, request.EndGetResponse, null);
    
        Stream stream = response.GetResponseStream();
        StreamReader strReader = new StreamReader(stream);
        string text = await strReader.ReadToEndAsync();
    
        return JsonConvert.DeserializeObject<List<T>>(text);
    }
    

    Laravel, sync() - how to sync an array and also pass additional pivot fields?

    Putting this here in case I forget it later and Google it again.

    In my case I wanted the extra column to have the same data for each row

    Where $syncData is an array of IDs:

    $syncData = array_map(fn($locationSysid) => ['other_column' => 'foo'], array_flip($syncData));
    

    or without arrow

    $syncData = array_map(function($locationSysid) {
          return ['ENTITY' => 'dbo.Cli_Core'];
       }, array_flip($syncData));
    

    (array_flip means we're using the IDs as the index for the array)

    Programmatic equivalent of default(Type)

    I do the same task like this.

    //in MessageHeader 
       private void SetValuesDefault()
       {
            MessageHeader header = this;             
            Framework.ObjectPropertyHelper.SetPropertiesToDefault<MessageHeader>(this);
       }
    
    //in ObjectPropertyHelper
       public static void SetPropertiesToDefault<T>(T obj) 
       {
                Type objectType = typeof(T);
    
                System.Reflection.PropertyInfo [] props = objectType.GetProperties();
    
                foreach (System.Reflection.PropertyInfo property in props)
                {
                    if (property.CanWrite)
                    {
                        string propertyName = property.Name;
                        Type propertyType = property.PropertyType;
    
                        object value = TypeHelper.DefaultForType(propertyType);
                        property.SetValue(obj, value, null);
                    }
                }
        }
    
    //in TypeHelper
        public static object DefaultForType(Type targetType)
        {
            return targetType.IsValueType ? Activator.CreateInstance(targetType) : null;
        }
    

    Creating executable files in Linux

    No need to hack your editor, or switch editors.

    Instead we can come up with a script to watch your development directories and chmod files as they're created. This is what I've done in the attached bash script. You probably want to read through the comments and edit the 'config' section as fits your needs, then I would suggest putting it in your $HOME/bin/ directory and adding its execution to your $HOME/.login or similar file. Or you can just run it from the terminal.

    This script does require inotifywait, which comes in the inotify-tools package on Ubuntu,

    sudo apt-get install inotify-tools
    

    Suggestions/edits/improvements are welcome.

    #!/usr/bin/env bash
    
    # --- usage --- #
    # Depends: 'inotifywait' available in inotify-tools on Ubuntu
    # 
    # Edit the 'config' section below to reflect your working directory, WORK_DIR,
    # and your watched directories, WATCH_DIR. Each directory in WATCH_DIR will
    # be logged by inotify and this script will 'chmod +x' any new files created
    # therein. If SUBDIRS is 'TRUE' this script will watch WATCH_DIRS recursively.
    # I recommend adding this script to your $HOME/.login or similar to have it
    # run whenever you log into a shell, eg 'echo "watchdirs.sh &" >> ~/.login'.
    # This script will only allow one instance of itself to run at a time.
    
    # --- config --- #
    
    WORK_DIR="$HOME/path/to/devel" # top working directory (for cleanliness?)
    WATCH_DIRS=" \
        $WORK_DIR/dirA \
        $WORK_DIR/dirC \
        "                          # list of directories to watch
    SUBDIRS="TRUE"                 # watch subdirectories too
    NOTIFY_ARGS="-e create -q"     # watch for create events, non-verbose
    
    
    # --- script starts here --- #
    # probably don't need to edit beyond this point
    
    # kill all previous instances of myself
    SCRIPT="bash.*`basename $0`"
    MATCHES=`ps ax | egrep $SCRIPT | grep -v grep | awk '{print $1}' | grep -v $$`
    kill $MATCHES >& /dev/null
    
    # set recursive notifications (for subdirectories)
    if [ "$SUBDIRS" = "TRUE" ] ; then
        RECURSE="-r"
    else
        RECURSE=""
    fi
    
    while true ; do
        # grab an event
        EVENT=`inotifywait $RECURSE $NOTIFY_ARGS $WATCH_DIRS`
    
        # parse the event into DIR, TAGS, FILE
        OLDIFS=$IFS ; IFS=" " ; set -- $EVENT
        E_DIR=$1
        E_TAGS=$2
        E_FILE=$3
        IFS=$OLDIFS
    
        # skip if it's not a file event or already executable (unlikely)
        if [ ! -f "$E_DIR$E_FILE" ] || [ -x "$E_DIR$E_FILE" ] ; then
            continue
        fi
    
        # set file executable
        chmod +x $E_DIR$E_FILE
    done
    

    FULL OUTER JOIN vs. FULL JOIN

    Microsoft® SQL Server™ 2000 uses these SQL-92 keywords for outer joins specified in a FROM clause:

    • LEFT OUTER JOIN or LEFT JOIN

    • RIGHT OUTER JOIN or RIGHT JOIN

    • FULL OUTER JOIN or FULL JOIN

    From MSDN

    The full outer join or full join returns all rows from both tables, matching up the rows wherever a match can be made and placing NULLs in the places where no matching row exists.

    What's the fastest way to loop through an array in JavaScript?

    It's just 2018 so an update could be nice...

    And I really have to disagree with the accepted answer. It defers on different browsers. some do forEach faster, some for-loop, and some while here is a benchmark on all method http://jsben.ch/mW36e

    arr.forEach( a => {
      // ...
    }
    

    and since you can see alot of for-loop like for(a = 0; ... ) then worth to mention that without 'var' variables will be define globally and this can dramatically affects on speed so it'll get slow.

    Duff's device run faster on opera but not in firefox

    _x000D_
    _x000D_
    var arr = arr = new Array(11111111).fill(255);_x000D_
    var benches =     _x000D_
    [ [ "empty", () => {_x000D_
      for(var a = 0, l = arr.length; a < l; a++);_x000D_
    }]_x000D_
    , ["for-loop", () => {_x000D_
      for(var a = 0, l = arr.length; a < l; ++a)_x000D_
        var b = arr[a] + 1;_x000D_
    }]_x000D_
    , ["for-loop++", () => {_x000D_
      for(var a = 0, l = arr.length; a < l; a++)_x000D_
        var b = arr[a] + 1;_x000D_
    }]_x000D_
    , ["for-loop - arr.length", () => {_x000D_
      for(var a = 0; a < arr.length; ++a )_x000D_
        var b = arr[a] + 1;_x000D_
    }]_x000D_
    , ["reverse for-loop", () => {_x000D_
      for(var a = arr.length - 1; a >= 0; --a )_x000D_
        var b = arr[a] + 1;_x000D_
    }]_x000D_
    ,["while-loop", () => {_x000D_
      var a = 0, l = arr.length;_x000D_
      while( a < l ) {_x000D_
        var b = arr[a] + 1;_x000D_
        ++a;_x000D_
      }_x000D_
    }]_x000D_
    , ["reverse-do-while-loop", () => {_x000D_
      var a = arr.length - 1; // CAREFUL_x000D_
      do {_x000D_
        var b = arr[a] + 1;_x000D_
      } while(a--);   _x000D_
    }]_x000D_
    , ["forEach", () => {_x000D_
      arr.forEach( a => {_x000D_
        var b = a + 1;_x000D_
      });_x000D_
    }]_x000D_
    , ["for const..in (only 3.3%)", () => {_x000D_
      var ar = arr.slice(0,arr.length/33);_x000D_
      for( const a in ar ) {_x000D_
        var b = a + 1;_x000D_
      }_x000D_
    }]_x000D_
    , ["for let..in (only 3.3%)", () => {_x000D_
      var ar = arr.slice(0,arr.length/33);_x000D_
      for( let a in ar ) {_x000D_
        var b = a + 1;_x000D_
      }_x000D_
    }]_x000D_
    , ["for var..in (only 3.3%)", () => {_x000D_
      var ar = arr.slice(0,arr.length/33);_x000D_
      for( var a in ar ) {_x000D_
        var b = a + 1;_x000D_
      }_x000D_
    }]_x000D_
    , ["Duff's device", () => {_x000D_
      var len = arr.length;_x000D_
      var i, n = len % 8 - 1;_x000D_
    _x000D_
      if (n > 0) {_x000D_
        do {_x000D_
          var b = arr[len-n] + 1;_x000D_
        } while (--n); // n must be greater than 0 here_x000D_
      }_x000D_
      n = (len * 0.125) ^ 0;_x000D_
      if (n > 0) { _x000D_
        do {_x000D_
          i = --n <<3;_x000D_
          var b = arr[i] + 1;_x000D_
          var c = arr[i+1] + 1;_x000D_
          var d = arr[i+2] + 1;_x000D_
          var e = arr[i+3] + 1;_x000D_
          var f = arr[i+4] + 1;_x000D_
          var g = arr[i+5] + 1;_x000D_
          var h = arr[i+6] + 1;_x000D_
          var k = arr[i+7] + 1;_x000D_
        }_x000D_
        while (n); // n must be greater than 0 here also_x000D_
      }_x000D_
    }]];_x000D_
    function bench(title, f) {_x000D_
      var t0 = performance.now();_x000D_
      var res = f();_x000D_
      return performance.now() - t0; // console.log(`${title} took ${t1-t0} msec`);_x000D_
    }_x000D_
    var globalVarTime = bench( "for-loop without 'var'", () => {_x000D_
      // Here if you forget to put 'var' so variables'll be global_x000D_
      for(a = 0, l = arr.length; a < l; ++a)_x000D_
         var b = arr[a] + 1;_x000D_
    });_x000D_
    var times = benches.map( function(a) {_x000D_
                          arr = new Array(11111111).fill(255);_x000D_
                          return [a[0], bench(...a)]_x000D_
                         }).sort( (a,b) => a[1]-b[1] );_x000D_
    var max = times[times.length-1][1];_x000D_
    times = times.map( a => {a[2] = (a[1]/max)*100; return a; } );_x000D_
    var template = (title, time, n) =>_x000D_
      `<div>` +_x000D_
        `<span>${title} &nbsp;</span>` +_x000D_
        `<span style="width:${3+n/2}%">&nbsp;${Number(time.toFixed(3))}msec</span>` +_x000D_
      `</div>`;_x000D_
    _x000D_
    var strRes = times.map( t => template(...t) ).join("\n") + _x000D_
                `<br><br>for-loop without 'var' ${globalVarTime} msec.`;_x000D_
    var $container = document.getElementById("container");_x000D_
    $container.innerHTML = strRes;
    _x000D_
    body { color:#fff; background:#333; font-family:helvetica; }_x000D_
    body > div > div {  clear:both   }_x000D_
    body > div > div > span {_x000D_
      float:left;_x000D_
      width:43%;_x000D_
      margin:3px 0;_x000D_
      text-align:right;_x000D_
    }_x000D_
    body > div > div > span:nth-child(2) {_x000D_
      text-align:left;_x000D_
      background:darkorange;_x000D_
      animation:showup .37s .111s;_x000D_
      -webkit-animation:showup .37s .111s;_x000D_
    }_x000D_
    @keyframes showup { from { width:0; } }_x000D_
    @-webkit-keyframes showup { from { width:0; } }
    _x000D_
    <div id="container"> </div>
    _x000D_
    _x000D_
    _x000D_

    CS0234: Mvc does not exist in the System.Web namespace

    Check your runtime tag inside the web.config, and verify you have something like this declared:

    <runtime>
        <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
          <dependentAssembly>
            <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
            <bindingRedirect oldVersion="0.0.0.0-4.0.0.0" newVersion="4.0.0.0" />
          </dependentAssembly>
    .....
    </runtime>
    

    CSS3 transition on click using pure CSS

    As jeremyjjbrow said, :active pseudo won't persist. But there's a hack for doing it on pure css. You can wrap it on a <a> tag, and apply the :active on it, like this:

    <a class="test">
        <img class="crossRotate" src="images/cross.png" alt="Cross Menu button" />
     </a>
    

    And the css:

    .test:active .crossRotate {
        transform: rotate(45deg);
        -webkit-transform: rotate(45deg);
        -ms-transform: rotate(45deg);
        }
    

    Try it out... It works (at least on Chrome)!

    HttpServletRequest - Get query string parameters, no form data

    I am afraid there is no way to get the query string parameters parsed separately from the post parameters. BTW the fact that such API absent may mean that probably you should check your design. Why are you using query string when sending POST? If you really want to send more data into URL use REST-like convention, e.g. instead of sending

    http://mycompany.com/myapp/myservlet?first=11&second=22

    say:

    http://mycompany.com/myapp/myservlet/11/22

    Is there a method for String conversion to Title Case?

    You can use apache commons langs like this :

    WordUtils.capitalizeFully("this is a text to be capitalize")
    

    you can find the java doc here : WordUtils.capitalizeFully java doc

    and if you want to remove the spaces in between the worlds you can use :

    StringUtils.remove(WordUtils.capitalizeFully("this is a text to be capitalize")," ")
    

    you can find the java doc for String StringUtils.remove java doc

    i hope this help.

    How to remove empty lines with or without whitespace in Python

    If you are not willing to try regex (which you should), you can use this:

    s.replace('\n\n','\n')
    

    Repeat this several times to make sure there is no blank line left. Or chaining the commands:

    s.replace('\n\n','\n').replace('\n\n','\n')
    


    Just to encourage you to use regex, here are two introductory videos that I find intuitive:
    Regular Expressions (Regex) Tutorial
    Python Tutorial: re Module

    Creating a DateTime in a specific Time Zone in c#

    The other answers here are useful but they don't cover how to access Pacific specifically - here you go:

    public static DateTime GmtToPacific(DateTime dateTime)
    {
        return TimeZoneInfo.ConvertTimeFromUtc(dateTime,
            TimeZoneInfo.FindSystemTimeZoneById("Pacific Standard Time"));
    }
    

    Oddly enough, although "Pacific Standard Time" normally means something different from "Pacific Daylight Time," in this case it refers to Pacific time in general. In fact, if you use FindSystemTimeZoneById to fetch it, one of the properties available is a bool telling you whether that timezone is currently in daylight savings or not.

    You can see more generalized examples of this in a library I ended up throwing together to deal with DateTimes I need in different TimeZones based on where the user is asking from, etc:

    https://github.com/b9chris/TimeZoneInfoLib.Net

    This won't work outside of Windows (for example Mono on Linux) since the list of times comes from the Windows Registry: HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Time Zones\

    Underneath that you'll find keys (folder icons in Registry Editor); the names of those keys are what you pass to FindSystemTimeZoneById. On Linux you have to use a separate Linux-standard set of timezone definitions, which I've not adequately explored.

    What does a (+) sign mean in an Oracle SQL WHERE clause?

    This is an Oracle-specific notation for an outer join. It means that it will include all rows from t1, and use NULLS in the t0 columns if there is no corresponding row in t0.

    In standard SQL one would write:

    SELECT t0.foo, t1.bar
      FROM FIRST_TABLE t0
     RIGHT OUTER JOIN SECOND_TABLE t1;
    

    Oracle recommends not to use those joins anymore if your version supports ANSI joins (LEFT/RIGHT JOIN) :

    Oracle recommends that you use the FROM clause OUTER JOIN syntax rather than the Oracle join operator. Outer join queries that use the Oracle join operator (+) are subject to the following rules and restrictions […]

    How to save all console output to file in R?

    You have to sink "output" and "message" separately (the sink function only looks at the first element of type)

    Now if you want the input to be logged too, then put it in a script:

    script.R

    1:5 + 1:3   # prints and gives a warning
    stop("foo") # an error
    

    And at the prompt:

    con <- file("test.log")
    sink(con, append=TRUE)
    sink(con, append=TRUE, type="message")
    
    # This will echo all input and not truncate 150+ character lines...
    source("script.R", echo=TRUE, max.deparse.length=10000)
    
    # Restore output to console
    sink() 
    sink(type="message")
    
    # And look at the log...
    cat(readLines("test.log"), sep="\n")
    

    How can I see the current value of my $PATH variable on OS X?

    By entering $PATH on its own at the command prompt, you're trying to run it. This isn't like Windows where you can get your path output by simply typing path.

    If you want to see what the path is, simply echo it:

    echo $PATH
    

    How to call javascript function from code-behind

    There is a very simple way in which you can do this. It involves injecting a javascript code to a label control from code behind. here is sample code:

    <head runat="server"> 
        <title>Calling javascript function from code behind example</title> 
            <script type="text/javascript"> 
                function showDialogue() { 
                    alert("this dialogue has been invoked through codebehind."); 
                } 
            </script> 
    </head>
    

    ..........

    lblJavaScript.Text = "<script type='text/javascript'>showDialogue();</script>";
    

    Check out the full code here: http://softmate-technologies.com/javascript-from-CodeBehind.htm (dead)
    Link from Internet Archive: https://web.archive.org/web/20120608053720/http://softmate-technologies.com/javascript-from-CodeBehind.htm

    Design Patterns web based applications

    A bit decent web application consists of a mix of design patterns. I'll mention only the most important ones.


    Model View Controller pattern

    The core (architectural) design pattern you'd like to use is the Model-View-Controller pattern. The Controller is to be represented by a Servlet which (in)directly creates/uses a specific Model and View based on the request. The Model is to be represented by Javabean classes. This is often further dividable in Business Model which contains the actions (behaviour) and Data Model which contains the data (information). The View is to be represented by JSP files which have direct access to the (Data) Model by EL (Expression Language).

    Then, there are variations based on how actions and events are handled. The popular ones are:

    • Request (action) based MVC: this is the simplest to implement. The (Business) Model works directly with HttpServletRequest and HttpServletResponse objects. You have to gather, convert and validate the request parameters (mostly) yourself. The View can be represented by plain vanilla HTML/CSS/JS and it does not maintain state across requests. This is how among others Spring MVC, Struts and Stripes works.

    • Component based MVC: this is harder to implement. But you end up with a simpler model and view wherein all the "raw" Servlet API is abstracted completely away. You shouldn't have the need to gather, convert and validate the request parameters yourself. The Controller does this task and sets the gathered, converted and validated request parameters in the Model. All you need to do is to define action methods which works directly with the model properties. The View is represented by "components" in flavor of JSP taglibs or XML elements which in turn generates HTML/CSS/JS. The state of the View for the subsequent requests is maintained in the session. This is particularly helpful for server-side conversion, validation and value change events. This is how among others JSF, Wicket and Play! works.

    As a side note, hobbying around with a homegrown MVC framework is a very nice learning exercise, and I do recommend it as long as you keep it for personal/private purposes. But once you go professional, then it's strongly recommended to pick an existing framework rather than reinventing your own. Learning an existing and well-developed framework takes in long term less time than developing and maintaining a robust framework yourself.

    In the below detailed explanation I'll restrict myself to request based MVC since that's easier to implement.


    Front Controller pattern (Mediator pattern)

    First, the Controller part should implement the Front Controller pattern (which is a specialized kind of Mediator pattern). It should consist of only a single servlet which provides a centralized entry point of all requests. It should create the Model based on information available by the request, such as the pathinfo or servletpath, the method and/or specific parameters. The Business Model is called Action in the below HttpServlet example.

    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        try {
            Action action = ActionFactory.getAction(request);
            String view = action.execute(request, response);
    
            if (view.equals(request.getPathInfo().substring(1)) {
                request.getRequestDispatcher("/WEB-INF/" + view + ".jsp").forward(request, response);
            }
            else {
                response.sendRedirect(view); // We'd like to fire redirect in case of a view change as result of the action (PRG pattern).
            }
        }
        catch (Exception e) {
            throw new ServletException("Executing action failed.", e);
        }
    }
    

    Executing the action should return some identifier to locate the view. Simplest would be to use it as filename of the JSP. Map this servlet on a specific url-pattern in web.xml, e.g. /pages/*, *.do or even just *.html.

    In case of prefix-patterns as for example /pages/* you could then invoke URL's like http://example.com/pages/register, http://example.com/pages/login, etc and provide /WEB-INF/register.jsp, /WEB-INF/login.jsp with the appropriate GET and POST actions. The parts register, login, etc are then available by request.getPathInfo() as in above example.

    When you're using suffix-patterns like *.do, *.html, etc, then you could then invoke URL's like http://example.com/register.do, http://example.com/login.do, etc and you should change the code examples in this answer (also the ActionFactory) to extract the register and login parts by request.getServletPath() instead.


    Strategy pattern

    The Action should follow the Strategy pattern. It needs to be defined as an abstract/interface type which should do the work based on the passed-in arguments of the abstract method (this is the difference with the Command pattern, wherein the abstract/interface type should do the work based on the arguments which are been passed-in during the creation of the implementation).

    public interface Action {
        public String execute(HttpServletRequest request, HttpServletResponse response) throws Exception;
    }
    

    You may want to make the Exception more specific with a custom exception like ActionException. It's just a basic kickoff example, the rest is all up to you.

    Here's an example of a LoginAction which (as its name says) logs in the user. The User itself is in turn a Data Model. The View is aware of the presence of the User.

    public class LoginAction implements Action {
    
        public String execute(HttpServletRequest request, HttpServletResponse response) throws Exception {
            String username = request.getParameter("username");
            String password = request.getParameter("password");
            User user = userDAO.find(username, password);
    
            if (user != null) {
                request.getSession().setAttribute("user", user); // Login user.
                return "home"; // Redirect to home page.
            }
            else {
                request.setAttribute("error", "Unknown username/password. Please retry."); // Store error message in request scope.
                return "login"; // Go back to redisplay login form with error.
            }
        }
    
    }
    

    Factory method pattern

    The ActionFactory should follow the Factory method pattern. Basically, it should provide a creational method which returns a concrete implementation of an abstract/interface type. In this case, it should return an implementation of the Action interface based on the information provided by the request. For example, the method and pathinfo (the pathinfo is the part after the context and servlet path in the request URL, excluding the query string).

    public static Action getAction(HttpServletRequest request) {
        return actions.get(request.getMethod() + request.getPathInfo());
    }
    

    The actions in turn should be some static/applicationwide Map<String, Action> which holds all known actions. It's up to you how to fill this map. Hardcoding:

    actions.put("POST/register", new RegisterAction());
    actions.put("POST/login", new LoginAction());
    actions.put("GET/logout", new LogoutAction());
    // ...
    

    Or configurable based on a properties/XML configuration file in the classpath: (pseudo)

    for (Entry entry : configuration) {
        actions.put(entry.getKey(), Class.forName(entry.getValue()).newInstance());
    }
    

    Or dynamically based on a scan in the classpath for classes implementing a certain interface and/or annotation: (pseudo)

    for (ClassFile classFile : classpath) {
        if (classFile.isInstanceOf(Action.class)) {
           actions.put(classFile.getAnnotation("mapping"), classFile.newInstance());
        }
    }
    

    Keep in mind to create a "do nothing" Action for the case there's no mapping. Let it for example return directly the request.getPathInfo().substring(1) then.


    Other patterns

    Those were the important patterns so far.

    To get a step further, you could use the Facade pattern to create a Context class which in turn wraps the request and response objects and offers several convenience methods delegating to the request and response objects and pass that as argument into the Action#execute() method instead. This adds an extra abstract layer to hide the raw Servlet API away. You should then basically end up with zero import javax.servlet.* declarations in every Action implementation. In JSF terms, this is what the FacesContext and ExternalContext classes are doing. You can find a concrete example in this answer.

    Then there's the State pattern for the case that you'd like to add an extra abstraction layer to split the tasks of gathering the request parameters, converting them, validating them, updating the model values and execute the actions. In JSF terms, this is what the LifeCycle is doing.

    Then there's the Composite pattern for the case that you'd like to create a component based view which can be attached with the model and whose behaviour depends on the state of the request based lifecycle. In JSF terms, this is what the UIComponent represent.

    This way you can evolve bit by bit towards a component based framework.


    See also:

    How can I render Partial views in asp.net mvc 3?

    <%= Html.Partial("PartialName", Model) %>
    

    Missing Compliance in Status when I add built for internal testing in Test Flight.How to solve?

    Additionally, if you can't see the "Provide Export Compliance Information" button make sure you have the right role in your App Store Connect or talk to the right person (Account Holder, Admin, or App Manager).

    PHP - regex to allow letters and numbers only

    You left off the / (pattern delimiter) and $ (match end string).

    preg_match("/^[a-zA-Z0-9]+$/", $value)
    

    How do I update pip itself from inside my virtual environment?

    Very Simple. Just download pip from https://bootstrap.pypa.io/get-pip.py . Save the file in some forlder or dekstop. I saved the file in my D drive.Then from your command prompt navigate to the folder where you have downloaded pip. Then type there

    python -get-pip.py
    

    Pip installation screenshot

    SQL Server datetime LIKE select?

    I am a little late to this thread but in fact there is direct support for the like operator in MS SQL server.

    As documented in LIKE help if the datatype is not a string it is attempted to convert it to a string. And as documented in cast\convert documentation:

    default datetime conversion to string is type 0 (,100) which is mon dd yyyy hh:miAM (or PM).

    If you have a date like this in the DB:

    2015-06-01 11:52:59.057
    

    and you do queries like this:

    select * from wws_invoice where invdate like 'Jun%'
    select * from wws_invoice where invdate like 'Jun 1%'
    select * from wws_invoice where invdate like 'Jun 1 %'
    select * from wws_invoice where invdate like 'Jun 1 2015:%'
    select * from wws_invoice where invdate like 'Jun ? 2015%'
    ...
    select * from wws_invoice where invdate like 'Jun 1 2015 11:52AM'
    

    you get that row.

    However, this date format suggests that it is a DateTime2, then documentation says:

    21 or 121 -- ODBC canonical (with milliseconds) default for time, date, datetime2, and datetimeoffset. -- yyyy-mm-dd hh:mi:ss.mmm(24h)

    That makes it easier and you can use:

    select * from wws_invoice where invdate like '2015-06-01%'
    

    and get the invoice record. Here is a demo code:

    DECLARE @myDates TABLE (myDate DATETIME2);
    INSERT INTO @myDates (myDate)
    VALUES
    ('2015-06-01 11:52:59.057'),
    ('2015-06-01 11:52:59.054'),
    ('2015-06-01 13:52:59.057'),
    ('2015-06-01 14:52:59.057');
    
    SELECT * FROM @myDates WHERE myDate LIKE '2015-06-01%';
    SELECT * FROM @myDates WHERE myDate LIKE '2015-06-01 11%';
    SELECT * FROM @myDates WHERE myDate LIKE '2015-06-01 11:52:59%';
    SELECT * FROM @myDates WHERE myDate LIKE '2015-06-01 11:52:59.054%';
    

    Doing datetime searches in SQL server without any conversion to string has always been problematic. Getting each date part is an overkill (which unlikely would use an index). Probably a better way when you don't use string conversion would be to use range checks. ie:

    select * from record 
    where register_date >= '20091010' and register_date < '20091011';
    

    Replace spaces with dashes and make all letters lower-case

    Above answer can be considered to be confusing a little. String methods are not modifying original object. They return new object. It must be:

    var str = "Sonic Free Games";
    str = str.replace(/\s+/g, '-').toLowerCase(); //new object assigned to var str
    

    Separators for Navigation

    Put it in as a background on the list element:

    <ul id="nav">
        <li><a><img /></a></li>
        ...
        <li><a><img /></a></li>
    </ul>
    
    #nav li{background: url(/images/separator.gif) no-repeat left; padding-left:20px;} 
    /* left padding creates a gap between links */
    

    Next, I recommend a different markup for accessibility:
    Rather than embedding the images inline, put text in as text, surround each with a span, apply the image as a background the the , and then hide the text with display:none -- this gives much more styling flexibilty, and allows you to use tiling with a 1px wide bg image, saves bandwidth, and you can embed it in a CSS sprite, which saves HTTP calls:

    HTML:

    <ul id="nav">
        <li><a><span>link text</span></a></li>
        ...
        <li><a><span>link text</span></a></li>
    </ul
    

    CSS:

    #nav li{background: url(/images/separator.gif) no-repeat left; padding-left:20px;} 
    #nav a{background: url(/images/nav-bg.gif) repeat-x;}
    #nav a span{display:none;}
    

    UPDATE OK, I see others got similar answer in before me -- and I note that John also includes a means for keeping the separator from appearing before the first element, by using the li + li selector -- which means any li coming after another li.

    How to enumerate an enum

    Some versions of the .NET framework do not support Enum.GetValues. Here's a good workaround from Ideas 2.0: Enum.GetValues in Compact Framework:

    public Enum[] GetValues(Enum enumeration)
    {
        FieldInfo[] fields = enumeration.GetType().GetFields(BindingFlags.Static | BindingFlags.Public);
        Enum[] enumerations = new Enum[fields.Length];
    
        for (var i = 0; i < fields.Length; i++)
            enumerations[i] = (Enum) fields[i].GetValue(enumeration);
    
        return enumerations;
    }
    

    As with any code that involves reflection, you should take steps to ensure it runs only once and results are cached.