Programs & Examples On #Mcps

Server.MapPath("."), Server.MapPath("~"), Server.MapPath(@"\"), Server.MapPath("/"). What is the difference?

Just to expand on @splattne's answer a little:

MapPath(string virtualPath) calls the following:

public string MapPath(string virtualPath)
{
    return this.MapPath(VirtualPath.CreateAllowNull(virtualPath));
}

MapPath(VirtualPath virtualPath) in turn calls MapPath(VirtualPath virtualPath, VirtualPath baseVirtualDir, bool allowCrossAppMapping) which contains the following:

//...
if (virtualPath == null)
{
    virtualPath = VirtualPath.Create(".");
}
//...

So if you call MapPath(null) or MapPath(""), you are effectively calling MapPath(".")

Efficiently checking if arbitrary object is NaN in Python / numpy / pandas?

I found this brilliant solution here, it uses the simple logic NAN!=NAN. https://www.codespeedy.com/check-if-a-given-string-is-nan-in-python/

Using above example you can simply do the following. This should work on different type of objects as it simply utilize the fact that NAN is not equal to NAN.

 import numpy as np
 s = pd.Series(['apple', np.nan, 'banana'])
 s.apply(lambda x: x!=x)
 out[252]
 0    False
 1     True
 2    False
 dtype: bool

How to access a mobile's camera from a web app?

I don't think you can - there is a W3C draft API to get audio or video, but there is no implementation yet on any of the major mobile OSs.

Second best The only option is to go with Dennis' suggestion to use PhoneGap. This will mean you need to create a native app and add it to the mobile app store/marketplace.

Maven - Failed to execute goal org.apache.maven.plugins:maven-clean-plugin:2.4.1:clean

In my case I changed the owner of all the files and it worked.

sudo chown -R anuruddha *

mysqli_real_connect(): (HY000/2002): No such file or directory

If you are using archlinux or Ubuntu just type the commands below:

cd /opt/lampp/phpmyadmin

then

sudo gedit config.inc.php

Then when you access the file look for the scripts below,

//$cfg['Servers'][$i]['host'] ='localhost'

remove '//' so that it remains as shown below:

$cfg['Servers'][$i]['host'] ='localhost'

Then change the 'localhost' to '127.0.0.1' and the script should turn as shown below:

$cfg['Servers'][$i]['host'] ='127.0.0.1'

Get back to your browser and type http://127.0.0.1/phpmyadmin/

If it is still refusing

You should check the host, username and password in your configuration and make sure that they correspond to the information given by the administrator of the MySQL server.

so then get back to the same file config.inc.php you were editing and do as follows:

cd /opt/lampp/phpmyadmin

then

sudo gedit config.inc.php

search for the script below

$cfg['Servers'][$i]['password'] =''

Fill the password with your root password

$cfg['Servers'][$i]['password'] ='your_password'

And it should work.

How can I make a TextBox be a "password box" and display stars when using MVVM?

As Tasnim Fabiha mentioned, it is possible to change font for TextBox in order to show only dots/asterisks. But I wasn't able to find his font...so I give you my working example:

<TextBox Text="{Binding Password}" 
     FontFamily="pack://application:,,,/Resources/#password" />

Just copy-paste won't work. Firstly you have to download mentioned font "password.ttf" link: https://github.com/davidagraf/passwd/blob/master/public/ttf/password.ttf Then copy that to your project Resources folder (Project->Properties->Resources->Add resource->Add existing file). Then set it's Build Action to: Resource.

After this you will see just dots, but you can still copy text from that, so it is needed to disable CTRL+C shortcut like this:

<TextBox Text="{Binding Password}" 
     FontFamily="pack://application:,,,/Resources/#password" > 
    <TextBox.InputBindings>
        <!--Disable CTRL+C -->
        <KeyBinding Command="ApplicationCommands.NotACommand"
            Key="C"
            Modifiers="Control" />
    </TextBox.InputBindings>
</TextBox>

Shared-memory objects in multiprocessing

If you use an operating system that uses copy-on-write fork() semantics (like any common unix), then as long as you never alter your data structure it will be available to all child processes without taking up additional memory. You will not have to do anything special (except make absolutely sure you don't alter the object).

The most efficient thing you can do for your problem would be to pack your array into an efficient array structure (using numpy or array), place that in shared memory, wrap it with multiprocessing.Array, and pass that to your functions. This answer shows how to do that.

If you want a writeable shared object, then you will need to wrap it with some kind of synchronization or locking. multiprocessing provides two methods of doing this: one using shared memory (suitable for simple values, arrays, or ctypes) or a Manager proxy, where one process holds the memory and a manager arbitrates access to it from other processes (even over a network).

The Manager approach can be used with arbitrary Python objects, but will be slower than the equivalent using shared memory because the objects need to be serialized/deserialized and sent between processes.

There are a wealth of parallel processing libraries and approaches available in Python. multiprocessing is an excellent and well rounded library, but if you have special needs perhaps one of the other approaches may be better.

Get class list for element with jQuery

$('div').attr('class').split(' ').each(function(cls){ console.log(cls);})

Execute a terminal command from a Cocoa app

fork, exec, and wait should work, if you're not really looking for a Objective-C specific way. fork creates a copy of the currently running program, exec replaces the currently running program with a new one, and wait waits for the subprocess to exit. For example (without any error checking):

#include <stdlib.h>
#include <unistd.h>


pid_t p = fork();
if (p == 0) {
    /* fork returns 0 in the child process. */
    execl("/other/program/to/run", "/other/program/to/run", "foo", NULL);
} else {
    /* fork returns the child's PID in the parent. */
    int status;
    wait(&status);
    /* The child has exited, and status contains the way it exited. */
}

/* The child has run and exited by the time execution gets to here. */

There's also system, which runs the command as if you typed it from the shell's command line. It's simpler, but you have less control over the situation.

I'm assuming you're working on a Mac application, so the links are to Apple's documentation for these functions, but they're all POSIX, so you should be to use them on any POSIX-compliant system.

How can I shuffle an array?

You could use the Fisher-Yates Shuffle (code adapted from this site):

function shuffle(array) {
    let counter = array.length;

    // While there are elements in the array
    while (counter > 0) {
        // Pick a random index
        let index = Math.floor(Math.random() * counter);

        // Decrease counter by 1
        counter--;

        // And swap the last element with it
        let temp = array[counter];
        array[counter] = array[index];
        array[index] = temp;
    }

    return array;
}

Implementing two interfaces in a class with same method. Which interface method is overridden?

Well if they are both the same it doesn't matter. It implements both of them with a single concrete method per interface method.

What is the maximum length of a table name in Oracle?

Teach a man to fish

Notice the data-type and size

>describe all_tab_columns

VIEW all_tab_columns

Name                                      Null?    Type                        
 ----------------------------------------- -------- ----------------------------
 OWNER                                     NOT NULL VARCHAR2(30)                
 TABLE_NAME                                NOT NULL VARCHAR2(30)                
 COLUMN_NAME                               NOT NULL VARCHAR2(30)                
 DATA_TYPE                                          VARCHAR2(106)               
 DATA_TYPE_MOD                                      VARCHAR2(3)                 
 DATA_TYPE_OWNER                                    VARCHAR2(30)                
 DATA_LENGTH                               NOT NULL NUMBER                      
 DATA_PRECISION                                     NUMBER                      
 DATA_SCALE                                         NUMBER                      
 NULLABLE                                           VARCHAR2(1)                 
 COLUMN_ID                                          NUMBER                      
 DEFAULT_LENGTH                                     NUMBER                      
 DATA_DEFAULT                                       LONG                        
 NUM_DISTINCT                                       NUMBER                      
 LOW_VALUE                                          RAW(32)                     
 HIGH_VALUE                                         RAW(32)                     
 DENSITY                                            NUMBER                      
 NUM_NULLS                                          NUMBER                      
 NUM_BUCKETS                                        NUMBER                      
 LAST_ANALYZED                                      DATE                        
 SAMPLE_SIZE                                        NUMBER                      
 CHARACTER_SET_NAME                                 VARCHAR2(44)                
 CHAR_COL_DECL_LENGTH                               NUMBER                      
 GLOBAL_STATS                                       VARCHAR2(3)                 
 USER_STATS                                         VARCHAR2(3)                 
 AVG_COL_LEN                                        NUMBER                      
 CHAR_LENGTH                                        NUMBER                      
 CHAR_USED                                          VARCHAR2(1)                 
 V80_FMT_IMAGE                                      VARCHAR2(3)                 
 DATA_UPGRADED                                      VARCHAR2(3)                 
 HISTOGRAM                                          VARCHAR2(15)                

Convert Json String to C# Object List

Please make sure that all properties are both the getter and setter. In case, any property is getter only, it will cause the reverting the List to original data as the JSON string is typed.

Please refer to the following code snippet for the same: Model:

 public class Person
{
    public int ID { get; set; }
    // following 2 lines are cause of error
    //public string Name { get { return string.Format("{0} {1}", First, Last); } }
    //public string Country { get { return Countries[CountryID]; } }
    public int CountryID { get; set; }
    public bool Active { get; set; }
    public string First { get; set; }
    public string Last { get; set; }
    public DateTime Hired { get; set; }
}
public class ModelObj
    {
        public string Str { get; set; }
        public List<Person> Persons { get; set; }
    }

Controller:

 [HttpPost]
    public ActionResult Index(FormCollection collection)
    {
        var data = new ModelObj();
        data.Str = (string)collection.GetValue("Str").ConvertTo(typeof(string));
        var personsString = (string)collection.GetValue("Persons").ConvertTo(typeof(string));
        using (var textReader = new StringReader(personsString))
        {
            using (var reader = new JsonTextReader(textReader))
            {
                data.Persons = new JsonSerializer().Deserialize(reader, typeof(List<Person>)) as List<Person>; 
            }
        }

        return View(data);
    }

How can I set the focus (and display the keyboard) on my EditText programmatically

use:

editText.requestFocus();
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, InputMethodManager.HIDE_IMPLICIT_ONLY);

Include php files when they are in different folders

You can get to the root from within each site using $_SERVER['DOCUMENT_ROOT']. For testing ONLY you can echo out the path to make sure it's working, if you do it the right way. You NEVER want to show the local server paths for things like includes and requires.

Site 1

echo $_SERVER['DOCUMENT_ROOT']; //should be '/main_web_folder/';

Includes under site one would be at:

echo $_SERVER['DOCUMENT_ROOT'].'/includes/'; // should be '/main_web_folder/includes/';

Site 2

echo $_SERVER['DOCUMENT_ROOT']; //should be '/main_web_folder/blog/';

The actual code to access includes from site1 inside of site2 you would say:

include($_SERVER['DOCUMENT_ROOT'].'/../includes/file_from_site_1.php');

It will only use the relative path of the file executing the query if you try to access it by excluding the document root and the root slash:

 //(not as fool-proof or non-platform specific)
 include('../includes/file_from_site_1.php');

Included paths have no place in code on the front end (live) of the site anywhere, and should be secured and used in production environments only.

Additionally for URLs on the site itself you can make them relative to the domain. Browsers will automatically fill in the rest because they know which page they are looking at. So instead of:

<a href='http://www.__domain__name__here__.com/contact/'>Contact</a>

You should use:

<a href='/contact/'>Contact</a>

For good SEO you'll want to make sure that the URLs for the blog do not exist in the other domain, otherwise it may be marked as a duplicate site. With that being said you might also want to add a line to your robots.txt file for ONLY site1:

User-agent: *
Disallow: /blog/

Other possibilities:

Look up your IP address and include this snippet of code:

function is_dev(){
  //use the external IP from Google.
  //If you're hosting locally it's 127.0.01 unless you've changed it.
  $ip_address='xxx.xxx.xxx.xxx';

  if ($_SERVER['REMOTE_ADDR']==$ip_address){
     return true;
  } else {
     return false;
  } 
}

if(is_dev()){
    echo $_SERVER['DOCUMENT_ROOT'];       
}

Remember if your ISP changes your IP, as in you have a DCHP Dynamic IP, you'll need to change the IP in that file to see the results. I would put that file in an include, then require it on pages for debugging.

If you're okay with modern methods like using the browser console log you could do this instead and view it in the browser's debugging interface:

if(is_dev()){
    echo "<script>".PHP_EOL;
    echo "console.log('".$_SERVER['DOCUMENT_ROOT']."');".PHP_EOL;
    echo "</script>".PHP_EOL;       
}

Open a local HTML file using window.open in Chrome

First, make sure that the source page and the target page are both served through the file URI scheme. You can't force an http page to open a file page (but it works the other way around).

Next, your script that calls window.open() should be invoked by a user-initiated event, such as clicks, keypresses and the like. Simply calling window.open() won't work.

You can test this right here in this question page. Run these in Chrome's JavaScript console:

// Does nothing
window.open('http://google.com');

// Click anywhere within this page and the new window opens
$(document.body).unbind('click').click(function() { window.open('http://google.com'); });

// This will open a new window, but it would be blank
$(document.body).unbind('click').click(function() { window.open('file:///path/to/a/local/html/file.html'); });

You can also test if this works with a local file. Here's a sample HTML file that simply loads jQuery:

<html>
    <head>
        <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.0/jquery.min.js"></script>
    </head>
    <body>
        <h5>Feel the presha</h5>
        <h3>Come play my game, I'll test ya</h3>
        <h1>Psycho- somatic- addict- insane!</h1>
    </body>
</html>

Then open Chrome's JavaScript console and run the statements above. The 3rd one will now work.

How to get all elements inside "div" that starts with a known text

With modern browsers, this is easy without jQuery:

document.getElementById('yourParentDiv').querySelectorAll('[id^="q17_"]');

The querySelectorAll takes a selector (as per CSS selectors) and uses it to search children of the 'yourParentDiv' element recursively. The selector uses ^= which means "starts with".

Note that all browsers released since June 2009 support this.

find difference between two text files with one item per line

an awk answer:

awk 'NR == FNR {file1[$0]++; next} !($0 in file1)' file1 file2

Comments in Markdown

Also see Critic Markup, supported by an increasing number of Markdown tools.

http://criticmarkup.com/

Comment {>> <<}

Lorem ipsum dolor sit amet.{>>This is a comment<<}

Highlight+Comment {== ==}{>> <<}

Lorem ipsum dolor sit amet, consectetur adipiscing elit. {==Vestibulum at orci magna. Phasellus augue justo, sodales eu pulvinar ac, vulputate eget nulla.==}{>>confusing<<} Mauris massa sem, tempor sed cursus et, semper tincidunt lacus.

How do you remove the title text from the Android ActionBar?

I am new to Android so maybe I am wrong...but to solve this problem cant we just go to the manifest and remove the activity label

<activity
        android:name=".Bcft"
        android:screenOrientation="portrait"

        **android:label="" >**

Worked for me....

link with target="_blank" does not open in new tab in Chrome

most simple answer

<a onclick="window.open(this.href,'_blank');return false;" href="http://www.foracure.org.au">Some Other Site</a>

it will work

How to Sign an Already Compiled Apk

You use jarsigner to sign APK's. You don't have to sign with the original keystore, just generate a new one. Read up on the details: http://developer.android.com/guide/publishing/app-signing.html

How to remove unique key from mysql table

All keys are named, you should use something like this -

ALTER TABLE tbl_quiz_attempt_master
  DROP INDEX index_name;

To drop primary key use this one -

ALTER TABLE tbl_quiz_attempt_master
  DROP INDEX `PRIMARY`;

ALTER TABLE Syntax.

What is the difference between the GNU Makefile variable assignments =, ?=, := and +=?

When you use VARIABLE = value, if value is actually a reference to another variable, then the value is only determined when VARIABLE is used. This is best illustrated with an example:

VAL = foo
VARIABLE = $(VAL)
VAL = bar

# VARIABLE and VAL will both evaluate to "bar"

When you use VARIABLE := value, you get the value of value as it is now. For example:

VAL = foo
VARIABLE := $(VAL)
VAL = bar

# VAL will evaluate to "bar", but VARIABLE will evaluate to "foo"

Using VARIABLE ?= val means that you only set the value of VARIABLE if VARIABLE is not set already. If it's not set already, the setting of the value is deferred until VARIABLE is used (as in example 1).

VARIABLE += value just appends value to VARIABLE. The actual value of value is determined as it was when it was initially set, using either = or :=.

How do I set a JLabel's background color?

For the Background, make sure you have imported java.awt.Color into your package.

In your main method, i.e. public static void main(String[] args), call the already imported method:

JLabel name_of_your_label=new JLabel("the title of your label");
name_of_your_label.setBackground(Color.the_color_you_wish);
name_of_your_label.setOpaque(true);

NB: Setting opaque will affect its visibility. Remember the case sensitivity in Java.

How do I completely uninstall Node.js, and reinstall from beginning (Mac OS X)

If you're unable to locate node just run whereis node and whereis npm and whereis nvm and you can remove the listed directories as needed.

You'll also need to entirely close your terminal and reopen it for changes to take effect.

Java 8 lambda get and remove element from list

The direct solution would be to invoke ifPresent(consumer) on the Optional returned by findFirst(). This consumer will be invoked when the optional is not empty. The benefit also is that it won't throw an exception if the find operation returned an empty optional, like your current code would do; instead, nothing will happen.

If you want to return the removed value, you can map the Optional to the result of calling remove:

producersProcedureActive.stream()
                        .filter(producer -> producer.getPod().equals(pod))
                        .findFirst()
                        .map(p -> {
                            producersProcedureActive.remove(p);
                            return p;
                        });

But note that the remove(Object) operation will again traverse the list to find the element to remove. If you have a list with random access, like an ArrayList, it would be better to make a Stream over the indexes of the list and find the first index matching the predicate:

IntStream.range(0, producersProcedureActive.size())
         .filter(i -> producersProcedureActive.get(i).getPod().equals(pod))
         .boxed()
         .findFirst()
         .map(i -> producersProcedureActive.remove((int) i));

With this solution, the remove(int) operation operates directly on the index.

Fastest way to update 120 Million records

set rowcount 1000000
Update table set int_field = -1 where int_field<>-1

see how fast that takes, adjust and repeat as necessary

How to comment lines in rails html.erb files?

This is CLEANEST, SIMPLEST ANSWER for CONTIGUOUS NON-PRINTING Ruby Code:

The below also happens to answer the Original Poster's question without, the "ugly" conditional code that some commenters have mentioned.


  1. CONTIGUOUS NON-PRINTING Ruby Code

    • This will work in any mixed language Rails View file, e.g, *.html.erb, *.js.erb, *.rhtml, etc.

    • This should also work with STD OUT/printing code, e.g. <%#= f.label :title %>

    • DETAILS:

      Rather than use rails brackets on each line and commenting in front of each starting bracket as we usually do like this:

        <%# if flash[:myErrors] %>
          <%# if flash[:myErrors].any? %>
            <%# if @post.id.nil? %>
              <%# if @myPost!=-1 %>
                <%# @post = @myPost %>
              <%# else %>
                <%# @post = Post.new %>
              <%# end %>
            <%# end %>
          <%# end %>
        <%# end %>
      

      YOU CAN INSTEAD add only one comment (hashmark/poundsign) to the first open Rails bracket if you write your code as one large block... LIKE THIS:

        <%# 
          if flash[:myErrors] then
            if flash[:myErrors].any? then
              if @post.id.nil? then
                if @myPost!=-1 then
                  @post = @myPost 
                else 
                  @post = Post.new 
                end 
              end 
            end 
          end 
        %>
      

How to display Wordpress search results?

Basically, you need to include the Wordpress loop in your search.php template to loop through the search results and show them as part of the template.

Below is a very basic example from The WordPress Theme Search Template and Page Template over at ThemeShaper.

<?php
/**
 * The template for displaying Search Results pages.
 *
 * @package Shape
 * @since Shape 1.0
 */

get_header(); ?>

        <section id="primary" class="content-area">
            <div id="content" class="site-content" role="main">

            <?php if ( have_posts() ) : ?>

                <header class="page-header">
                    <h1 class="page-title"><?php printf( __( 'Search Results for: %s', 'shape' ), '<span>' . get_search_query() . '</span>' ); ?></h1>
                </header><!-- .page-header -->

                <?php shape_content_nav( 'nav-above' ); ?>

                <?php /* Start the Loop */ ?>
                <?php while ( have_posts() ) : the_post(); ?>

                    <?php get_template_part( 'content', 'search' ); ?>

                <?php endwhile; ?>

                <?php shape_content_nav( 'nav-below' ); ?>

            <?php else : ?>

                <?php get_template_part( 'no-results', 'search' ); ?>

            <?php endif; ?>

            </div><!-- #content .site-content -->
        </section><!-- #primary .content-area -->

<?php get_sidebar(); ?>
<?php get_footer(); ?>

ruby 1.9: invalid byte sequence in UTF-8

While Nakilon's solution works, at least as far as getting past the error, in my case, I had this weird f-ed up character originating from Microsoft Excel converted to CSV that was registering in ruby as a (get this) cyrillic K which in ruby was a bolded K. To fix this I used 'iso-8859-1' viz. CSV.parse(f, :encoding => "iso-8859-1"), which turned my freaky deaky cyrillic K's into a much more manageable /\xCA/, which I could then remove with string.gsub!(/\xCA/, '')

jQuery Mobile how to check if button is disabled?

Try

$("#deliveryNext").is(":disabled")

The following code works for me:

<script type="text/javascript">
    $(document).ready(function () {
        $("#testButton").button();
        $("#testButton").button('disable');
        alert($('#testButton').is(':disabled'));
    });
</script>
<p>
    <button id="testButton">Testing</button>
</p>

Command copy exited with code 4 when building - Visual Studio restart solves it

I got this error because the user account that TFS Build Service was running under did not have permissions to write to the destination folder. Right-click on the folder-->Properties-->Security.

Asp.net MVC ModelState.Clear

I think is a bug in MVC. I struggled with this issue for hours today.

Given this:

public ViewResult SomeAction(SomeModel model) 
{
    model.SomeString = "some value";
    return View(model); 
}

The view renders with the original model, ignoring the changes. So I thought, maybe it does not like me using the same model, so I tried like this:

public ViewResult SomeAction(SomeModel model) 
{
    var newModel = new SomeModel { SomeString = "some value" };
    return View(newModel); 
}

And still the view renders with the original model. What's odd is, when I put a breakpoint in the view and examine the model, it has the changed value. But the response stream has the old values.

Eventually I discovered the same work around that you did:

public ViewResult SomeAction(SomeModel model) 
{
    var newModel = new SomeModel { SomeString = "some value" };
    ModelState.Clear();
    return View(newModel); 
}

Works as expected.

I don't think this is a "feature," is it?

offsetting an html anchor to adjust for fixed header

Adding to Ziav's answer (with thanks to Alexander Savin), I need to be using the old-school <a name="...">...</a> as we're using <div id="...">...</div> for another purpose in our code. I had some display issues using display: inline-block -- the first line of every <p> element was turning out to be slightly right-indented (on both Webkit and Firefox browsers). I ended up trying other display values and display: table-caption works perfectly for me.

.anchor {
  padding-top: 60px;
  margin-top: -60px;
  display: table-caption;
}

'cannot open git-upload-pack' error in Eclipse when cloning or pushing git repository

I got the similar problem. I just followed the below steps 1. Team > Remote > Configure Fetch from upstream... 2. Provide the https: bit bucket uri then Save and Fetch. 3. Reset the latest commit in your project. Team > Reset > Select the latest commit from remote folder 4. Then synchronize the workspace. Team > Synchronize (in synchronize perspective) 5. Right click on project and overwrite the local copy. 6. Click on Pull icon.

Compare two dates with JavaScript

By far the easiest method is to subtract one date from the other and compare the result.

_x000D_
_x000D_
var oDateOne = new Date();_x000D_
var oDateTwo = new Date();_x000D_
_x000D_
alert(oDateOne - oDateTwo === 0);_x000D_
alert(oDateOne - oDateTwo < 0);_x000D_
alert(oDateOne - oDateTwo > 0);
_x000D_
_x000D_
_x000D_

Where and why do I have to put the "template" and "typename" keywords?

typedef typename Tail::inUnion<U> dummy;

However, I'm not sure you're implementation of inUnion is correct. If I understand correctly, this class is not supposed to be instantiated, therefore the "fail" tab will never avtually fails. Maybe it would be better to indicates whether the type is in the union or not with a simple boolean value.

template <typename T, typename TypeList> struct Contains;

template <typename T, typename Head, typename Tail>
struct Contains<T, UnionNode<Head, Tail> >
{
    enum { result = Contains<T, Tail>::result };
};

template <typename T, typename Tail>
struct Contains<T, UnionNode<T, Tail> >
{
    enum { result = true };
};

template <typename T>
struct Contains<T, void>
{
    enum { result = false };
};

PS: Have a look at Boost::Variant

PS2: Have a look at typelists, notably in Andrei Alexandrescu's book: Modern C++ Design

SQL Server stored procedure Nullable parameter

It looks like you're passing in Null for every argument except for PropertyValueID and DropDownOptionID, right? I don't think any of your IF statements will fire if only these two values are not-null. In short, I think you have a logic error.

Other than that, I would suggest two things...

First, instead of testing for NULL, use this kind syntax on your if statements (it's safer)...

    ELSE IF ISNULL(@UnitValue, 0) != 0 AND ISNULL(@UnitOfMeasureID, 0) = 0

Second, add a meaningful PRINT statement before each UPDATE. That way, when you run the sproc in MSSQL, you can look at the messages and see how far it's actually getting.

Fatal error: Uncaught Error: Call to undefined function mysql_connect()

You can use mysqli_connect($mysql_hostname , $mysql_username) instead of mysql_connect($mysql_hostname , $mysql_username).

mysql_* functions were removed as of PHP 7. You now have two alternatives: MySQLi and PDO.

How to see the changes between two commits without commits in-between?

you can simply pass the 2 commits to git diff like :

-> git diff 0da94be  59ff30c > my.patch
-> git apply my.patch

Android: Share plain text using intent (to all messaging apps)

Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT, "This is my text to send.");
sendIntent.setType("text/plain");

Intent shareIntent = Intent.createChooser(sendIntent, null);
startActivity(shareIntent);

SQL Server Insert Example

Here are 4 ways to insert data into a table.

  1. Simple insertion when the table column sequence is known.

    INSERT INTO Table1 VALUES (1,2,...)

  2. Simple insertion into specified columns of the table.

    INSERT INTO Table1(col2,col4) VALUES (1,2)

  3. Bulk insertion when...

    1. You wish to insert every column of Table2 into Table1
    2. You know the column sequence of Table2
    3. You are certain that the column sequence of Table2 won't change while this statement is being used (perhaps you the statement will only be used once).

    INSERT INTO Table1 {Column sequence} SELECT * FROM Table2

  4. Bulk insertion of selected data into specified columns of Table2.

.

INSERT INTO Table1 (Column1,Column2 ....)
    SELECT Column1,Column2...
       FROM Table2

reading and parsing a TSV file, then manipulating it for saving as CSV (*efficiently*)

You should use the csv module to read the tab-separated value file. Do not read it into memory in one go. Each row you read has all the information you need to write rows to the output CSV file, after all. Keep the output file open throughout.

import csv

with open('sample.txt', newline='') as tsvin, open('new.csv', 'w', newline='') as csvout:
    tsvin = csv.reader(tsvin, delimiter='\t')
    csvout = csv.writer(csvout)

    for row in tsvin:
        count = int(row[4])
        if count > 0:
            csvout.writerows([row[2:4] for _ in range(count)])

or, using the itertools module to do the repeating with itertools.repeat():

from itertools import repeat
import csv

with open('sample.txt', newline='') as tsvin, open('new.csv', 'w', newline='') as csvout:
    tsvin = csv.reader(tsvin, delimiter='\t')
    csvout = csv.writer(csvout)

    for row in tsvin:
        count = int(row[4])
        if count > 0:
            csvout.writerows(repeat(row[2:4], count))

Print multiple arguments in Python

In Python 3.6, f-string is much cleaner.

In earlier version:

print("Total score for %s is %s. " % (name, score))

In Python 3.6:

print(f'Total score for {name} is {score}.')

will do.

It is more efficient and elegant.

What's the simplest way to list conflicted files in Git?

Here's what I use to a list modified files suitable for command line substitution in bash

git diff --numstat -b -w | grep ^[1-9] | cut -f 3

To edit the list use $(cmd) substitution.

vi $(git diff --numstat -b -w | grep ^[1-9] | cut -f 3)

Doesn't work if the file names have spaces. I tried to use sed to escape or quote the spaces and the output list looked right, but the $() substitution still did not behave as desired.

Android RecyclerView addition & removal of items

Incase Anyone wants to implement something like this in Main class instead of Adapter class, you can use:

public void removeAt(int position) {
    peopleListUser.remove(position);

    friendsListRecycler.getAdapter().notifyItemRemoved(position);
    friendsListRecycler.getAdapter().notifyItemRangeChanged(position, peopleListUser.size());
}

where friendsListRecycler is the Adapter name

How to customize Bootstrap 3 tab color

_x000D_
_x000D_
.panel.with-nav-tabs .panel-heading {_x000D_
  padding: 5px 5px 0 5px;_x000D_
}_x000D_
_x000D_
.panel.with-nav-tabs .nav-tabs {_x000D_
  border-bottom: none;_x000D_
}_x000D_
_x000D_
.panel.with-nav-tabs .nav-justified {_x000D_
  margin-bottom: -1px;_x000D_
}_x000D_
_x000D_
_x000D_
/********************************************************************/_x000D_
_x000D_
_x000D_
/*** PANEL DEFAULT ***/_x000D_
_x000D_
.with-nav-tabs.panel-default .nav-tabs>li>a,_x000D_
.with-nav-tabs.panel-default .nav-tabs>li>a:hover,_x000D_
.with-nav-tabs.panel-default .nav-tabs>li>a:focus {_x000D_
  color: #777;_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-default .nav-tabs>.open>a,_x000D_
.with-nav-tabs.panel-default .nav-tabs>.open>a:hover,_x000D_
.with-nav-tabs.panel-default .nav-tabs>.open>a:focus,_x000D_
.with-nav-tabs.panel-default .nav-tabs>li>a:hover,_x000D_
.with-nav-tabs.panel-default .nav-tabs>li>a:focus {_x000D_
  color: #777;_x000D_
  background-color: #ddd;_x000D_
  border-color: transparent;_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-default .nav-tabs>li.active>a,_x000D_
.with-nav-tabs.panel-default .nav-tabs>li.active>a:hover,_x000D_
.with-nav-tabs.panel-default .nav-tabs>li.active>a:focus {_x000D_
  color: #555;_x000D_
  background-color: #fff;_x000D_
  border-color: #ddd;_x000D_
  border-bottom-color: transparent;_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-default .nav-tabs>li.dropdown .dropdown-menu {_x000D_
  background-color: #f5f5f5;_x000D_
  border-color: #ddd;_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-default .nav-tabs>li.dropdown .dropdown-menu>li>a {_x000D_
  color: #777;_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-default .nav-tabs>li.dropdown .dropdown-menu>li>a:hover,_x000D_
.with-nav-tabs.panel-default .nav-tabs>li.dropdown .dropdown-menu>li>a:focus {_x000D_
  background-color: #ddd;_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-default .nav-tabs>li.dropdown .dropdown-menu>.active>a,_x000D_
.with-nav-tabs.panel-default .nav-tabs>li.dropdown .dropdown-menu>.active>a:hover,_x000D_
.with-nav-tabs.panel-default .nav-tabs>li.dropdown .dropdown-menu>.active>a:focus {_x000D_
  color: #fff;_x000D_
  background-color: #555;_x000D_
}_x000D_
_x000D_
_x000D_
/********************************************************************/_x000D_
_x000D_
_x000D_
/*** PANEL PRIMARY ***/_x000D_
_x000D_
.with-nav-tabs.panel-primary .nav-tabs>li>a,_x000D_
.with-nav-tabs.panel-primary .nav-tabs>li>a:hover,_x000D_
.with-nav-tabs.panel-primary .nav-tabs>li>a:focus {_x000D_
  color: #fff;_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-primary .nav-tabs>.open>a,_x000D_
.with-nav-tabs.panel-primary .nav-tabs>.open>a:hover,_x000D_
.with-nav-tabs.panel-primary .nav-tabs>.open>a:focus,_x000D_
.with-nav-tabs.panel-primary .nav-tabs>li>a:hover,_x000D_
.with-nav-tabs.panel-primary .nav-tabs>li>a:focus {_x000D_
  color: #fff;_x000D_
  background-color: #3071a9;_x000D_
  border-color: transparent;_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-primary .nav-tabs>li.active>a,_x000D_
.with-nav-tabs.panel-primary .nav-tabs>li.active>a:hover,_x000D_
.with-nav-tabs.panel-primary .nav-tabs>li.active>a:focus {_x000D_
  color: #428bca;_x000D_
  background-color: #fff;_x000D_
  border-color: #428bca;_x000D_
  border-bottom-color: transparent;_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-primary .nav-tabs>li.dropdown .dropdown-menu {_x000D_
  background-color: #428bca;_x000D_
  border-color: #3071a9;_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-primary .nav-tabs>li.dropdown .dropdown-menu>li>a {_x000D_
  color: #fff;_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-primary .nav-tabs>li.dropdown .dropdown-menu>li>a:hover,_x000D_
.with-nav-tabs.panel-primary .nav-tabs>li.dropdown .dropdown-menu>li>a:focus {_x000D_
  background-color: #3071a9;_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-primary .nav-tabs>li.dropdown .dropdown-menu>.active>a,_x000D_
.with-nav-tabs.panel-primary .nav-tabs>li.dropdown .dropdown-menu>.active>a:hover,_x000D_
.with-nav-tabs.panel-primary .nav-tabs>li.dropdown .dropdown-menu>.active>a:focus {_x000D_
  background-color: #4a9fe9;_x000D_
}_x000D_
_x000D_
_x000D_
/********************************************************************/_x000D_
_x000D_
_x000D_
/*** PANEL SUCCESS ***/_x000D_
_x000D_
.with-nav-tabs.panel-success .nav-tabs>li>a,_x000D_
.with-nav-tabs.panel-success .nav-tabs>li>a:hover,_x000D_
.with-nav-tabs.panel-success .nav-tabs>li>a:focus {_x000D_
  color: #3c763d;_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-success .nav-tabs>.open>a,_x000D_
.with-nav-tabs.panel-success .nav-tabs>.open>a:hover,_x000D_
.with-nav-tabs.panel-success .nav-tabs>.open>a:focus,_x000D_
.with-nav-tabs.panel-success .nav-tabs>li>a:hover,_x000D_
.with-nav-tabs.panel-success .nav-tabs>li>a:focus {_x000D_
  color: #3c763d;_x000D_
  background-color: #d6e9c6;_x000D_
  border-color: transparent;_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-success .nav-tabs>li.active>a,_x000D_
.with-nav-tabs.panel-success .nav-tabs>li.active>a:hover,_x000D_
.with-nav-tabs.panel-success .nav-tabs>li.active>a:focus {_x000D_
  color: #3c763d;_x000D_
  background-color: #fff;_x000D_
  border-color: #d6e9c6;_x000D_
  border-bottom-color: transparent;_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-success .nav-tabs>li.dropdown .dropdown-menu {_x000D_
  background-color: #dff0d8;_x000D_
  border-color: #d6e9c6;_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-success .nav-tabs>li.dropdown .dropdown-menu>li>a {_x000D_
  color: #3c763d;_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-success .nav-tabs>li.dropdown .dropdown-menu>li>a:hover,_x000D_
.with-nav-tabs.panel-success .nav-tabs>li.dropdown .dropdown-menu>li>a:focus {_x000D_
  background-color: #d6e9c6;_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-success .nav-tabs>li.dropdown .dropdown-menu>.active>a,_x000D_
.with-nav-tabs.panel-success .nav-tabs>li.dropdown .dropdown-menu>.active>a:hover,_x000D_
.with-nav-tabs.panel-success .nav-tabs>li.dropdown .dropdown-menu>.active>a:focus {_x000D_
  color: #fff;_x000D_
  background-color: #3c763d;_x000D_
}_x000D_
_x000D_
_x000D_
/********************************************************************/_x000D_
_x000D_
_x000D_
/*** PANEL INFO ***/_x000D_
_x000D_
.with-nav-tabs.panel-info .nav-tabs>li>a,_x000D_
.with-nav-tabs.panel-info .nav-tabs>li>a:hover,_x000D_
.with-nav-tabs.panel-info .nav-tabs>li>a:focus {_x000D_
  color: #31708f;_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-info .nav-tabs>.open>a,_x000D_
.with-nav-tabs.panel-info .nav-tabs>.open>a:hover,_x000D_
.with-nav-tabs.panel-info .nav-tabs>.open>a:focus,_x000D_
.with-nav-tabs.panel-info .nav-tabs>li>a:hover,_x000D_
.with-nav-tabs.panel-info .nav-tabs>li>a:focus {_x000D_
  color: #31708f;_x000D_
  background-color: #bce8f1;_x000D_
  border-color: transparent;_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-info .nav-tabs>li.active>a,_x000D_
.with-nav-tabs.panel-info .nav-tabs>li.active>a:hover,_x000D_
.with-nav-tabs.panel-info .nav-tabs>li.active>a:focus {_x000D_
  color: #31708f;_x000D_
  background-color: #fff;_x000D_
  border-color: #bce8f1;_x000D_
  border-bottom-color: transparent;_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-info .nav-tabs>li.dropdown .dropdown-menu {_x000D_
  background-color: #d9edf7;_x000D_
  border-color: #bce8f1;_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-info .nav-tabs>li.dropdown .dropdown-menu>li>a {_x000D_
  color: #31708f;_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-info .nav-tabs>li.dropdown .dropdown-menu>li>a:hover,_x000D_
.with-nav-tabs.panel-info .nav-tabs>li.dropdown .dropdown-menu>li>a:focus {_x000D_
  background-color: #bce8f1;_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-info .nav-tabs>li.dropdown .dropdown-menu>.active>a,_x000D_
.with-nav-tabs.panel-info .nav-tabs>li.dropdown .dropdown-menu>.active>a:hover,_x000D_
.with-nav-tabs.panel-info .nav-tabs>li.dropdown .dropdown-menu>.active>a:focus {_x000D_
  color: #fff;_x000D_
  background-color: #31708f;_x000D_
}_x000D_
_x000D_
_x000D_
/********************************************************************/_x000D_
_x000D_
_x000D_
/*** PANEL WARNING ***/_x000D_
_x000D_
.with-nav-tabs.panel-warning .nav-tabs>li>a,_x000D_
.with-nav-tabs.panel-warning .nav-tabs>li>a:hover,_x000D_
.with-nav-tabs.panel-warning .nav-tabs>li>a:focus {_x000D_
  color: #8a6d3b;_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-warning .nav-tabs>.open>a,_x000D_
.with-nav-tabs.panel-warning .nav-tabs>.open>a:hover,_x000D_
.with-nav-tabs.panel-warning .nav-tabs>.open>a:focus,_x000D_
.with-nav-tabs.panel-warning .nav-tabs>li>a:hover,_x000D_
.with-nav-tabs.panel-warning .nav-tabs>li>a:focus {_x000D_
  color: #8a6d3b;_x000D_
  background-color: #faebcc;_x000D_
  border-color: transparent;_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-warning .nav-tabs>li.active>a,_x000D_
.with-nav-tabs.panel-warning .nav-tabs>li.active>a:hover,_x000D_
.with-nav-tabs.panel-warning .nav-tabs>li.active>a:focus {_x000D_
  color: #8a6d3b;_x000D_
  background-color: #fff;_x000D_
  border-color: #faebcc;_x000D_
  border-bottom-color: transparent;_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-warning .nav-tabs>li.dropdown .dropdown-menu {_x000D_
  background-color: #fcf8e3;_x000D_
  border-color: #faebcc;_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-warning .nav-tabs>li.dropdown .dropdown-menu>li>a {_x000D_
  color: #8a6d3b;_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-warning .nav-tabs>li.dropdown .dropdown-menu>li>a:hover,_x000D_
.with-nav-tabs.panel-warning .nav-tabs>li.dropdown .dropdown-menu>li>a:focus {_x000D_
  background-color: #faebcc;_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-warning .nav-tabs>li.dropdown .dropdown-menu>.active>a,_x000D_
.with-nav-tabs.panel-warning .nav-tabs>li.dropdown .dropdown-menu>.active>a:hover,_x000D_
.with-nav-tabs.panel-warning .nav-tabs>li.dropdown .dropdown-menu>.active>a:focus {_x000D_
  color: #fff;_x000D_
  background-color: #8a6d3b;_x000D_
}_x000D_
_x000D_
_x000D_
/********************************************************************/_x000D_
_x000D_
_x000D_
/*** PANEL DANGER ***/_x000D_
_x000D_
.with-nav-tabs.panel-danger .nav-tabs>li>a,_x000D_
.with-nav-tabs.panel-danger .nav-tabs>li>a:hover,_x000D_
.with-nav-tabs.panel-danger .nav-tabs>li>a:focus {_x000D_
  color: #a94442;_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-danger .nav-tabs>.open>a,_x000D_
.with-nav-tabs.panel-danger .nav-tabs>.open>a:hover,_x000D_
.with-nav-tabs.panel-danger .nav-tabs>.open>a:focus,_x000D_
.with-nav-tabs.panel-danger .nav-tabs>li>a:hover,_x000D_
.with-nav-tabs.panel-danger .nav-tabs>li>a:focus {_x000D_
  color: #a94442;_x000D_
  background-color: #ebccd1;_x000D_
  border-color: transparent;_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-danger .nav-tabs>li.active>a,_x000D_
.with-nav-tabs.panel-danger .nav-tabs>li.active>a:hover,_x000D_
.with-nav-tabs.panel-danger .nav-tabs>li.active>a:focus {_x000D_
  color: #a94442;_x000D_
  background-color: #fff;_x000D_
  border-color: #ebccd1;_x000D_
  border-bottom-color: transparent;_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-danger .nav-tabs>li.dropdown .dropdown-menu {_x000D_
  background-color: #f2dede;_x000D_
  /* bg color */_x000D_
  border-color: #ebccd1;_x000D_
  /* border color */_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-danger .nav-tabs>li.dropdown .dropdown-menu>li>a {_x000D_
  color: #a94442;_x000D_
  /* normal text color */_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-danger .nav-tabs>li.dropdown .dropdown-menu>li>a:hover,_x000D_
.with-nav-tabs.panel-danger .nav-tabs>li.dropdown .dropdown-menu>li>a:focus {_x000D_
  background-color: #ebccd1;_x000D_
  /* hover bg color */_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-danger .nav-tabs>li.dropdown .dropdown-menu>.active>a,_x000D_
.with-nav-tabs.panel-danger .nav-tabs>li.dropdown .dropdown-menu>.active>a:hover,_x000D_
.with-nav-tabs.panel-danger .nav-tabs>li.dropdown .dropdown-menu>.active>a:focus {_x000D_
  color: #fff;_x000D_
  /* active text color */_x000D_
  background-color: #a94442;_x000D_
  /* active bg color */_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<link href="//netdna.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">_x000D_
<script src="//netdna.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>_x000D_
<!------ Include the above in your HEAD tag ---------->_x000D_
_x000D_
<div class="container">_x000D_
  <div class="page-header">_x000D_
    <h1>Panels with nav tabs.<span class="pull-right label label-default">:)</span></h1>_x000D_
  </div>_x000D_
  <div class="row">_x000D_
    <div class="col-md-6">_x000D_
      <div class="panel with-nav-tabs panel-default">_x000D_
        <div class="panel-heading">_x000D_
          <ul class="nav nav-tabs">_x000D_
            <li class="active"><a href="#tab1default" data-toggle="tab">Default 1</a></li>_x000D_
            <li><a href="#tab2default" data-toggle="tab">Default 2</a></li>_x000D_
            <li><a href="#tab3default" data-toggle="tab">Default 3</a></li>_x000D_
            <li class="dropdown">_x000D_
              <a href="#" data-toggle="dropdown">Dropdown <span class="caret"></span></a>_x000D_
              <ul class="dropdown-menu" role="menu">_x000D_
                <li><a href="#tab4default" data-toggle="tab">Default 4</a></li>_x000D_
                <li><a href="#tab5default" data-toggle="tab">Default 5</a></li>_x000D_
              </ul>_x000D_
            </li>_x000D_
          </ul>_x000D_
        </div>_x000D_
        <div class="panel-body">_x000D_
          <div class="tab-content">_x000D_
            <div class="tab-pane fade in active" id="tab1default">Default 1</div>_x000D_
            <div class="tab-pane fade" id="tab2default">Default 2</div>_x000D_
            <div class="tab-pane fade" id="tab3default">Default 3</div>_x000D_
            <div class="tab-pane fade" id="tab4default">Default 4</div>_x000D_
            <div class="tab-pane fade" id="tab5default">Default 5</div>_x000D_
          </div>_x000D_
        </div>_x000D_
      </div>_x000D_
    </div>_x000D_
    <div class="col-md-6">_x000D_
      <div class="panel with-nav-tabs panel-primary">_x000D_
        <div class="panel-heading">_x000D_
          <ul class="nav nav-tabs">_x000D_
            <li class="active"><a href="#tab1primary" data-toggle="tab">Primary 1</a></li>_x000D_
            <li><a href="#tab2primary" data-toggle="tab">Primary 2</a></li>_x000D_
            <li><a href="#tab3primary" data-toggle="tab">Primary 3</a></li>_x000D_
            <li class="dropdown">_x000D_
              <a href="#" data-toggle="dropdown">Dropdown <span class="caret"></span></a>_x000D_
              <ul class="dropdown-menu" role="menu">_x000D_
                <li><a href="#tab4primary" data-toggle="tab">Primary 4</a></li>_x000D_
                <li><a href="#tab5primary" data-toggle="tab">Primary 5</a></li>_x000D_
              </ul>_x000D_
            </li>_x000D_
          </ul>_x000D_
        </div>_x000D_
        <div class="panel-body">_x000D_
          <div class="tab-content">_x000D_
            <div class="tab-pane fade in active" id="tab1primary">Primary 1</div>_x000D_
            <div class="tab-pane fade" id="tab2primary">Primary 2</div>_x000D_
            <div class="tab-pane fade" id="tab3primary">Primary 3</div>_x000D_
            <div class="tab-pane fade" id="tab4primary">Primary 4</div>_x000D_
            <div class="tab-pane fade" id="tab5primary">Primary 5</div>_x000D_
          </div>_x000D_
        </div>_x000D_
      </div>_x000D_
    </div>_x000D_
  </div>_x000D_
</div>_x000D_
<div class="container">_x000D_
  <div class="row">_x000D_
    <div class="col-md-6">_x000D_
      <div class="panel with-nav-tabs panel-success">_x000D_
        <div class="panel-heading">_x000D_
          <ul class="nav nav-tabs">_x000D_
            <li class="active"><a href="#tab1success" data-toggle="tab">Success 1</a></li>_x000D_
            <li><a href="#tab2success" data-toggle="tab">Success 2</a></li>_x000D_
            <li><a href="#tab3success" data-toggle="tab">Success 3</a></li>_x000D_
            <li class="dropdown">_x000D_
              <a href="#" data-toggle="dropdown">Dropdown <span class="caret"></span></a>_x000D_
              <ul class="dropdown-menu" role="menu">_x000D_
                <li><a href="#tab4success" data-toggle="tab">Success 4</a></li>_x000D_
                <li><a href="#tab5success" data-toggle="tab">Success 5</a></li>_x000D_
              </ul>_x000D_
            </li>_x000D_
          </ul>_x000D_
        </div>_x000D_
        <div class="panel-body">_x000D_
          <div class="tab-content">_x000D_
            <div class="tab-pane fade in active" id="tab1success">Success 1</div>_x000D_
            <div class="tab-pane fade" id="tab2success">Success 2</div>_x000D_
            <div class="tab-pane fade" id="tab3success">Success 3</div>_x000D_
            <div class="tab-pane fade" id="tab4success">Success 4</div>_x000D_
            <div class="tab-pane fade" id="tab5success">Success 5</div>_x000D_
          </div>_x000D_
        </div>_x000D_
      </div>_x000D_
    </div>_x000D_
    <div class="col-md-6">_x000D_
      <div class="panel with-nav-tabs panel-info">_x000D_
        <div class="panel-heading">_x000D_
          <ul class="nav nav-tabs">_x000D_
            <li class="active"><a href="#tab1info" data-toggle="tab">Info 1</a></li>_x000D_
            <li><a href="#tab2info" data-toggle="tab">Info 2</a></li>_x000D_
            <li><a href="#tab3info" data-toggle="tab">Info 3</a></li>_x000D_
            <li class="dropdown">_x000D_
              <a href="#" data-toggle="dropdown">Dropdown <span class="caret"></span></a>_x000D_
              <ul class="dropdown-menu" role="menu">_x000D_
                <li><a href="#tab4info" data-toggle="tab">Info 4</a></li>_x000D_
                <li><a href="#tab5info" data-toggle="tab">Info 5</a></li>_x000D_
              </ul>_x000D_
            </li>_x000D_
          </ul>_x000D_
        </div>_x000D_
        <div class="panel-body">_x000D_
          <div class="tab-content">_x000D_
            <div class="tab-pane fade in active" id="tab1info">Info 1</div>_x000D_
            <div class="tab-pane fade" id="tab2info">Info 2</div>_x000D_
            <div class="tab-pane fade" id="tab3info">Info 3</div>_x000D_
            <div class="tab-pane fade" id="tab4info">Info 4</div>_x000D_
            <div class="tab-pane fade" id="tab5info">Info 5</div>_x000D_
          </div>_x000D_
        </div>_x000D_
      </div>_x000D_
    </div>_x000D_
  </div>_x000D_
</div>_x000D_
<div class="container">_x000D_
  <div class="row">_x000D_
    <div class="col-md-6">_x000D_
      <div class="panel with-nav-tabs panel-warning">_x000D_
        <div class="panel-heading">_x000D_
          <ul class="nav nav-tabs">_x000D_
            <li class="active"><a href="#tab1warning" data-toggle="tab">Warning 1</a></li>_x000D_
            <li><a href="#tab2warning" data-toggle="tab">Warning 2</a></li>_x000D_
            <li><a href="#tab3warning" data-toggle="tab">Warning 3</a></li>_x000D_
            <li class="dropdown">_x000D_
              <a href="#" data-toggle="dropdown">Dropdown <span class="caret"></span></a>_x000D_
              <ul class="dropdown-menu" role="menu">_x000D_
                <li><a href="#tab4warning" data-toggle="tab">Warning 4</a></li>_x000D_
                <li><a href="#tab5warning" data-toggle="tab">Warning 5</a></li>_x000D_
              </ul>_x000D_
            </li>_x000D_
          </ul>_x000D_
        </div>_x000D_
        <div class="panel-body">_x000D_
          <div class="tab-content">_x000D_
            <div class="tab-pane fade in active" id="tab1warning">Warning 1</div>_x000D_
            <div class="tab-pane fade" id="tab2warning">Warning 2</div>_x000D_
            <div class="tab-pane fade" id="tab3warning">Warning 3</div>_x000D_
            <div class="tab-pane fade" id="tab4warning">Warning 4</div>_x000D_
            <div class="tab-pane fade" id="tab5warning">Warning 5</div>_x000D_
          </div>_x000D_
        </div>_x000D_
      </div>_x000D_
    </div>_x000D_
    <div class="col-md-6">_x000D_
      <div class="panel with-nav-tabs panel-danger">_x000D_
        <div class="panel-heading">_x000D_
          <ul class="nav nav-tabs">_x000D_
            <li class="active"><a href="#tab1danger" data-toggle="tab">Danger 1</a></li>_x000D_
            <li><a href="#tab2danger" data-toggle="tab">Danger 2</a></li>_x000D_
            <li><a href="#tab3danger" data-toggle="tab">Danger 3</a></li>_x000D_
            <li class="dropdown">_x000D_
              <a href="#" data-toggle="dropdown">Dropdown <span class="caret"></span></a>_x000D_
              <ul class="dropdown-menu" role="menu">_x000D_
                <li><a href="#tab4danger" data-toggle="tab">Danger 4</a></li>_x000D_
                <li><a href="#tab5danger" data-toggle="tab">Danger 5</a></li>_x000D_
              </ul>_x000D_
            </li>_x000D_
          </ul>_x000D_
        </div>_x000D_
        <div class="panel-body">_x000D_
          <div class="tab-content">_x000D_
            <div class="tab-pane fade in active" id="tab1danger">Danger 1</div>_x000D_
            <div class="tab-pane fade" id="tab2danger">Danger 2</div>_x000D_
            <div class="tab-pane fade" id="tab3danger">Danger 3</div>_x000D_
            <div class="tab-pane fade" id="tab4danger">Danger 4</div>_x000D_
            <div class="tab-pane fade" id="tab5danger">Danger 5</div>_x000D_
          </div>_x000D_
        </div>_x000D_
      </div>_x000D_
    </div>_x000D_
  </div>_x000D_
</div>_x000D_
<br/>
_x000D_
_x000D_
_x000D_

Bridged networking not working in Virtualbox under Windows 10

First of all you have to create a VirtualBox Host-Only Ethernet adapter

In Virtualbox :

  • Go to File > Preferences On the Network tab select Host only Networks click on "add a Host-only adapter" give it a name by default it is "VirtualBox Host-Only Ethernet adapter"

In Windows :

  • go to Network connections on Windows and highlight both the real adapter and the new virtual ethernet adapter that you just created.
  • Right click and select "Bridge Connections", it's going to create a network bridge in Windows.

Now configure your VM :

  • in the Network part you can activate a new adapter and then select Attached to Host only adapter
  • Choose the VirtualBox Host-Only Ethernet adapter you have just created

You can now configure your static IP Address by modifying /etc/network/interfaces :

auto eth0
iface eth0 inet static
address 10.1.1.100
netmask 255.255.255.0
gateway 10.1.1.1

You can now restart eth0 by doing :

sudo ifdown eth0
sudo ifup eth0

Some wireless adapters don't work

JAX-RS — How to return JSON and HTTP status code together?

JAX-RS has support for standard/custom HTTP codes. See ResponseBuilder and ResponseStatus, for example:

http://jackson.codehaus.org/javadoc/jax-rs/1.0/javax/ws/rs/core/Response.ResponseBuilder.html#status%28javax.ws.rs.core.Response.Status%29

Keep in mind that JSON information is more about the data associated with the resource/application. The HTTP codes are more about the status of the CRUD operation being requested. (at least that is how it's supposed to be in REST-ful systems)

How can I mock the JavaScript window object using Jest?

In my component I need access to window.location.search. This is what I did in the Jest test:

Object.defineProperty(global, "window", {
  value: {
    location: {
      search: "test"
    }
  }
});

In case window properties must be different in different tests, we can put window mocking into a function, and make it writable in order to override for different tests:

function mockWindow(search, pathname) {
  Object.defineProperty(global, "window", {
    value: {
      location: {
        search,
        pathname
      }
    },
    writable: true
  });
}

And reset after each test:

afterEach(() => {
  delete global.window.location;
});

Get POST data in C#/ASP.NET

I'm a little surprised that this question has been asked so many times before, but the most reuseable and friendly solution hasn't been documented.

I often have webpages using AngularJS, and when I click on a Save button, I'll "POST" this data back to my .aspx page or .ashx handler to save this back to the database. The data will be in the form of a JSON record.

On the server, to turn the raw posted data back into a C# class, here's what I would do.

First, define a C# class which will contain the posted data.

Supposing my webpage is posting JSON data like this:

{
    "UserID" : 1,
    "FirstName" : "Mike",
    "LastName" : "Mike",
    "Address1" : "10 Really Street",
    "Address2" : "London"
}

Then I'd define a C# class like this...

public class JSONRequest
{
    public int UserID { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Address1 { get; set; }
    public string Address2 { get; set; }
}

(These classes can be nested, but the structure must match the format of the JSON data. So, if you're posting a JSON User record, with a list of Order records within it, your C# class should also contain a List<> of Order records.)

Now, in my .aspx.cs or .ashx file, I just need to do this, and leave JSON.Net to do the hard work...

    protected void Page_Load(object sender, EventArgs e)
    {
        string jsonString = "";
        HttpContext.Current.Request.InputStream.Position = 0;
        using (StreamReader inputStream = new StreamReader(this.Request.InputStream))
        {
            jsonString = inputStream.ReadToEnd();
        }
        JSONRequest oneQuestion = JsonConvert.DeserializeObject<JSONRequest>(jsonString);

And that's it. You now have a JSONRequest class containing the various fields which were POSTed to your server.

How to compile c# in Microsoft's new Visual Studio Code?

Install the extension "Code Runner". Check if you can compile your program with csc (ex.: csc hello.cs). The command csc is shipped with Mono. Then add this to your VS Code user settings:

"code-runner.executorMap": {
        "csharp": "echo '# calling mono\n' && cd $dir && csc /nologo $fileName && mono $dir$fileNameWithoutExt.exe",
        // "csharp": "echo '# calling dotnet run\n' && dotnet run"
    }

Open your C# file and use the execution key of Code Runner.

Edit: also added dotnet run, so you can choose how you want to execute your program: with Mono, or with dotnet. If you choose dotnet, then first create the project (dotnet new console, dotnet restore).

How to convert an entire MySQL database characterset and collation to UTF-8?

  1. Make a backup!

  2. Then you need to set the default char sets on the database. This does not convert existing tables, it only sets the default for newly created tables.

    ALTER DATABASE dbname CHARACTER SET utf8 COLLATE utf8_general_ci;
    
  3. Then, you will need to convert the char set on all existing tables and their columns. This assumes that your current data is actually in the current char set. If your columns are set to one char set but your data is really stored in another then you will need to check the MySQL manual on how to handle this.

    ALTER TABLE tbl_name CONVERT TO CHARACTER SET utf8 COLLATE utf8_general_ci;
    

Getting IP address of client

I do like this,you can have a try

public String getIpAddr(HttpServletRequest request) {      
   String ip = request.getHeader("x-forwarded-for");      
   if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {      
       ip = request.getHeader("Proxy-Client-IP");      
   }      
   if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {      
       ip = request.getHeader("WL-Proxy-Client-IP");      
   }      
   if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {      
       ip = request.getRemoteAddr();      
   }      
   return ip;      
}   

Why doesn't Python have multiline comments?

From The Zen of Python:

There should be one-- and preferably only one --obvious way to do it.

Difference between @click and v-on:click Vuejs

v-bind and v-on are two frequently used directives in vuejs html template. So they provided a shorthand notation for the both of them as follows:

You can replace v-on: with @

v-on:click='someFunction'

as:

@click='someFunction'

Another example:

v-on:keyup='someKeyUpFunction'

as:

@keyup='someKeyUpFunction'

Similarly, v-bind with :

v-bind:href='var1'

Can be written as:

:href='var1'

Hope it helps!

jQuery AJAX single file upload

After hours of searching and looking for answer, finally I made it!!!!! Code is below :))))

HTML:

<form id="fileinfo" enctype="multipart/form-data" method="post" name="fileinfo">
    <label>File to stash:</label>
    <input type="file" name="file" required />
</form>
<input type="button" value="Stash the file!"></input>
<div id="output"></div>

jQuery:

$(function(){
    $('#uploadBTN').on('click', function(){ 
        var fd = new FormData($("#fileinfo"));
        //fd.append("CustomField", "This is some extra data");
        $.ajax({
            url: 'upload.php',  
            type: 'POST',
            data: fd,
            success:function(data){
                $('#output').html(data);
            },
            cache: false,
            contentType: false,
            processData: false
        });
    });
});

In the upload.php file you can access the data passed with $_FILES['file'].

Thanks everyone for trying to help:)

I took the answer from here (with some changes) MDN

jquery get all form elements: input, textarea & select

JQuery serialize function makes it pretty easy to get all form elements.

Demo: http://jsfiddle.net/55xnJ/2/

$("form").serialize(); //get all form elements at once 

//result would be like this:
single=Single&multiple=Multiple&multiple=Multiple3&check=check2&radio=radio1

How to Sort Date in descending order From Arraylist Date in android?

If date in string format convert it to date format for each object :

String argmodifiledDate = "2014-04-06 22:26:15";
SimpleDateFormat  format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");  
            try
            {
                this.modifiledDate = format.parse(argmodifiledDate);
            }
            catch (ParseException e)
            {

                e.printStackTrace();
            }

Then sort the arraylist in descending order :

ArrayList<Document> lstDocument= this.objDocument.getArlstDocuments();
        Collections.sort(lstDocument, new Comparator<Document>() {
              public int compare(Document o1, Document o2) {
                  if (o1.getModifiledDate() == null || o2.getModifiledDate() == null)
                    return 0;     
                  return o2.getModifiledDate().compareTo(o1.getModifiledDate());
              }
            });

find vs find_by vs where

Edit: This answer is very old and other, better answers have come up since this post was made. I'd advise looking at the one posted below by @Hossam Khamis for more details.

Use whichever one you feel suits your needs best.

The find method is usually used to retrieve a row by ID:

Model.find(1)

It's worth noting that find will throw an exception if the item is not found by the attribute that you supply. Use where (as described below, which will return an empty array if the attribute is not found) to avoid an exception being thrown.

Other uses of find are usually replaced with things like this:

Model.all
Model.first

find_by is used as a helper when you're searching for information within a column, and it maps to such with naming conventions. For instance, if you have a column named name in your database, you'd use the following syntax:

Model.find_by(name: "Bob")

.where is more of a catch all that lets you use a bit more complex logic for when the conventional helpers won't do, and it returns an array of items that match your conditions (or an empty array otherwise).

PHP foreach loop key value

You can also use array_keys() . Newbie friendly:

$keys = array_keys($arrayToWalk);
$arraySize = count($arrayToWalk); 

for($i=0; $i < $arraySize; $i++) {
    echo '<option value="' . $keys[$i] . '">' . $arrayToWalk[$keys[$i]] . '</option>';
}

Visual Studio: Relative Assembly References Paths

To expand upon Pavel Minaev's original comment - The GUI for Visual Studio supports relative references with the assumption that your .sln is the root of the relative reference. So if you have a solution C:\myProj\myProj.sln, any references you add in subfolders of C:\myProj\ are automatically added as relative references.

To add a relative reference in a separate directory, such as C:/myReferences/myDLL.dll, do the following:

  1. Add the reference in Visual Studio GUI by right-clicking the project in Solution Explorer and selecting Add Reference...
  2. Find the *.csproj where this reference exist and open it in a text editor
  3. Edit the < HintPath > to be equal to

    <HintPath>..\..\myReferences\myDLL.dll</HintPath>

This now references C:\myReferences\myDLL.dll.

Hope this helps.

How to change the background color on a input checkbox with css?

I always use pseudo elements :before and :after for changing the appearance of checkboxes and radio buttons. it's works like a charm.

Refer this link for more info

CODEPEN

Steps

  1. Hide the default checkbox using css rules like visibility:hidden or opacity:0 or position:absolute;left:-9999px etc.
  2. Create a fake checkbox using :before element and pass either an empty or a non-breaking space '\00a0';
  3. When the checkbox is in :checked state, pass the unicode content: "\2713", which is a checkmark;
  4. Add :focus style to make the checkbox accessible.
  5. Done

Here is how I did it.

_x000D_
_x000D_
.box {_x000D_
  background: #666666;_x000D_
  color: #ffffff;_x000D_
  width: 250px;_x000D_
  padding: 10px;_x000D_
  margin: 1em auto;_x000D_
}_x000D_
p {_x000D_
  margin: 1.5em 0;_x000D_
  padding: 0;_x000D_
}_x000D_
input[type="checkbox"] {_x000D_
  visibility: hidden;_x000D_
}_x000D_
label {_x000D_
  cursor: pointer;_x000D_
}_x000D_
input[type="checkbox"] + label:before {_x000D_
  border: 1px solid #333;_x000D_
  content: "\00a0";_x000D_
  display: inline-block;_x000D_
  font: 16px/1em sans-serif;_x000D_
  height: 16px;_x000D_
  margin: 0 .25em 0 0;_x000D_
  padding: 0;_x000D_
  vertical-align: top;_x000D_
  width: 16px;_x000D_
}_x000D_
input[type="checkbox"]:checked + label:before {_x000D_
  background: #fff;_x000D_
  color: #333;_x000D_
  content: "\2713";_x000D_
  text-align: center;_x000D_
}_x000D_
input[type="checkbox"]:checked + label:after {_x000D_
  font-weight: bold;_x000D_
}_x000D_
_x000D_
input[type="checkbox"]:focus + label::before {_x000D_
    outline: rgb(59, 153, 252) auto 5px;_x000D_
}
_x000D_
<div class="content">_x000D_
  <div class="box">_x000D_
    <p>_x000D_
      <input type="checkbox" id="c1" name="cb">_x000D_
      <label for="c1">Option 01</label>_x000D_
    </p>_x000D_
    <p>_x000D_
      <input type="checkbox" id="c2" name="cb">_x000D_
      <label for="c2">Option 02</label>_x000D_
    </p>_x000D_
    <p>_x000D_
      <input type="checkbox" id="c3" name="cb">_x000D_
      <label for="c3">Option 03</label>_x000D_
    </p>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Much more stylish using :before and :after

_x000D_
_x000D_
body{_x000D_
  font-family: sans-serif;  _x000D_
}_x000D_
_x000D_
.container {_x000D_
    margin-top: 50px;_x000D_
    margin-left: 20px;_x000D_
    margin-right: 20px;_x000D_
}_x000D_
.checkbox {_x000D_
    width: 100%;_x000D_
    margin: 15px auto;_x000D_
    position: relative;_x000D_
    display: block;_x000D_
}_x000D_
_x000D_
.checkbox input[type="checkbox"] {_x000D_
    width: auto;_x000D_
    opacity: 0.00000001;_x000D_
    position: absolute;_x000D_
    left: 0;_x000D_
    margin-left: -20px;_x000D_
}_x000D_
.checkbox label {_x000D_
    position: relative;_x000D_
}_x000D_
.checkbox label:before {_x000D_
    content: '';_x000D_
    position: absolute;_x000D_
    left: 0;_x000D_
    top: 0;_x000D_
    margin: 4px;_x000D_
    width: 22px;_x000D_
    height: 22px;_x000D_
    transition: transform 0.28s ease;_x000D_
    border-radius: 3px;_x000D_
    border: 2px solid #7bbe72;_x000D_
}_x000D_
.checkbox label:after {_x000D_
  content: '';_x000D_
    display: block;_x000D_
    width: 10px;_x000D_
    height: 5px;_x000D_
    border-bottom: 2px solid #7bbe72;_x000D_
    border-left: 2px solid #7bbe72;_x000D_
    -webkit-transform: rotate(-45deg) scale(0);_x000D_
    transform: rotate(-45deg) scale(0);_x000D_
    transition: transform ease 0.25s;_x000D_
    will-change: transform;_x000D_
    position: absolute;_x000D_
    top: 12px;_x000D_
    left: 10px;_x000D_
}_x000D_
.checkbox input[type="checkbox"]:checked ~ label::before {_x000D_
    color: #7bbe72;_x000D_
}_x000D_
_x000D_
.checkbox input[type="checkbox"]:checked ~ label::after {_x000D_
    -webkit-transform: rotate(-45deg) scale(1);_x000D_
    transform: rotate(-45deg) scale(1);_x000D_
}_x000D_
_x000D_
.checkbox label {_x000D_
    min-height: 34px;_x000D_
    display: block;_x000D_
    padding-left: 40px;_x000D_
    margin-bottom: 0;_x000D_
    font-weight: normal;_x000D_
    cursor: pointer;_x000D_
    vertical-align: sub;_x000D_
}_x000D_
.checkbox label span {_x000D_
    position: absolute;_x000D_
    top: 50%;_x000D_
    -webkit-transform: translateY(-50%);_x000D_
    transform: translateY(-50%);_x000D_
}_x000D_
.checkbox input[type="checkbox"]:focus + label::before {_x000D_
    outline: 0;_x000D_
}
_x000D_
<div class="container"> _x000D_
  <div class="checkbox">_x000D_
     <input type="checkbox" id="checkbox" name="" value="">_x000D_
     <label for="checkbox"><span>Checkbox</span></label>_x000D_
  </div>_x000D_
_x000D_
  <div class="checkbox">_x000D_
     <input type="checkbox" id="checkbox2" name="" value="">_x000D_
     <label for="checkbox2"><span>Checkbox</span></label>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

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:

What is the difference between properties and attributes in HTML?

well these are specified by the w3c what is an attribute and what is a property http://www.w3.org/TR/SVGTiny12/attributeTable.html

but currently attr and prop are not so different and there are almost the same

but they prefer prop for some things

Summary of Preferred Usage

The .prop() method should be used for boolean attributes/properties and for properties which do not exist in html (such as window.location). All other attributes (ones you can see in the html) can and should continue to be manipulated with the .attr() method.

well actually you dont have to change something if you use attr or prop or both, both work but i saw in my own application that prop worked where atrr didnt so i took in my 1.6 app prop =)

How to place two divs next to each other?

Try to use below code changes to place two divs in front of each other

#wrapper {
  width: 500px;
  border: 1px solid black;
  display:flex;
}

JSFiddle link

Programmatically switching between tabs within Swift

In a typical application there is a UITabBarController and it embeds 3 or more UIViewController as its tabs. In such a case if you subclassed a UITabBarController as YourTabBarController then you can set the selected index simply by:

selectedIndex = 1 // Displays 2nd tab. The index starts from 0.

In case you are navigating to YourTabBarController from any other view, then in that view controller's prepare(for segue:) method you can do:

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destination.
        // Pass the selected object to the new view controller.
        if segue.identifier == "SegueToYourTabBarController" {
            if let destVC = segue.destination as? YourTabBarController {
                destVC.selectedIndex = 0
            }
        }

I am using this way of setting tab with Xcode 10 and Swift 4.2.

how to toggle (hide/show) a table onClick of <a> tag in java script

visibility property makes the element visible or invisible.

function showTable(){
    document.getElementById('table').style.visibility = "visible";
}
function hideTable(){
    document.getElementById('table').style.visibility = "hidden";
}

Upload file to FTP using C#

The existing answers are valid, but why re-invent the wheel and bother with lower level WebRequest types while WebClient already implements FTP uploading neatly:

using (var client = new WebClient())
{
    client.Credentials = new NetworkCredential(ftpUsername, ftpPassword);
    client.UploadFile("ftp://host/path.zip", WebRequestMethods.Ftp.UploadFile, localFile);
}

Use of Application.DoEvents()

I saw jheriko's comment above and was initially agreeing that I couldn't find a way to avoid using DoEvents if you end up spinning your main UI thread waiting for a long running asynchronous piece of code on another thread to complete. But from Matthias's answer a simple Refresh of a small panel on my UI can replace the DoEvents (and avoid a nasty side effect).

More detail on my case ...

I was doing the following (as suggested here) to ensure that a progress bar type splash screen (How to display a "loading" overlay...) updated during a long running SQL command:

IAsyncResult asyncResult = sqlCmd.BeginExecuteNonQuery();
while (!asyncResult.IsCompleted)  //UI thread needs to Wait for Async SQL command to return
{
      System.Threading.Thread.Sleep(10); 
      Application.DoEvents();  //to make the UI responsive
}

The bad: For me calling DoEvents meant that mouse clicks were sometimes firing on forms behind my splash screen, even if I made it TopMost.

The good/answer: Replace the DoEvents line with a simple Refresh call to a small panel in the centre of my splash screen, FormSplash.Panel1.Refresh(). The UI updates nicely and the DoEvents weirdness others have warned of was gone.

JavaScript listener, "keypress" doesn't detect backspace?

Try keydown instead of keypress.

The keyboard events occur in this order: keydown, keyup, keypress

The problem with backspace probably is, that the browser will navigate back on keyup and thus your page will not see the keypress event.

Allow User to input HTML in ASP.NET MVC - ValidateInput or AllowHtml

I have faced this problem during development of a E-Commerce site using NopCommerce, I got this solution by 3 different ways as like the previous answers. But according to the NopCommerce structure I didn't found those three at a time. I have just seen that there they are using just [AllowHtml] and it's working fine except any problem. As previously asked question

Personally I don't prefer [ValidateInput(false)] because i's skipping total model entity checking, which is insecure. But if anyone just write have a look here

[AllowHtml] 
public string BlogText {get;set;}

then it just skip only single property, and just allow only particular property and check hardly all other entities. Therefore it seems preferable towards mine.

Convert Python program to C/C++ code?

If the C variant needs x hours less, then I'd invest that time in letting the algorithms run longer/again

"invest" isn't the right word here.

  1. Build a working implementation in Python. You'll finish this long before you'd finish a C version.

  2. Measure performance with the Python profiler. Fix any problems you find. Change data structures and algorithms as necessary to really do this properly. You'll finish this long before you finish the first version in C.

  3. If it's still too slow, manually translate the well-designed and carefully constructed Python into C.

    Because of the way hindsight works, doing the second version from existing Python (with existing unit tests, and with existing profiling data) will still be faster than trying to do the C code from scratch.

This quote is important.

Thompson's Rule for First-Time Telescope Makers
It is faster to make a four-inch mirror and then a six-inch mirror than to make a six-inch mirror.

Bill McKeenan
Wang Institute

Alter and Assign Object Without Side Effects

You either need to keep creating new objects, or clone the existing one. See What is the most efficient way to deep clone an object in JavaScript? for how to clone.

Make header and footer files to be included in multiple html pages

Aloha from 2018. Unfortunately, I don't have anything cool or futuristic to share with you.

I did however want to point out to those who have commented that the jQuery load() method isn't working in the present are probably trying to use the method with local files without running a local web server. Doing so will throw the above mentioned "cross origin" error, which specifies that cross origin requests such as that made by the load method are only supported for protocol schemes like http, data, or https. (I'm assuming that you're not making an actual cross-origin request, i.e the header.html file is actually on the same domain as the page you're requesting it from)

So, if the accepted answer above isn't working for you, please make sure you're running a web server. The quickest and simplest way to do that if you're in a rush (and using a Mac, which has Python pre-installed) would be to spin up a simple Python http server. You can see how easy it is to do that here.

I hope this helps!

How do SO_REUSEADDR and SO_REUSEPORT differ?

Mecki's answer is absolutly perfect, but it's worth adding that FreeBSD also supports SO_REUSEPORT_LB, which mimics Linux' SO_REUSEPORT behaviour - it balances the load; see setsockopt(2)

adding and removing classes in angularJs using ng-click

If you prefer separation of concerns such that logic for adding and removing classes happens on the controller, you can do this

controller

 (function() {
    angular.module('MyApp', []).controller('MyController', MyController);

    function MyController() {
      var vm = this;
      vm.tab = 0;

      vm.setTab = function(val) {
          vm.tab = val;
       };
      vm.toggleClass = function(val) {
          return val === vm.tab;
           };
        }
    })();

HTML

<div ng-app="MyApp">
  <ul class="" ng-controller="MyController as myCtrl">
    <li ng-click="myCtrl.setTab(0)" ng-class="{'highlighted':myCtrl.toggleClass(0)}">One</li>
    <li ng-click="myCtrl.setTab(1)" ng-class="{'highlighted':myCtrl.toggleClass(1)}">Two</li>
    <li ng-click="myCtrl.setTab(2)" ng-class="{'highlighted':myCtrl.toggleClass(2)}">Three</li>
   <li ng-click="myCtrl.setTab(3)" ng-class="{'highlighted':myCtrl.toggleClass(3)}">Four</li>
 </ul>

CSS

.highlighted {
   background-color: green;
   color: white;
}

Java : Convert formatted xml file to one line string

The above solutions work if you are compressing all white space in the XML document. Other quick options are JDOM (using Format.getCompactFormat()) and dom4j (using OutputFormat.createCompactFormat()) when outputting the XML document.

However, I had a unique requirement to preserve the white space contained within the element's text value and these solutions did not work as I needed. All I needed was to remove the 'pretty-print' formatting added to the XML document.

The solution that I came up with can be explained in the following 3-step/regex process ... for the sake of understanding the algorithm for the solution.

String regex, updatedXml;

// 1. remove all white space preceding a begin element tag:
regex = "[\\n\\s]+(\\<[^/])";
updatedXml = originalXmlStr.replaceAll( regex, "$1" );

// 2. remove all white space following an end element tag:
regex = "(\\</[a-zA-Z0-9-_\\.:]+\\>)[\\s]+";
updatedXml = updatedXml.replaceAll( regex, "$1" );

// 3. remove all white space following an empty element tag
// (<some-element xmlns:attr1="some-value".... />):
regex = "(/\\>)[\\s]+";
updatedXml = updatedXml.replaceAll( regex, "$1" );

NOTE: The pseudo-code is in Java ... the '$1' is the replacement string which is the 1st capture group.

This will simply remove the white space used when adding the 'pretty-print' format to an XML document, yet preserve all other white space when it is part of the element text value.

Excel to JSON javascript code?

NOTE: Not 100% Cross Browser

Check browser compatibility @ http://caniuse.com/#search=FileReader

as you will see people have had issues with the not so common browsers, But this could come down to the version of the browser.. I always recommend using something like caniuse to see what generation of browser is supported... This is only a working answer for the user, not a final copy and paste code for people to just use..

The Fiddle: http://jsfiddle.net/d2atnbrt/3/

THE HTML CODE:

<input type="file" id="my_file_input" />
<div id='my_file_output'></div>

THE JS CODE:

var oFileIn;

$(function() {
    oFileIn = document.getElementById('my_file_input');
    if(oFileIn.addEventListener) {
        oFileIn.addEventListener('change', filePicked, false);
    }
});


function filePicked(oEvent) {
    // Get The File From The Input
    var oFile = oEvent.target.files[0];
    var sFilename = oFile.name;
    // Create A File Reader HTML5
    var reader = new FileReader();

    // Ready The Event For When A File Gets Selected
    reader.onload = function(e) {
        var data = e.target.result;
        var cfb = XLS.CFB.read(data, {type: 'binary'});
        var wb = XLS.parse_xlscfb(cfb);
        // Loop Over Each Sheet
        wb.SheetNames.forEach(function(sheetName) {
            // Obtain The Current Row As CSV
            var sCSV = XLS.utils.make_csv(wb.Sheets[sheetName]);   
            var oJS = XLS.utils.sheet_to_row_object_array(wb.Sheets[sheetName]);   

            $("#my_file_output").html(sCSV);
            console.log(oJS)
        });
    };

    // Tell JS To Start Reading The File.. You could delay this if desired
    reader.readAsBinaryString(oFile);
}

This also requires https://cdnjs.cloudflare.com/ajax/libs/xls/0.7.4-a/xls.js to convert to a readable format, i've also used jquery only for changing the div contents and for the dom ready event.. so jquery is not needed

This is as basic as i could get it,

EDIT - Generating A Table

The Fiddle: http://jsfiddle.net/d2atnbrt/5/

This second fiddle shows an example of generating your own table, the key here is using sheet_to_json to get the data in the correct format for JS use..

One or two comments in the second fiddle might be incorrect as modified version of the first fiddle.. the CSV comment is at least

Test XLS File: http://www.whitehouse.gov/sites/default/files/omb/budget/fy2014/assets/receipts.xls

This does not cover XLSX files thought, it should be fairly easy to adjust for them using their examples.

Thread Safe C# Singleton Pattern

Reflection resistant Singleton pattern:

public sealed class Singleton
{
    public static Singleton Instance => _lazy.Value;
    private static Lazy<Singleton, Func<int>> _lazy { get; }

    static Singleton()
    {
        var i = 0;
        _lazy = new Lazy<Singleton, Func<int>>(() =>
        {
            i++;
            return new Singleton();
        }, () => i);
    }

    private Singleton()
    {
        if (_lazy.Metadata() == 0 || _lazy.IsValueCreated)
            throw new Exception("Singleton creation exception");
    }

    public void Run()
    {
        Console.WriteLine("Singleton called");
    }
}

What is the bower (and npm) version syntax?

Based on semver, you can use

  • Hyphen Ranges X.Y.Z - A.B.C 1.2.3-2.3.4 Indicates >=1.2.3 <=2.3.4

  • X-Ranges 1.2.x 1.X 1.2.*

  • Tilde Ranges ~1.2.3 ~1.2 Indicates allowing patch-level changes or minor version changes.

  • Caret Ranges ^1.2.3 ^0.2.5 ^0.0.4

    Allows changes that do not modify the left-most non-zero digit in the [major, minor, patch] tuple

    • ^1.2.x (means >=1.2.0 <2.0.0)
    • ^0.0.x (means >=0.0.0 <0.1.0)
    • ^0.0 (means >=0.0.0 <0.1.0)

a tag as a submit button?

Try something like below

 <a href="#" onclick="this.forms['formName'].submit()">Submit</a> 

How to enable or disable an anchor using jQuery?

The app I'm currently working on does it with a CSS style in combination with javascript.

a.disabled { color:gray; }

Then whenever I want to disable a link I call

$('thelink').addClass('disabled');

Then, in the click handler for 'thelink' a tag I always run a check first thing

if ($('thelink').hasClass('disabled')) return;

HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG))

Just looking at the message it sounds like one or more of the components that you reference, or one or more of their dependencies is not registered properly.

If you know which component it is you can use regsvr32.exe to register it, just open a command prompt, go to the directory where the component is and type regsvr32 filename.dll (assuming it's a dll), if it works, try to run the code again otherwise come back here with the error.

If you don't know which component it is, try re-installing/repairing the GIS software (I assume you've installed some GIS software that includes the component you're trying to use).

Clear dropdownlist with JQuery

How about storing the new options in a variable, and then using .html(variable) to replace the data in the container?

Spacing between elements

Use a margin to space around an element.

.box {
        margin: top right bottom left;
 }

.box {
        margin: 10px 5px 10px 5px;
}

This adds space outside of the element. So background colours, borders etc will not be included.

If you want to add spacing within an element use padding instead. It can be called in the same way as above.

Get the week start date and week end date from week number

for Access Queries, you can use in the below format as a field

"FirstDayofWeek:IIf(IsDate([ForwardedForActionDate]),CDate(Format([ForwardedForActionDate],"dd/mm/yyyy"))-(Weekday([ForwardedForActionDate])-1))"

direct Calculation allowed..

How to make a HTML Page in A4 paper size page(s)?

Ages ago, in November 2005, AlistApart.com published an article on how they published a book using nothing but HTML and CSS. See: http://alistapart.com/article/boom

Here's an excerpt of that article:

CSS2 has a notion of paged media (think sheets of paper), as opposed to continuous media (think scrollbars). Style sheets can set the size of pages and their margins. Page templates can be given names and elements can state which named page they want to be printed on. Also, elements in the source document can force page breaks. Here is a snippet from the style sheet we used:

@page {
   size: 7in 9.25in;
   margin: 27mm 16mm 27mm 16mm;
}

Having a US-based publisher, we were given the page size in inches. We, being Europeans, continued with metric measurements. CSS accepts both.

After setting the up the page size and margin, we needed to make sure there are page breaks in the right places. The following excerpt shows how page breaks are generated after chapters and appendices:

div.chapter, div.appendix {
    page-break-after: always;
}

Also, we used CSS2 to declare named pages:

div.titlepage {
  page: blank;
}

That is, the title page is to be printed on pages with the name “blank.” CSS2 described the concept of named pages, but their value only becomes apparent when headers and footers are available.

Anyway…

Since you want to print A4, you'll need different dimensions of course:

@page {
    size: 21cm 29.7cm;
    margin: 30mm 45mm 30mm 45mm;
     /* change the margins as you want them to be. */
}

The article dives into things like setting page-breaks, etc. so you might want to read that completely.

In your case, the trick is to create the print CSS first. Most modern browsers (>2005) support zooming and will already be able to display a website based on the print CSS.

Now, you'll want to make the web display look a bit different and adapt the whole design to fit most browsers too (including the old, pre 2005 ones). For that, you'll have to create a web CSS file or override some parts of your print CSS. When creating CSS for web display, remember that a browser can have ANY size (think: “mobile” up to “big-screen TVs”). Meaning: for the web CSS your page-width and image-width is best set using a variable width (%) to support as many display devices and web-browsing clients as possible.

EDIT (26-02-2015)

Today, I happened to stumble upon another, more recent article at SmashingMagazine which also dives into designing for print with HTML and CSS… just in case you could use yet-another-tutorial.

EDIT (30-10-2018)

It has been brought to my attention in that size is not valid CSS3, which is indeed correct — I merely repeated the code quoted in the article which (as noted) was good old CSS2 (which makes sense when you look at the year the article and this answer were first published). Anyway, here's the valid CSS3 code for your copy-and-paste convenience:

@media print {
    body{
        width: 21cm;
        height: 29.7cm;
        margin: 30mm 45mm 30mm 45mm; 
        /* change the margins as you want them to be. */
   } 
}

In case you think you really need pixels (you should actually avoid using pixels), you will have to take care of choosing the correct DPI for printing:

  • 72 dpi (web) = 595 X 842 pixels
  • 300 dpi (print) = 2480 X 3508 pixels
  • 600 dpi (high quality print) = 4960 X 7016 pixels

Yet, I would avoid the hassle and simply use cm (centimeters) or mm (millimeters) for sizing as that avoids rendering glitches that can arise depending on which client you use.

Creating a textarea with auto-resize

$('textarea').bind('keyup change', function() {
    var $this = $(this), $offset = this.offsetHeight;
    $offset > $this.height() && $offset < 300 ?
        $this.css('height ', $offset)
            .attr('rows', $this.val().split('\n').length)
            .css({'height' : $this.attr('scrollHeight'),'overflow' : 'hidden'}) :
        $this.css('overflow','auto');
});

How do I position one image on top of another in HTML?

Inline style only for clarity here. Use a real CSS stylesheet.

<!-- First, your background image is a DIV with a background 
     image style applied, not a IMG tag. -->
<div style="background-image:url(YourBackgroundImage);">
    <!-- Second, create a placeholder div to assist in positioning 
         the other images. This is relative to the background div. -->
    <div style="position: relative; left: 0; top: 0;">
        <!-- Now you can place your IMG tags, and position them relative 
             to the container we just made -->   
        <img src="YourForegroundImage" style="position: relative; top: 0; left: 0;"/>
    </div>
</div>

Rails and PostgreSQL: Role postgres does not exist

In the Heroku documentation; Getting started whit rails 4, they say:

You will also need to remove the username field in your database.yml if there is one so: In file config/database.yml remove: username: myapp

Then you just delete that line in "development:", if you don't pg tells to the database that works under role "myapp"

This line tells rails that the database myapp_development should be run under a role of myapp. Since you likely don’t have this role in your database we will remove it. With the line remove Rails will try to access the database as user who is currently logged into the computer.

Also remember to create the database for development:

$createdb myapp_development

Repleace "myapp" for your app name

How to increase storage for Android Emulator? (INSTALL_FAILED_INSUFFICIENT_STORAGE)

The following approach worked for me

  1. Navigate to your android SDK/tools folder in the terminal window (in case you didn't added the path for it)

  2. Make sure the virtual device you're planning to clean is powered off.

  3. Run the command "./emulator -wipe-data -avd YourAvdName" where YourAvdName is the name of your virtual android device

How to convert xml into array in php?

See https://github.com/gaarf/XML-string-to-PHP-array/blob/master/xmlstr_to_array.php

<?php
/**
  * convert xml string to php array - useful to get a serializable value
  *
  * @param string $xmlstr
  * @return array
  *
  * @author Adrien aka Gaarf & contributors
  * @see http://gaarf.info/2009/08/13/xml-string-to-php-array/
*/
function xmlstr_to_array($xmlstr) {
  $doc = new DOMDocument();
  $doc->loadXML($xmlstr);
  $root = $doc->documentElement;
  $output = domnode_to_array($root);
  $output['@root'] = $root->tagName;
  return $output;
}
function domnode_to_array($node) {
  $output = array();
  switch ($node->nodeType) {
    case XML_CDATA_SECTION_NODE:
    case XML_TEXT_NODE:
      $output = trim($node->textContent);
    break;
    case XML_ELEMENT_NODE:
      for ($i=0, $m=$node->childNodes->length; $i<$m; $i++) {
        $child = $node->childNodes->item($i);
        $v = domnode_to_array($child);
        if(isset($child->tagName)) {
          $t = $child->tagName;
          if(!isset($output[$t])) {
            $output[$t] = array();
          }
          $output[$t][] = $v;
        }
        elseif($v || $v === '0') {
          $output = (string) $v;
        }
      }
      if($node->attributes->length && !is_array($output)) { //Has attributes but isn't an array
        $output = array('@content'=>$output); //Change output into an array.
      }
      if(is_array($output)) {
        if($node->attributes->length) {
          $a = array();
          foreach($node->attributes as $attrName => $attrNode) {
            $a[$attrName] = (string) $attrNode->value;
          }
          $output['@attributes'] = $a;
        }
        foreach ($output as $t => $v) {
          if(is_array($v) && count($v)==1 && $t!='@attributes') {
            $output[$t] = $v[0];
          }
        }
      }
    break;
  }
  return $output;
}

How to Deep clone in javascript

Here is an ES6 function that will also work for objects with cyclic references:

_x000D_
_x000D_
function deepClone(obj, hash = new WeakMap()) {_x000D_
    if (Object(obj) !== obj) return obj; // primitives_x000D_
    if (hash.has(obj)) return hash.get(obj); // cyclic reference_x000D_
    const result = obj instanceof Set ? new Set(obj) // See note about this!_x000D_
                 : obj instanceof Map ? new Map(Array.from(obj, ([key, val]) => _x000D_
                                        [key, deepClone(val, hash)])) _x000D_
                 : obj instanceof Date ? new Date(obj)_x000D_
                 : obj instanceof RegExp ? new RegExp(obj.source, obj.flags)_x000D_
                 // ... add here any specific treatment for other classes ..._x000D_
                 // and finally a catch-all:_x000D_
                 : obj.constructor ? new obj.constructor() _x000D_
                 : Object.create(null);_x000D_
    hash.set(obj, result);_x000D_
    return Object.assign(result, ...Object.keys(obj).map(_x000D_
        key => ({ [key]: deepClone(obj[key], hash) }) ));_x000D_
}_x000D_
_x000D_
// Sample data_x000D_
var p = {_x000D_
  data: 1,_x000D_
  children: [{_x000D_
    data: 2,_x000D_
    parent: null_x000D_
  }]_x000D_
};_x000D_
p.children[0].parent = p;_x000D_
_x000D_
var q = deepClone(p);_x000D_
_x000D_
console.log(q.children[0].parent.data); // 1
_x000D_
_x000D_
_x000D_

A note about Sets and Maps

How to deal with the keys of Sets and Maps is debatable: those keys are often primitives (in which case there is no debate), but they can also be objects. In that case the question becomes: should those keys be cloned?

One could argue that this should be done, so that if those objects are mutated in the copy, the objects in the original are not affected, and vice versa.

On the other hand one would want that if a Set/Map has a key, this should be true in both the original and the copy -- at least before any change is made to either of them. It would be strange if the copy would be a Set/Map that has keys that never occurred before (as they were created during the cloning process): surely that is not very useful for any code that needs to know whether a given object is a key in that Set/Map or not.

As you notice, I am more of the second opinion: the keys of Sets and Maps are values (maybe references) that should remain the same.

Such choices will often also surface with other (maybe custom) objects. There is no general solution, as much depends on how the cloned object is expected to behave in your specific case.

Set title background color

There is an easier alternative to change the color of the title bar, by using the v7 appcompat support library provided by Google.

See this link on how to to setup this support library: https://developer.android.com/tools/support-library/setup.html

Once you have done that, it's sufficient to add the following lines to your res/values/styles.xml file:

<style name="AppTheme" parent="AppBaseTheme">
    <item name="android:actionBarStyle">@style/ActionBar</item>
</style>

<!-- Actionbar Theme -->
<style name="ActionBar" parent="Widget.AppCompat.Light.ActionBar.Solid.Inverse">
    <item name="android:background">@color/titlebackgroundcolor</item>
</style>

(assuming that "titlebackgroundcolor" is defined in your res/values/colors.xml, e.g.:

<color name="titlebackgroundcolor">#0000AA</color>

)

Handling urllib2's timeout? - Python

In Python 2.7.3:

import urllib2
import socket

class MyException(Exception):
    pass

try:
    urllib2.urlopen("http://example.com", timeout = 1)
except urllib2.URLError as e:
    print type(e)    #not catch
except socket.timeout as e:
    print type(e)    #catched
    raise MyException("There was an error: %r" % e)

Use 'import module' or 'from module import'?

There's another detail here, not mentioned, related to writing to a module. Granted this may not be very common, but I've needed it from time to time.

Due to the way references and name binding works in Python, if you want to update some symbol in a module, say foo.bar, from outside that module, and have other importing code "see" that change, you have to import foo a certain way. For example:

module foo:

bar = "apples"

module a:

import foo
foo.bar = "oranges"   # update bar inside foo module object

module b:

import foo           
print foo.bar        # if executed after a's "foo.bar" assignment, will print "oranges"

However, if you import symbol names instead of module names, this will not work.

For example, if I do this in module a:

from foo import bar
bar = "oranges"

No code outside of a will see bar as "oranges" because my setting of bar merely affected the name "bar" inside module a, it did not "reach into" the foo module object and update its "bar".

How to change Android version and code version number?

Go in the build.gradle and set the version code and name inside the defaultConfig element

defaultConfig { minSdkVersion 9 targetSdkVersion 19 versionCode 1 versionName "1.0" }

Increasing heap space in Eclipse: (java.lang.OutOfMemoryError)

The accepted solution of modifying a Run Configuration wasn't ideal for me as I have a few different run configurations and could easily forget to do this when adding further ones in future. Also I wanted the setting to apply whenever running anything, e.g. when running JUnit tests by right-clicking and selecting "Run As" -> "JUnit Test".

The above can be achieved by modifying the JRE/JDK settings instead:-

  1. Go to Window -> Preferences.
  2. Select Java -> Installed JREs
  3. Select your default JRE (which could be a JDK) and click on "Edit..."
  4. Change the "Default VM arguments" value as required, e.g. -Xms512m -Xmx4G -XX:MaxPermSize=256M

How to properly export an ES6 class in Node 4?

Sometimes I need to declare multiple classes in one file, or I want to export base classes and keep their names exported because of my JetBrains editor understands that better. I just use

global.MyClass = class MyClass { ... };

And somewhere else:

require('baseclasses.js');
class MySubclass extends MyClass() { ... }

Accessing variables from other functions without using global variables

I think your best bet here may be to define a single global-scoped variable, and dumping your variables there:

var MyApp = {}; // Globally scoped object

function foo(){
    MyApp.color = 'green';
}

function bar(){
    alert(MyApp.color); // Alerts 'green'
} 

No one should yell at you for doing something like the above.

Creating a new empty branch for a new project

Let's say you have a master branch with files/directories:

> git branch  
master
> ls -la # (files and dirs which you may keep in master)
.git
directory1
directory2
file_1
..
file_n

Step by step how to make an empty branch:

  1. git checkout —orphan new_branch_name
  2. Make sure you are in the right directory before executing the following command:
    ls -la |awk '{print $9}' |grep -v git |xargs -I _ rm -rf ./_
  3. git rm -rf .
  4. touch new_file
  5. git add new_file
  6. git commit -m 'added first file in the new branch'
  7. git push origin new_branch_name

In step 2, we simply remove all the files locally to avoid confusion with the files on your new branch and those ones you keep in master branch. Then, we unlink all those files in step 3. Finally, step 4 and after are working with our new empty branch.

Once you're done, you can easily switch between your branches:

git checkout master 
git checkout new_branch

How to remove entity with ManyToMany relationship in JPA (and corresponding join table rows)?

  • The ownership of the relation is determined by where you place the 'mappedBy' attribute to the annotation. The entity you put 'mappedBy' is the one which is NOT the owner. There's no chance for both sides to be owners. If you don't have a 'delete user' use-case you could simply move the ownership to the Group entity, as currently the User is the owner.
  • On the other hand, you haven't been asking about it, but one thing worth to know. The groups and users are not combined with each other. I mean, after deleting User1 instance from Group1.users, the User1.groups collections is not changed automatically (which is quite surprising for me),
  • All in all, I would suggest you decide who is the owner. Let say the User is the owner. Then when deleting a user the relation user-group will be updated automatically. But when deleting a group you have to take care of deleting the relation yourself like this:

entityManager.remove(group)
for (User user : group.users) {
     user.groups.remove(group);
}
...
// then merge() and flush()

How to start http-server locally

When you're running npm install in the project's root, it installs all of the npm dependencies into the project's node_modules directory.

If you take a look at the project's node_modules directory, you should see a directory called http-server, which holds the http-server package, and a .bin folder, which holds the executable binaries from the installed dependencies. The .bin directory should have the http-server binary (or a link to it).

So in your case, you should be able to start the http-server by running the following from your project's root directory (instead of npm start):

./node_modules/.bin/http-server -a localhost -p 8000 -c-1

This should have the same effect as running npm start.

If you're running a Bash shell, you can simplify this by adding the ./node_modules/.bin folder to your $PATH environment variable:

export PATH=./node_modules/.bin:$PATH

This will put this folder on your path, and you should be able to simply run

http-server -a localhost -p 8000 -c-1

Is it possible to run an .exe or .bat file on 'onclick' in HTML

You can do it on Internet explorer with OCX component and on chrome browser using a chrome extension chrome document in any case need additional settings on the client system!

Important part of chrome extension source:

var port = chrome.runtime.connectNative("your.app.id"); 
      port.onMessage.addListener(onNativeMessage); 
      port.onDisconnect.addListener(onDisconnected);
      port.postMessage("send some data to STDIO");

permission file:

{
      "name": "your.app.id",
      "description": "Name of your extension",
      "path": "myapp.exe",
      "type": "stdio",
      "allowed_origins": [
            "chrome-extension://IDOFYOUREXTENSION_lokldaeplkmh/"
      ]
}

and windows registry settings:

HKEY_CURRENT_USER\Software\Google\Chrome\NativeMessagingHosts\your.app.id
REG_EXPAND_SZ : c:\permissionsettings.json

Convert seconds value to hours minutes seconds?

I use this in python to convert a float representing seconds to hours, minutes, seconds, and microseconds. It's reasonably elegant and is handy for converting to a datetime type via strptime to convert. It could also be easily extended to longer intervals (weeks, months, etc.) if needed.

    def sectohmsus(seconds):
        x = seconds
        hmsus = []
        for i in [3600, 60, 1]:  # seconds in a hour, minute, and second
            hmsus.append(int(x / i))
            x %= i
        hmsus.append(int(round(x * 1000000)))  # microseconds
        return hmsus  # hours, minutes, seconds, microsecond

How to lose margin/padding in UITextView?

For iOS 7.0, I've found that the contentInset trick no longer works. This is the code I used to get rid of the margin/padding in iOS 7.

This brings the left edge of the text to the left edge of the container:

textView.textContainer.lineFragmentPadding = 0

This causes the top of the text to align with the top of the container

textView.textContainerInset = .zero

Both Lines are needed to completely remove the margin/padding.

What does the red exclamation point icon in Eclipse mean?

I had the same problem and Andrew is correct. Check your classpath variable "M2_REPO". It probably points to an invalid location of your local maven repo.

In my case I was using mvn eclipse:eclipse on the command line and this plugin was setting the M2_REPO classpath variable. Eclipse couldn't find my maven settings.xml in my home directory and as a result was incorrectly the M2_REPO classpath variable. My solution was to restart eclipse and it picked up my settings.xml and removed the red exclamation on my projects.

I got some more information from this guy: http://www.mkyong.com/maven/how-to-configure-m2_repo-variable-in-eclipse-ide/

Check last modified date of file in C#

Be aware that the function File.GetLastWriteTime does not always work as expected, the values are sometimes not instantaneously updated by the OS. You may get an old Timestamp, even if the file has been modified right before.

The behaviour may vary between OS versions. For example, this unit test worked well every time on my developer machine, but it always fails on our build server.

  [TestMethod]
  public void TestLastModifiedTimeStamps()
  {
     var tempFile = Path.GetTempFileName();
     var lastModified = File.GetLastWriteTime(tempFile);
     using (new FileStream(tempFile, FileMode.Create, FileAccess.Write, FileShare.None))
     {

     }
     Assert.AreNotEqual(lastModified, File.GetLastWriteTime(tempFile));
  }

See File.GetLastWriteTime seems to be returning 'out of date' value

Your options:

a) live with the occasional omissions.

b) Build up an active component realising the observer pattern (eg. a tcp server client structure), communicating the changes directly instead of writing / reading files. Fast and flexible, but another dependency and a possible point of failure (and some work, of course).

c) Ensure the signalling process by replacing the content of a dedicated signal file that other processes regularly read. It´s not that smart as it´s a polling procedure and has a greater overhead than calling File.GetLastWriteTime, but if not checking the content from too many places too often, it will do the work.

/// <summary>
/// type to set signals or check for them using a central file 
/// </summary>
public class FileSignal
{
    /// <summary>
    /// path to the central file for signal control
    /// </summary>
    public string FilePath { get; private set; }

    /// <summary>
    /// numbers of retries when not able to retrieve (exclusive) file access
    /// </summary>
    public int MaxCollisions { get; private set; }

    /// <summary>
    /// timespan to wait until next try
    /// </summary>
    public TimeSpan SleepOnCollisionInterval { get; private set; }

    /// <summary>
    /// Timestamp of the last signal
    /// </summary>
    public DateTime LastSignal { get; private set; }

    /// <summary>
    /// constructor
    /// </summary>
    /// <param name="filePath">path to the central file for signal control</param>
    /// <param name="maxCollisions">numbers of retries when not able to retrieve (exclusive) file access</param>
    /// <param name="sleepOnCollisionInterval">timespan to wait until next try </param>
    public FileSignal(string filePath, int maxCollisions, TimeSpan sleepOnCollisionInterval)
    {
        FilePath = filePath;
        MaxCollisions = maxCollisions;
        SleepOnCollisionInterval = sleepOnCollisionInterval;
        LastSignal = GetSignalTimeStamp();
    }

    /// <summary>
    /// constructor using a default value of 50 ms for sleepOnCollisionInterval
    /// </summary>
    /// <param name="filePath">path to the central file for signal control</param>
    /// <param name="maxCollisions">numbers of retries when not able to retrieve (exclusive) file access</param>        
    public FileSignal(string filePath, int maxCollisions): this (filePath, maxCollisions, TimeSpan.FromMilliseconds(50))
    {
    }

    /// <summary>
    /// constructor using a default value of 50 ms for sleepOnCollisionInterval and a default value of 10 for maxCollisions
    /// </summary>
    /// <param name="filePath">path to the central file for signal control</param>        
    public FileSignal(string filePath) : this(filePath, 10)
    {
    }

    private Stream GetFileStream(FileAccess fileAccess)
    {
        var i = 0;
        while (true)
        {
            try
            {
                return new FileStream(FilePath, FileMode.Create, fileAccess, FileShare.None);
            }
            catch (Exception e)
            {
                i++;
                if (i >= MaxCollisions)
                {
                    throw e;
                }
                Thread.Sleep(SleepOnCollisionInterval);
            };
        };
    }

    private DateTime GetSignalTimeStamp()
    {
        if (!File.Exists(FilePath))
        {
            return DateTime.MinValue;
        }
        using (var stream = new FileStream(FilePath, FileMode.Open, FileAccess.Read, FileShare.None))
        {
            if(stream.Length == 0)
            {
                return DateTime.MinValue;
            }
            using (var reader = new BinaryReader(stream))
            {
                return DateTime.FromBinary(reader.ReadInt64());
            };                
        }
    }

    /// <summary>
    /// overwrites the existing central file and writes the current time into it.
    /// </summary>
    public void Signal()
    {
        LastSignal = DateTime.Now;
        using (var stream = new FileStream(FilePath, FileMode.Create, FileAccess.Write, FileShare.None))
        {
            using (var writer = new BinaryWriter(stream))
            {
                writer.Write(LastSignal.ToBinary());
            }
        }
    }

    /// <summary>
    /// returns true if the file signal has changed, otherwise false.
    /// </summary>        
    public bool CheckIfSignalled()
    {
        var signal = GetSignalTimeStamp();
        var signalTimestampChanged = LastSignal != signal;
        LastSignal = signal;
        return signalTimestampChanged;
    }
}

Some tests for it:

    [TestMethod]
    public void TestSignal()
    {
        var fileSignal = new FileSignal(Path.GetTempFileName());
        var fileSignal2 = new FileSignal(fileSignal.FilePath);
        Assert.IsFalse(fileSignal.CheckIfSignalled());
        Assert.IsFalse(fileSignal2.CheckIfSignalled());
        Assert.AreEqual(fileSignal.LastSignal, fileSignal2.LastSignal);
        fileSignal.Signal();
        Assert.IsFalse(fileSignal.CheckIfSignalled());
        Assert.AreNotEqual(fileSignal.LastSignal, fileSignal2.LastSignal);
        Assert.IsTrue(fileSignal2.CheckIfSignalled());
        Assert.AreEqual(fileSignal.LastSignal, fileSignal2.LastSignal);
        Assert.IsFalse(fileSignal2.CheckIfSignalled());
    }

How can I Insert data into SQL Server using VBNet

Function ExtSql(ByVal sql As String) As Boolean
    Dim cnn As SqlConnection
    Dim cmd As SqlCommand
    cnn = New SqlConnection(My.Settings.mySqlConnectionString)
    Try
        cnn.Open()
        cmd = New SqlCommand
        cmd.Connection = cnn
        cmd.CommandType = CommandType.Text
        cmd.CommandText = sql
        cmd.ExecuteNonQuery()
        cnn.Close()
        cmd.Dispose()
    Catch ex As Exception
        cnn.Close()
        Return False
    End Try
    Return True
End Function

Arduino error: does not name a type?

I found the solution to this problem in a "}". I did some changes to my sketch and forgot to check for "}" and I had an extra one. As soon as I deleted it and compiled everything was fine.

warning: implicit declaration of function

You are using a function for which the compiler has not seen a declaration ("prototype") yet.

For example:

int main()
{
    fun(2, "21"); /* The compiler has not seen the declaration. */       
    return 0;
}

int fun(int x, char *p)
{
    /* ... */
}

You need to declare your function before main, like this, either directly or in a header:

int fun(int x, char *p);

Android Studio marks R in red with error message "cannot resolve symbol R", but build succeeds

I had a similar issue for weeks but i had the design lib version with + in my build.gradle which made it download the latest version. So i set it to the version of the package and it worked.

LocalDate to java.util.Date and vice versa simplest conversion?

Converting LocalDateTime to java.util.Date

    LocalDateTime localDateTime = LocalDateTime.now();

    ZonedDateTime zonedDateTime = localDateTime.atZone(ZoneOffset.systemDefault());

    Instant instant = zonedDateTime.toInstant();

    Date date = Date.from(instant);

System.out.println("Result Date is : "+date);

Match everything except for specified strings

Depends on the language, but there are generally negative-assertions you can put in like so:

(?!red|green|blue)

(Thanks for the syntax fix, the above is valid Java and Perl, YMMV)

PHP date yesterday

date() itself is only for formatting, but it accepts a second parameter.

date("F j, Y", time() - 60 * 60 * 24);

To keep it simple I just subtract 24 hours from the unix timestamp.

A modern oop-approach is using DateTime

$date = new DateTime();
$date->sub(new DateInterval('P1D'));
echo $date->format('F j, Y') . "\n";

Or in your case (more readable/obvious)

$date = new DateTime();
$date->add(DateInterval::createFromDateString('yesterday'));
echo $date->format('F j, Y') . "\n";

(Because DateInterval is negative here, we must add() it here)

See also: DateTime::sub() and DateInterval

AngularJS: How can I pass variables between controllers?

You could do that with services or factories. They are essentially the same apart for some core differences. I found this explanation on thinkster.io to be the easiest to follow. Simple, to the point and effective.

How do you Hover in ReactJS? - onMouseLeave not registered during fast hover over

Have you tried any of these?

onMouseDown onMouseEnter onMouseLeave onMouseMove onMouseOut onMouseOver onMouseUp

SyntheticEvent

it also mentions the following:

React normalizes events so that they have consistent properties across different browsers.

The event handlers below are triggered by an event in the bubbling phase. To register an event handler for the capture phase, append Capture to the event name; for example, instead of using onClick, you would use onClickCapture to handle the click event in the capture phase.

Python unittest - opposite of assertRaises?

I've found it useful to monkey-patch unittest as follows:

def assertMayRaise(self, exception, expr):
  if exception is None:
    try:
      expr()
    except:
      info = sys.exc_info()
      self.fail('%s raised' % repr(info[0]))
  else:
    self.assertRaises(exception, expr)

unittest.TestCase.assertMayRaise = assertMayRaise

This clarifies intent when testing for the absence of an exception:

self.assertMayRaise(None, does_not_raise)

This also simplifies testing in a loop, which I often find myself doing:

# ValueError is raised only for op(x,x), op(y,y) and op(z,z).
for i,(a,b) in enumerate(itertools.product([x,y,z], [x,y,z])):
  self.assertMayRaise(None if i%4 else ValueError, lambda: op(a, b))

View array in Visual Studio debugger?

Are you trying to view an array with memory allocated dynamically? If not, you can view an array for C++ and C# by putting it in the watch window in the debugger, with its contents visible when you expand the array on the little (+) in the watch window by a left mouse-click.

If it's a pointer to a dynamically allocated array, to view N contents of the pointer, type "pointer, N" in the watch window of the debugger. Note, N must be an integer or the debugger will give you an error saying it can't access the contents. Then, left click on the little (+) icon that appears to view the contents.

Is it possible to delete an object's property in PHP?

This code is working fine for me in a loop

$remove = array(
    "market_value",
    "sector_id"
);

foreach($remove as $key){
    unset($obj_name->$key);
}

Can RDP clients launch remote applications and not desktops

Using an RDP connection file you can set the alternate shell to be your application; the file syntax is like

alternate shell:s:c:\winnt\system32\notepad.exe

and you pass that as a command-line argument to mstsc.exe; this similar to chrissr's solution, but without affecting every RDP session you launch. A fuller summary of settings here.

MAX function in where clause mysql

Use a subselect:

SELECT row  FROM table  WHERE id=(
    SELECT max(id) FROM table
)

Note: ID must be unique, else multiple rows are returned

What causes the error "undefined reference to (some function)"?

It's a linker error. ld is the linker, so if you get an error message ending with "ld returned 1 exit status", that tells you that it's a linker error.

The error message tells you that none of the object files you're linking against contains a definition for avergecolumns. The reason for that is that the function you've defined is called averagecolumns (in other words: you misspelled the function name when calling the function (and presumably in the header file as well - otherwise you'd have gotten a different error at compile time)).

How to see the values of a table variable at debug time in T-SQL?

SQL Server Profiler 2014 lists the content of table value parameter. Might work in previous versions too. Enable SP:Starting or RPC:Completed event in Stored Procedures group and TextData column and when you click on entry in log you'll have the insert statements for table variable. You can then copy the text and run in Management Studio.

Sample output:

declare @p1 dbo.TableType
insert into @p1 values(N'A',N'B')
insert into @p1 values(N'C',N'D')

exec uspWhatever @PARAM=@p1

PDF to byte array and vice versa

Calling toString() on an InputStream doesn't do what you think it does. Even if it did, a PDF contains binary data, so you wouldn't want to convert it to a string first.

What you need to do is read from the stream, write the results into a ByteArrayOutputStream, then convert the ByteArrayOutputStream into an actual byte array by calling toByteArray():

InputStream inputStream = new FileInputStream(sourcePath);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

int data;
while( (data = inputStream.read()) >= 0 ) {
    outputStream.write(data);
}

inputStream.close();
return outputStream.toByteArray();

iOS Swift - Get the Current Local Time and Date Timestamp

in Swift 5

extension Date {
    static var currentTimeStamp: Int64{
        return Int64(Date().timeIntervalSince1970 * 1000)
    }
}

call like this:

let timeStamp = Date.currentTimeStamp
print(timeStamp)

Thanks @lenooh

json_encode is returning NULL?

AHHH!!! This looks so wrong it hurts my head. Try something more like this...

<?php
include('db.php');

$result = mysql_query('SELECT `id`, `name`, `description`, `icon` FROM `staff` ORDER BY `id` DESC LIMIT 20') or die(mysql_error());
$rows = array();
while($row = mysql_fetch_assoc($result)){
    $rows[] = $row;
}

echo json_encode($rows);
?>
  • When iterating over mysql_num_rows you should use < not <=. You should also cache this value (save it to a variable) instead of having it re-count every loop. Who knows what it's doing under the hood... (might be efficient, I'm not really sure)
  • You don't need to copy out each value explicitly like that... you're just making this harder on yourself. If the query is returning more values than you've listed there, list only the ones you want in your SQL.
  • mysql_fetch_array returns the values both by key and by int. You not using the indices, so don't fetch em.

If this really is a problem with json_encode, then might I suggest replacing the body of the loop with something like

$rows[] = array_map('htmlentities',$row);

Perhpas there are some special chars in there that are mucking things up...

Format numbers to strings in Python

str() in python on an integer will not print any decimal places.

If you have a float that you want to ignore the decimal part, then you can use str(int(floatValue)).

Perhaps the following code will demonstrate:

>>> str(5)
'5'
>>> int(8.7)
8

Page unload event in asp.net

Refer to the ASP.NET page lifecycle to help find the right event to override. It really depends what you want to do. But yes, there is an unload event.

    protected override void OnUnload(EventArgs e)
    {
        base.OnUnload(e);

        // your code
    }

But just remember (from the above link): During the unload stage, the page and its controls have been rendered, so you cannot make further changes to the response stream. If you attempt to call a method such as the Response.Write method, the page will throw an exception.

modal View controllers - how to display and dismiss

I think you misunderstood some core concepts about iOS modal view controllers. When you dismiss VC1, any presented view controllers by VC1 are dismissed as well. Apple intended for modal view controllers to flow in a stacked manner - in your case VC2 is presented by VC1. You are dismissing VC1 as soon as you present VC2 from VC1 so it is a total mess. To achieve what you want, buttonPressedFromVC1 should have the mainVC present VC2 immediately after VC1 dismisses itself. And I think this can be achieved without delegates. Something along the lines:

UIViewController presentingVC = [self presentingViewController];
[self dismissViewControllerAnimated:YES completion:
 ^{
    [presentingVC presentViewController:vc2 animated:YES completion:nil];
 }];

Note that self.presentingViewController is stored in some other variable, because after vc1 dismisses itself, you shouldn't make any references to it.

Find duplicates and delete all in notepad++

If it is possible to change the sequence of the lines you could do:

  1. sort line with Edit -> Line Operations -> Sort Lines Lexicographically ascending
  2. do a Find / Replace:
    • Find What: ^(.*\r?\n)\1+
    • Replace with: (Nothing, leave empty)
    • Check Regular Expression in the lower left
    • Click Replace All

How it works: The sorting puts the duplicates behind each other. The find matches a line ^(.*\r?\n) and captures the line in \1 then it continues and tries to find \1 one or more times (+) behind the first match. Such a block of duplicates (if it exists) is replaced with nothing.

The \r?\n should deal nicely with Windows and Unix lineendings.

How to run an android app in background?

As apps run in the background anyway. I’m assuming what your really asking is how do you make apps do stuff in the background. The solution below will make your app do stuff in the background after opening the app and after the system has rebooted.

Below, I’ve added a link to a fully working example (in the form of an Android Studio Project)

This subject seems to be out of the scope of the Android docs, and there doesn’t seem to be any one comprehensive doc on this. The information is spread across a few docs.

The following docs tell you indirectly how to do this: https://developer.android.com/reference/android/app/Service.html

https://developer.android.com/reference/android/content/BroadcastReceiver.html

https://developer.android.com/guide/components/bound-services.html

In the interests of getting your usage requirements correct, the important part of this above doc to read carefully is: #Binder, #Messenger and the components link below:

https://developer.android.com/guide/components/aidl.html

Here is the link to a fully working example (in Android Studio format): http://developersfound.com/BackgroundServiceDemo.zip

This project will start an Activity which binds to a service; implementing the AIDL.

This project is also useful to re-factor for the purpose of IPC across different apps.

This project is also developed to start automatically when Android restarts (provided the app has been run at least one after installation and app is not installed on SD card)

When this app/project runs after reboot, it dynamically uses a transparent view to make it look like no app has started but the service of the associated app starts cleanly.

This code is written in such a way that it’s very easy to tweak to simulate a scheduled service.

This project is developed in accordance to the above docs and is subsequently a clean solution.

There is however a part of this project which is not clean being: I have not found a way to start a service on reboot without using an Activity. If any of you guys reading this post have a clean way to do this please post a comment.

How do I filter an array with AngularJS and use a property of the filtered object as the ng-model attribute?

please note, if you use $filter like this:

$scope.failedSubjects = $filter('filter')($scope.results.subjects, {'grade':'C'});

and you happened to have another grade for, Oh I don't know, CC or AC or C+ or CCC it pulls them in to. you need to append a requirement for an exact match:

$scope.failedSubjects = $filter('filter')($scope.results.subjects, {'grade':'C'}, true);

This really killed me when I was pulling in some commission details like this:

var obj = this.$filter('filter')(this.CommissionTypes, { commission_type_id: 6}))[0];

only get called in for a bug because it was pulling in the commission ID 56 rather than 6.

Adding the true forces an exact match.

var obj = this.$filter('filter')(this.CommissionTypes, { commission_type_id: 6}, true))[0];

Yet still, I prefer this (I use typescript, hence the "Let" and =>):

let obj = this.$filter('filter')(this.CommissionTypes, (item) =>{ 
             return item.commission_type_id === 6;
           })[0];

I do that because, at some point down the road, I might want to get some more info from that filtered data, etc... having the function right in there kind of leaves the hood open.

Java: how to convert HashMap<String, Object> to array

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

Object[][] twoDarray = new Object[map.size()][2];

Object[] keys = map.keySet().toArray();
Object[] values = map.values().toArray();

for (int row = 0; row < twoDarray.length; row++) {
    twoDarray[row][0] = keys[row];
    twoDarray[row][1] = values[row];
}

// Print out the new 2D array
for (int i = 0; i < twoDarray.length; i++) {
    for (int j = 0; j < twoDarray[i].length; j++) {
        System.out.println(twoDarray[i][j]);
    }
}

How can I access and process nested objects, arrays or JSON?

Dynamic approach

In below deep(data,key) function, you can use arbitrary key string - in your case items[1].name (you can use array notation [i] at any level) - if key is invalid then undefined is return.

_x000D_
_x000D_
let deep = (o,k) => k.split('.').reduce((a,c,i) => {_x000D_
    let m=c.match(/(.*?)\[(\d*)\]/);_x000D_
    if(m && a!=null && a[m[1]]!=null) return a[m[1]][+m[2]];_x000D_
    return a==null ? a: a[c];_x000D_
},o);_x000D_
_x000D_
// TEST_x000D_
_x000D_
let key = 'items[1].name' // arbitrary deep-key_x000D_
_x000D_
let data = {_x000D_
    code: 42,_x000D_
    items: [{ id: 11, name: 'foo'}, { id: 22, name: 'bar'},]_x000D_
};_x000D_
_x000D_
console.log( key,'=', deep(data,key) );
_x000D_
_x000D_
_x000D_

UICollectionView - Horizontal scroll, horizontal layout?

This code works well in Swift 3.1 and Xcode 8.3.2

override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()

        let layout = UICollectionViewFlowLayout()
        layout.scrollDirection = .horizontal
        self.collectionView.collectionViewLayout = layout
        self.collectionView!.contentInset = UIEdgeInsets(top: -10, left: 0, bottom:0, right: 0)

        if let layout = self.collectionView.collectionViewLayout as? UICollectionViewFlowLayout {
            layout.minimumInteritemSpacing = 0
            layout.minimumLineSpacing = 0
            layout.itemSize = CGSize(width: self.view.frame.size.width-40, height: self.collectionView.frame.size.height-10)
            layout.invalidateLayout()
        }

    }

Add a new item to a dictionary in Python

It can be as simple as:

default_data['item3'] = 3

As Chris' answer says, you can use update to add more than one item. An example:

default_data.update({'item4': 4, 'item5': 5})

Please see the documentation about dictionaries as data structures and dictionaries as built-in types.

Google Gson - deserialize list<class> object? (generic type)

Refer to this post. Java Type Generic as Argument for GSON

I have better solution for this. Here's the wrapper class for list so the wrapper can store the exactly type of list.

public class ListOfJson<T> implements ParameterizedType
{
  private Class<?> wrapped;

  public ListOfJson(Class<T> wrapper)
  {
    this.wrapped = wrapper;
  }

  @Override
  public Type[] getActualTypeArguments()
  {
      return new Type[] { wrapped };
  }

  @Override
  public Type getRawType()
  {
    return List.class;
  }

  @Override
  public Type getOwnerType()
  {
    return null;
  }
}

And then, the code can be simple:

public static <T> List<T> toList(String json, Class<T> typeClass)
{
    return sGson.fromJson(json, new ListOfJson<T>(typeClass));
}

tr:hover not working

You need to use <!DOCTYPE html> for :hover to work with anything other than the <a> tag. Try adding that to the top of your HTML.

Select n random rows from SQL Server table

The server-side processing language in use (eg PHP, .net, etc) isn't specified, but if it's PHP, grab the required number (or all the records) and instead of randomising in the query use PHP's shuffle function. I don't know if .net has an equivalent function but if it does then use that if you're using .net

ORDER BY RAND() can have quite a performance penalty, depending on how many records are involved.

How do you change the text in the Titlebar in Windows Forms?

public partial class Form1 : Form
{
    DateTime date = new DateTime();
    public Form1()
    {
        InitializeComponent();
}
    private void timer1_Tick(object sender, EventArgs e)
    {
        date = DateTime.Now;
        this.Text = "Date: "+date;
    }
}

I was having some problems with inserting date and time into the name of the form. Finally found the error. I'm posting this in case anyone has the same problem and doesn't have to spend years googling solutions.

CMD: How do I recursively remove the "Hidden"-Attribute of files and directories

For example folder named new under E: drive

type the command:

e:\cd new

e:\new\attrib *.* -s -h /s /d

and all the files and folders are un-hidden

How to change port number for apache in WAMP

Click on the WAMP server icon and from the menu under Config Files select httpd.conf. A long text file will open up in notepad. In this file scroll down to the line that reads Port 80 and change this to read Port 8080, Save the file and close notepad. Once again click on the wamp server icon and select restart all services. One more change needs to be made before we are done. In Windows Explorer find the location where WAMP server was installed which is by Default C:\Wamp.

Use of the MANIFEST.MF file in Java

The content of the Manifest file in a JAR file created with version 1.0 of the Java Development Kit is the following.

Manifest-Version: 1.0

All the entries are as name-value pairs. The name of a header is separated from its value by a colon. The default manifest shows that it conforms to version 1.0 of the manifest specification. The manifest can also contain information about the other files that are packaged in the archive. Exactly what file information is recorded in the manifest will depend on the intended use for the JAR file. The default manifest file makes no assumptions about what information it should record about other files, so its single line contains data only about itself. Special-Purpose Manifest Headers

Depending on the intended role of the JAR file, the default manifest may have to be modified. If the JAR file is created only for the purpose of archival, then the MANIFEST.MF file is of no purpose. Most uses of JAR files go beyond simple archiving and compression and require special information to be in the manifest file. Summarized below are brief descriptions of the headers that are required for some special-purpose JAR-file functions

Applications Bundled as JAR Files: If an application is bundled in a JAR file, the Java Virtual Machine needs to be told what the entry point to the application is. An entry point is any class with a public static void main(String[] args) method. This information is provided in the Main-Class header, which has the general form:

Main-Class: classname

The value classname is to be replaced with the application's entry point.

Download Extensions: Download extensions are JAR files that are referenced by the manifest files of other JAR files. In a typical situation, an applet will be bundled in a JAR file whose manifest references a JAR file (or several JAR files) that will serve as an extension for the purposes of that applet. Extensions may reference each other in the same way. Download extensions are specified in the Class-Path header field in the manifest file of an applet, application, or another extension. A Class-Path header might look like this, for example:

Class-Path: servlet.jar infobus.jar acme/beans.jar

With this header, the classes in the files servlet.jar, infobus.jar, and acme/beans.jar will serve as extensions for purposes of the applet or application. The URLs in the Class-Path header are given relative to the URL of the JAR file of the applet or application.

Package Sealing: A package within a JAR file can be optionally sealed, which means that all classes defined in that package must be archived in the same JAR file. A package might be sealed to ensure version consistency among the classes in your software or as a security measure. To seal a package, a Name header needs to be added for the package, followed by a Sealed header, similar to this:

Name: myCompany/myPackage/
Sealed: true

The Name header's value is the package's relative pathname. Note that it ends with a '/' to distinguish it from a filename. Any headers following a Name header, without any intervening blank lines, apply to the file or package specified in the Name header. In the above example, because the Sealed header occurs after the Name: myCompany/myPackage header, with no blank lines between, the Sealed header will be interpreted as applying (only) to the package myCompany/myPackage.

Package Versioning: The Package Versioning specification defines several manifest headers to hold versioning information. One set of such headers can be assigned to each package. The versioning headers should appear directly beneath the Name header for the package. This example shows all the versioning headers:

Name: java/util/
Specification-Title: "Java Utility Classes" 
Specification-Version: "1.2"
Specification-Vendor: "Sun Microsystems, Inc.".
Implementation-Title: "java.util" 
Implementation-Version: "build57"
Implementation-Vendor: "Sun Microsystems, Inc."

Possible reason for NGINX 499 error codes

In my case, I have setup like

AWS ELB >> ECS(nginx) >> ECS(php-fpm).

I had configured the wrong AWS security group for ECS(php-fpm) service, so Nginx wasn't able to reach out to php-fpm task container. That's why i was getting errors in nginx task log

499 0 - elb-healthchecker/2.0

Health check was configured as to check php-fpm service and confirm it's up and give back a response.

How can I open a website in my web browser using Python?

If you want to open any website first you need to import a module called "webbrowser". Then just use webbrowser.open() to open a website. e.g.

 import webbrowser

 webbrowser.open('https://yashprogrammer.wordpress.com/', new= 2)

Embed website into my site

You might want to check HTML frames, which can do pretty much exactly what you are looking for. They are considered outdated however.

Importing class from another file

Your problem is basically that you never specified the right path to the file.

Try instead, from your main script:

from folder.file import Klasa

Or, with from folder import file:

from folder import file
k = file.Klasa()

Or again:

import folder.file as myModule
k = myModule.Klasa()

Laravel - Eloquent or Fluent random row

Use Laravel function

ModelName::inRandomOrder()->first();

SOAP-UI - How to pass xml inside parameter

NOTE: This one is just an alternative for the previous provided .NET framework 3.5 and above

You can send it as raw xml

<test>or like this</test>

If you declare the paramater2 as XElement data type

.NET Global exception handler in console application

You also need to handle exceptions from threads:

static void Main(string[] args) {
Application.ThreadException += MYThreadHandler;
}

private void MYThreadHandler(object sender, Threading.ThreadExceptionEventArgs e)
{
    Console.WriteLine(e.Exception.StackTrace);
}

Whoop, sorry that was for winforms, for any threads you're using in a console application you will have to enclose in a try/catch block. Background threads that encounter unhandled exceptions do not cause the application to end.

handle textview link click in my android app

Another way, borrows a bit from Linkify but allows you to customize your handling.

Custom Span Class:

public class ClickSpan extends ClickableSpan {

    private OnClickListener mListener;

    public ClickSpan(OnClickListener listener) {
        mListener = listener;
    }

    @Override
    public void onClick(View widget) {
       if (mListener != null) mListener.onClick();
    }

    public interface OnClickListener {
        void onClick();
    }
}

Helper function:

public static void clickify(TextView view, final String clickableText, 
    final ClickSpan.OnClickListener listener) {

    CharSequence text = view.getText();
    String string = text.toString();
    ClickSpan span = new ClickSpan(listener);

    int start = string.indexOf(clickableText);
    int end = start + clickableText.length();
    if (start == -1) return;

    if (text instanceof Spannable) {
        ((Spannable)text).setSpan(span, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    } else {
        SpannableString s = SpannableString.valueOf(text);
        s.setSpan(span, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        view.setText(s);
    }

    MovementMethod m = view.getMovementMethod();
    if ((m == null) || !(m instanceof LinkMovementMethod)) {
        view.setMovementMethod(LinkMovementMethod.getInstance());
    }
}

Usage:

 clickify(textView, clickText,new ClickSpan.OnClickListener()
     {
        @Override
        public void onClick() {
            // do something
        }
    });

Shell equality operators (=, ==, -eq)

Several answers show dangerous examples. OP's example [ $a == $b ] specifically used unquoted variable substitution (as of Oct '17 edit). For [...] that is safe for string equality.

But if you're going to enumerate alternatives like [[...]], you must inform also that the right-hand-side must be quoted. If not quoted, it is a pattern match! (From bash man page: "Any part of the pattern may be quoted to force it to be matched as a string.").

Here in bash, the two statements yielding "yes" are pattern matching, other three are string equality:

$ rht="A*"
$ lft="AB"
$ [ $lft = $rht ] && echo yes
$ [ $lft == $rht ] && echo yes
$ [[ $lft = $rht ]] && echo yes
yes
$ [[ $lft == $rht ]] && echo yes
yes
$ [[ $lft == "$rht" ]] && echo yes
$

When to use static methods

Whenever you do not want to create an object to call a method in your code just declare that method as static. Since the static method does not need an instance to be called with but the catch here is not all static methods are called by JVM automatically. This privilege is enjoyed only by the main() "public static void main[String... args]" method in java because at Runtime this is the method Signature public "static" void main[] sought by JVM as an entry point to start execution of the code.

Example:

public class Demo
{
   public static void main(String... args) 
   {
      Demo d = new Demo();

      System.out.println("This static method is executed by JVM");

     //Now to call the static method Displ() you can use the below methods:
           Displ(); //By method name itself    
      Demo.Displ(); //By using class name//Recommended
         d.Displ(); //By using instance //Not recommended
   }

   public static void Displ()
   {
      System.out.println("This static method needs to be called explicitly");
   }
} 

Output:- This static method is executed by JVM This static method needs to be called explicitly This static method needs to be called explicitly This static method needs to be called explicitly

How to create python bytes object from long hex string?

Works in Python 2.7 and higher including python3:

result = bytearray.fromhex('deadbeef')

Note: There seems to be a bug with the bytearray.fromhex() function in Python 2.6. The python.org documentation states that the function accepts a string as an argument, but when applied, the following error is thrown:

>>> bytearray.fromhex('B9 01EF')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: fromhex() argument 1 must be unicode, not str`

Setting UILabel text to bold

Use attributed string:

// Define attributes
let labelFont = UIFont(name: "HelveticaNeue-Bold", size: 18)
let attributes :Dictionary = [NSFontAttributeName : labelFont]

// Create attributed string
var attrString = NSAttributedString(string: "Foo", attributes:attributes)
label.attributedText = attrString

You need to define attributes.

Using attributed string you can mix colors, sizes, fonts etc within one text

static and extern global variables in C and C++

When you #include a header, it's exactly as if you put the code into the source file itself. In both cases the varGlobal variable is defined in the source so it will work no matter how it's declared.

Also as pointed out in the comments, C++ variables at file scope are not static in scope even though they will be assigned to static storage. If the variable were a class member for example, it would need to be accessible to other compilation units in the program by default and non-class members are no different.

Reverting single file in SVN to a particular revision

Just adding on to @Mitch Dempsy answer since I don't have enough rep to comment yet.

svn export -r <REV> svn://host/path/to/file/on/repos --force

Adding the --force will overwrite the local copy with the export and then you can do an svn commit to push it to the repository.

Enabling CORS in Cloud Functions for Firebase

If none of the other solutions work, you could try adding the below address at the beginning of the call to enable CORS - redirect:

https://cors-anywhere.herokuapp.com/

Sample code with JQuery AJAX request:

$.ajax({
   url: 'https://cors-anywhere.herokuapp.com/https://fir-agilan.web.app/[email protected],
   type: 'GET'
});

split python source code into multiple files?

Python has importing and namespacing, which are good. In Python you can import into the current namespace, like:

>>> from test import disp
>>> disp('World!')

Or with a namespace:

>>> import test
>>> test.disp('World!')

Doctrine 2 ArrayCollection filter method

The Collection#filter method really does eager load all members. Filtering at the SQL level will be added in doctrine 2.3.

How to terminate a Python script

import sys
sys.exit()

details from the sys module documentation:

sys.exit([arg])

Exit from Python. This is implemented by raising the SystemExit exception, so cleanup actions specified by finally clauses of try statements are honored, and it is possible to intercept the exit attempt at an outer level.

The optional argument arg can be an integer giving the exit status (defaulting to zero), or another type of object. If it is an integer, zero is considered “successful termination” and any nonzero value is considered “abnormal termination” by shells and the like. Most systems require it to be in the range 0-127, and produce undefined results otherwise. Some systems have a convention for assigning specific meanings to specific exit codes, but these are generally underdeveloped; Unix programs generally use 2 for command line syntax errors and 1 for all other kind of errors. If another type of object is passed, None is equivalent to passing zero, and any other object is printed to stderr and results in an exit code of 1. In particular, sys.exit("some error message") is a quick way to exit a program when an error occurs.

Since exit() ultimately “only” raises an exception, it will only exit the process when called from the main thread, and the exception is not intercepted.

Note that this is the 'nice' way to exit. @glyphtwistedmatrix below points out that if you want a 'hard exit', you can use os._exit(*errorcode*), though it's likely os-specific to some extent (it might not take an errorcode under windows, for example), and it definitely is less friendly since it doesn't let the interpreter do any cleanup before the process dies. On the other hand, it does kill the entire process, including all running threads, while sys.exit() (as it says in the docs) only exits if called from the main thread, with no other threads running.

CSS media queries for screen sizes

Unless you have more style sheets than that, you've messed up your break points:

#1 (max-width: 700px)
#2 (min-width: 701px) and (max-width: 900px)
#3 (max-width: 901px)

The 3rd media query is probably meant to be min-width: 901px. Right now, it overlaps #1 and #2, and only controls the page layout by itself when the screen is exactly 901px wide.

Edit for updated question:

(max-width: 640px)
(max-width: 800px)
(max-width: 1024px)
(max-width: 1280px)

Media queries aren't like catch or if/else statements. If any of the conditions match, then it will apply all of the styles from each media query it matched. If you only specify a min-width for all of your media queries, it's possible that some or all of the media queries are matched. In your case, a device that's 640px wide matches all 4 of your media queries, so all for style sheets are loaded. What you are most likely looking for is this:

(max-width: 640px)
(min-width: 641px) and (max-width: 800px)
(min-width: 801px) and (max-width: 1024px)
(min-width: 1025px)

Now there's no overlap. The styles will only apply if the device's width falls between the widths specified.

How to query MongoDB with "like"?

Already u got the answers but to match regex with case insensitivity

You could use the following query

db.users.find ({ "name" : /m/i } ).pretty()

The i in the /m/i indicates case insensitivity and .pretty() provides a more pretty output

TCP: can two different sockets share a port?

TCP / HTTP Listening On Ports: How Can Many Users Share the Same Port

So, what happens when a server listen for incoming connections on a TCP port? For example, let's say you have a web-server on port 80. Let's assume that your computer has the public IP address of 24.14.181.229 and the person that tries to connect to you has IP address 10.1.2.3. This person can connect to you by opening a TCP socket to 24.14.181.229:80. Simple enough.

Intuitively (and wrongly), most people assume that it looks something like this:

    Local Computer    | Remote Computer
    --------------------------------
    <local_ip>:80     | <foreign_ip>:80

    ^^ not actually what happens, but this is the conceptual model a lot of people have in mind.

This is intuitive, because from the standpoint of the client, he has an IP address, and connects to a server at IP:PORT. Since the client connects to port 80, then his port must be 80 too? This is a sensible thing to think, but actually not what happens. If that were to be correct, we could only serve one user per foreign IP address. Once a remote computer connects, then he would hog the port 80 to port 80 connection, and no one else could connect.

Three things must be understood:

1.) On a server, a process is listening on a port. Once it gets a connection, it hands it off to another thread. The communication never hogs the listening port.

2.) Connections are uniquely identified by the OS by the following 5-tuple: (local-IP, local-port, remote-IP, remote-port, protocol). If any element in the tuple is different, then this is a completely independent connection.

3.) When a client connects to a server, it picks a random, unused high-order source port. This way, a single client can have up to ~64k connections to the server for the same destination port.

So, this is really what gets created when a client connects to a server:

    Local Computer   | Remote Computer           | Role
    -----------------------------------------------------------
    0.0.0.0:80       | <none>                    | LISTENING
    127.0.0.1:80     | 10.1.2.3:<random_port>    | ESTABLISHED

Looking at What Actually Happens

First, let's use netstat to see what is happening on this computer. We will use port 500 instead of 80 (because a whole bunch of stuff is happening on port 80 as it is a common port, but functionally it does not make a difference).

    netstat -atnp | grep -i ":500 "

As expected, the output is blank. Now let's start a web server:

    sudo python3 -m http.server 500

Now, here is the output of running netstat again:

    Proto Recv-Q Send-Q Local Address           Foreign Address         State  
    tcp        0      0 0.0.0.0:500             0.0.0.0:*               LISTEN      - 

So now there is one process that is actively listening (State: LISTEN) on port 500. The local address is 0.0.0.0, which is code for "listening for all ip addresses". An easy mistake to make is to only listen on port 127.0.0.1, which will only accept connections from the current computer. So this is not a connection, this just means that a process requested to bind() to port IP, and that process is responsible for handling all connections to that port. This hints to the limitation that there can only be one process per computer listening on a port (there are ways to get around that using multiplexing, but this is a much more complicated topic). If a web-server is listening on port 80, it cannot share that port with other web-servers.

So now, let's connect a user to our machine:

    quicknet -m tcp -t localhost:500 -p Test payload.

This is a simple script (https://github.com/grokit/quickweb) that opens a TCP socket, sends the payload ("Test payload." in this case), waits a few seconds and disconnects. Doing netstat again while this is happening displays the following:

    Proto Recv-Q Send-Q Local Address           Foreign Address         State  
    tcp        0      0 0.0.0.0:500             0.0.0.0:*               LISTEN      -
    tcp        0      0 192.168.1.10:500        192.168.1.13:54240      ESTABLISHED -

If you connect with another client and do netstat again, you will see the following:

    Proto Recv-Q Send-Q Local Address           Foreign Address         State  
    tcp        0      0 0.0.0.0:500             0.0.0.0:*               LISTEN      -
    tcp        0      0 192.168.1.10:500        192.168.1.13:26813      ESTABLISHED -

... that is, the client used another random port for the connection. So there is never confusion between the IP addresses.

Can't update: no tracked branch

Assume you have a local branch "Branch-200" (or other name) and server repository contains "origin/Branch-1". If you have local "Branch-1" not linked with "origin/Branch-1", rename it to "Branch-200".

In Android Studio checkout to "origin/Branch-1" creating a new local branch "Branch-1", then merge with you local branch "Branch-200".

Default session timeout for Apache Tomcat applications

Open $CATALINA_BASE/conf/web.xml and find this

<!-- ==================== Default Session Configuration ================= -->
<!-- You can set the default session timeout (in minutes) for all newly   -->
<!-- created sessions by modifying the value below.                       -->

<session-config>
  <session-timeout>30</session-timeout>
</session-config>

all webapps implicitly inherit from this default web descriptor. You can override session-config as well as other settings defined there in your web.xml.

This is actually from my Tomcat 7 (Windows) but I think 5.5 conf is not very different

Are there any log file about Windows Services Status?

Through the Computer management console, navigate through Event Viewer > Windows Logs > System. Every services that change state will be logged here.

You'll see info like: The XXXX service entered the running state or The XXXX service entered the stopped state, etc.

Java, Simplified check if int array contains int

A different way:

public boolean contains(final int[] array, final int key) {  
     Arrays.sort(array);  
     return Arrays.binarySearch(array, key) >= 0;  
}  

This modifies the passed-in array. You would have the option to copy the array and work on the original array i.e. int[] sorted = array.clone();
But this is just an example of short code. The runtime is O(NlogN) while your way is O(N)

Test if number is odd or even

Yes using the mod

$even = ($num % 2 == 0);
$odd = ($num % 2 != 0);

Synchronous request in Node.js

You could do this using my Common Node library:

function get(url) {
  return new (require('httpclient').HttpClient)({
    method: 'GET',
      url: url
    }).finish().body.read().decodeToString();
}

var a = get('www.example.com/api_1.php'), 
    b = get('www.example.com/api_2.php'),
    c = get('www.example.com/api_3.php');

Change background colour for Visual Studio

You can also use the Visual Studio Theme Generator. I have only tried this with VS 2005, but the settings it generates may work with newer versions of VS as well.

In case the link goes dead in the future here is a dark theme I generated. Just put this text into a file named VS_2005_dark_theme.vssettings and import it using Tools -> Import and Export Settings:

<UserSettings>
    <ApplicationIdentity version="8.0"/>
    <ToolsOptions>
        <ToolsOptionsCategory name="Environment" RegisteredName="Environment"/>
    </ToolsOptions>
    <Category name="Environment_Group" RegisteredName="Environment_Group">
        <Category name="Environment_FontsAndColors" Category="{1EDA5DD4-927A-43a7-810E-7FD247D0DA1D}" Package="{DA9FB551-C724-11d0-AE1F-00A0C90FFFC3}" RegisteredName="Environment_FontsAndColors" PackageName="Visual Studio Environment Package">
            <PropertyValue name="Version">2</PropertyValue>
            <FontsAndColors Version="2.0">
                <Categories>
                    <Category GUID="{5C48B2CB-0366-4FBF-9786-0BB37E945687}" FontName="PalmOS" FontSize="8" CharSet="0" FontIsDefault="No">
                        <Items>
                            <Item Name="Plain Text" Foreground="0x0000FF00" Background="0x00003700" BoldFont="No"/>
                            <Item Name="Selected Text" Foreground="0x00003700" Background="0x0000FF00" BoldFont="No"/>
                            <Item Name="Inactive Selected Text" Foreground="0x00003700" Background="0x00009100" BoldFont="No"/>
                            <Item Name="Current list location" Foreground="0x00A3DBFF" Background="0x01000007" BoldFont="No"/>
                        </Items>
                    </Category>
                    <Category GUID="{9973EFDF-317D-431C-8BC1-5E88CBFD4F7F}" FontName="PalmOS" FontSize="8" CharSet="0" FontIsDefault="No">
                        <Items>
                            <Item Name="Plain Text" Foreground="0x0057C732" Background="0x0017340E" BoldFont="No"/>
                            <Item Name="Selected Text" Foreground="0x00003700" Background="0x0000FF00" BoldFont="No"/>
                            <Item Name="Inactive Selected Text" Foreground="0x00003700" Background="0x00009100" BoldFont="No"/>
                            <Item Name="Current list location" Foreground="0x00A3DBFF" Background="0x01000007" BoldFont="No"/>
                        </Items>
                    </Category>
                    <Category GUID="{A27B4E24-A735-4D1D-B8E7-9716E1E3D8E0}" FontName="Monaco" FontSize="9" CharSet="0" FontIsDefault="No">
                        <Items>
                            <Item Name="Plain Text" Foreground="00CFCFCF" Background="00383838" BoldFont="No"/>
                            <Item Name="Indicator Margin" Foreground="0x02000000" Background="00383838" BoldFont="No"/>
                            <Item Name="Line Numbers" Foreground="00828282" Background="00383838" BoldFont="No"/>
                            <Item Name="Visible White Space" Foreground="0x00808080" Background="0x02000000" BoldFont="No"/>
                            <Item Name="Comment" Foreground="00828282" Background="0x02000000" BoldFont="No"/>
                            <Item Name="Compiler Error" Foreground="000000F0" Background="0x02000000" BoldFont="No"/>
                            <Item Name="CSS Comment" Foreground="00828282" Background="0x02000000" BoldFont="No"/>
                            <Item Name="CSS Keyword" Foreground="00FECE2F" Background="0x02000000" BoldFont="No"/>
                            <Item Name="CSS Property Name" Foreground="00FECE2F" Background="0x02000000" BoldFont="No"/>
                            <Item Name="CSS Property Value" Foreground="00F12FFE" Background="0x02000000" BoldFont="No"/>
                            <Item Name="CSS Selector" Foreground="00CFCFCF" Background="0x02000000" BoldFont="No"/>
                            <Item Name="CSS String Value" Foreground="0032FE2F" Background="0x02000000" BoldFont="No"/>
                            <Item Name="HTML Attribute" Foreground="00CFCFCF" Background="0x02000000" BoldFont="No"/>
                            <Item Name="HTML Attribute Value" Foreground="0032FE2F" Background="0x02000000" BoldFont="No"/>
                            <Item Name="HTML Comment" Foreground="00828282" Background="0x02000000" BoldFont="No"/>
                            <Item Name="HTML Element Name" Foreground="00FECE2F" Background="0x02000000" BoldFont="No"/>
                            <Item Name="HTML Operator" Foreground="00CFCFCF" Background="0x02000000" BoldFont="No"/>
                            <Item Name="Identifier" Foreground="00CFCFCF" Background="0x02000000" BoldFont="No"/>
                            <Item Name="Keyword" Foreground="00FECE2F" Background="0x02000000" BoldFont="No"/>
                            <Item Name="Number" Foreground="002FFE60" Background="0x02000000" BoldFont="No"/>
                            <Item Name="Operator" Foreground="00CFCFCF" Background="0x02000000" BoldFont="No"/>
                            <Item Name="Preprocessor Keyword" Foreground="00FE2F8C" Background="0x02000000" BoldFont="No"/>
                            <Item Name="Stale Code" Foreground="0x00808080" Background="0x00C0C0C0" BoldFont="No"/>
                            <Item Name="String" Foreground="0032FE2F" Background="0x02000000" BoldFont="No"/>
                            <Item Name="String (C# Verbatim)" Foreground="00FE2F8C" Background="0x02000000" BoldFont="No"/>
                            <Item Name="Task List Shortcut" Foreground="0x00FFFFFF" Background="0x02C0C0C0" BoldFont="No"/>
                            <Item Name="User Keywords" Foreground="00F12FFE" Background="0x02000000" BoldFont="No"/>
                            <Item Name="User Types" Foreground="00D64EDF" Background="0x02000000" BoldFont="No"/>
                            <Item Name="Warning" Foreground="000000F0" Background="0x02000000" BoldFont="No"/>
                            <Item Name="XAML Attribute" Foreground="00CFCFCF" Background="0x02000000" BoldFont="No"/>
                            <Item Name="XAML Attribute Quotes" Foreground="0032FE2F" Background="0x02000000" BoldFont="No"/>
                            <Item Name="XAML Attribute Value" Foreground="0032FE2F" Background="0x02000000" BoldFont="No"/>
                            <Item Name="XAML Comment" Foreground="00828282" Background="0x02000000" BoldFont="No"/>
                            <Item Name="XAML Delimiter" Foreground="00CFCFCF" Background="0x02000000" BoldFont="No"/>
                            <Item Name="XAML Keyword" Foreground="00FECE2F" Background="0x02000000" BoldFont="No"/>
                            <Item Name="XAML Markup Extension Class" Foreground="00FECE2F" Background="0x02000000" BoldFont="No"/>
                            <Item Name="XAML Markup Extension Parameter Name" Foreground="00F12FFE" Background="0x02000000" BoldFont="No"/>
                            <Item Name="XAML Markup Extension Parameter Value" Foreground="00D64EDF" Background="0x02000000" BoldFont="No"/>
                            <Item Name="XAML Name" Foreground="00FECE2F" Background="0x02000000" BoldFont="No"/>
                            <Item Name="XAML Processing Instruction" Foreground="00FE2F8C" Background="0x02000000" BoldFont="No"/>
                            <Item Name="XAML Text" Foreground="00CFCFCF" Background="0x02000000" BoldFont="No"/>                            
                            <Item Name="XML @ Attribute" Foreground="00CFCFCF" Background="0x02000000" BoldFont="No"/>
                            <Item Name="XML Attribute Quotes" Foreground="0032FE2F" Background="0x02000000" BoldFont="No"/>
                            <Item Name="XML Attribute Value" Foreground="0032FE2F" Background="0x02000000" BoldFont="No"/>
                            <Item Name="XML Comment" Foreground="00828282" Background="0x02000000" BoldFont="No"/>
                            <Item Name="XML Delimiter" Foreground="00CFCFCF" Background="0x02000000" BoldFont="No"/>
                            <Item Name="XML Doc Attribute" Foreground="00D64EDF" Background="0x02000000" BoldFont="No"/>
                            <Item Name="XML Doc Comment" Foreground="00828282" Background="0x02000000" BoldFont="No"/>
                            <Item Name="XML Doc Tag" Foreground="00D64EDF" Background="0x02000000" BoldFont="No"/>
                            <Item Name="XML Keyword" Foreground="00FECE2F" Background="0x02000000" BoldFont="No"/>
                            <Item Name="XML Name" Foreground="00FECE2F" Background="0x02000000" BoldFont="No"/>
                            <Item Name="XML Processing Instruction" Foreground="0x0015496C" Background="0x02000000" BoldFont="No"/>
                            <Item Name="XML Text" Foreground="00CFCFCF" Background="0x02000000" BoldFont="No"/>
                            <Item Name="XSLT Keyword" Foreground="00FECE2F" Background="0x02000000" BoldFont="No"/>                                                                 
                        </Items>
                    </Category>
                </Categories>
            </FontsAndColors>
        </Category>
    </Category>
</UserSettings>

How to add a bot to a Telegram Group?

Another way :

change BOT_USER_NAME before use

https://telegram.me/BOT_USER_NAME?startgroup=true

is vs typeof

This should answer that question, and then some.

The second line, if (obj.GetType() == typeof(ClassA)) {}, is faster, for those that don't want to read the article.

(Be aware that they don't do the same thing)

Scanner doesn't read whole sentence - difference between next() and nextLine() of scanner class

I would use Scanner#nextLine opposed to next for your address attribute.

This method returns the rest of the current line, excluding any line separator at the end.

Since this returns the entire line, delimited by a line separator, it will allow the user to enter any address without any constraint.

What is the maximum value for an int32?

Remember this: 21 IQ ITEM 47

It can be de-encoded with any phone pad, or you can just write one down yourself on a paper.

In order to remember "21 IQ ITEM 47", I would go with "Hitman:Codename 47 had 21 missions, which were each IQ ITEM's by themselves".

Or "I clean teeth at 21:47 every day, because I have high IQ and don't like items in my mouth".

How to vertically align a html radio button to it's label?

A lot of these answers say to use vertical-align: middle;, which gets the alignment close but for me it is still off by a few pixels. The method that I used to get true 1 to 1 alignment between the labels and radio inputs is this, with vertical-align: top;:

_x000D_
_x000D_
label, label>input{_x000D_
    font-size: 20px;_x000D_
    display: inline-block;_x000D_
    margin: 0;_x000D_
    line-height: 28px;_x000D_
    height: 28px;_x000D_
    vertical-align: top;_x000D_
}
_x000D_
<h1>How are you?</h1>_x000D_
<fieldset>_x000D_
 <legend>Your response:</legend>_x000D_
 <label for="radChoiceGood">_x000D_
  <input type="radio" id="radChoiceGood" name="radChoices" value="Good">Good_x000D_
 </label>_x000D_
 _x000D_
 <label for="radChoiceExcellent">_x000D_
  <input type="radio" id="radChoiceExcellent" name="radChoices" value="Excellent">Excellent_x000D_
 </label>_x000D_
 _x000D_
 <label for="radChoiceOk">_x000D_
  <input type="radio" id="radChoiceOk" name="radChoices" value="OK">OK_x000D_
 </label>_x000D_
</fieldset>
_x000D_
_x000D_
_x000D_

DataTables fixed headers misaligned with columns in wide tables

The code below worked. Corrected the issue on I.E 9.0 atleast. Hope this helps

var oTable =  $('#tblList').dataTable({
    "sScrollY": "320px",
    "bScrollCollapse": true,
    });

    setTimeout(function(){
        oTable.fnAdjustColumnSizing();
    },10);

Add column to SQL Server

Add new column to Table with default value.

ALTER TABLE NAME_OF_TABLE
ADD COLUMN_NAME datatype
DEFAULT DEFAULT_VALUE

c# open file with default application and parameters

you can try with

Process process = new Process();
process.StartInfo.FileName = "yourProgram.exe";
process.StartInfo.Arguments = ..... //your parameters
process.Start();

Selecting a Record With MAX Value

Say, for an user, there is revision for each date. The following will pick up record for the max revision of each date for each employee.

select job, adate, rev, usr, typ 
from tbl
where exists (  select 1 from ( select usr, adate, max(rev) as max_rev 
                                from tbl
                                group by usr, adate 
                              ) as cond
                where tbl.usr=cond.usr 
                and tbl.adate =cond.adate 
                and tbl.rev =cond.max_rev
             )
order by adate, job, usr

What is the best way to determine a session variable is null or empty in C#?

Checking for nothing/Null is the way to do it.

Dealing with object types is not the way to go. Declare a strict type and try to cast the object to the correct type. (And use cast hint or Convert)

 private const string SESSION_VAR = "myString";
 string sSession;
 if (Session[SESSION_VAR] != null)
 {
     sSession = (string)Session[SESSION_VAR];
 }
 else
 {
     sSession = "set this";
     Session[SESSION_VAR] = sSession;
 }

Sorry for any syntax violations, I am a daily VB'er

Can I use conditional statements with EJS templates (in JMVC)?

Yes , You can use conditional statement with EJS like if else , ternary operator or even switch case also

For Example

Ternary operator : <%- role == 'Admin' ? 'Super Admin' : role == 'subAdmin' ? 'Sub Admin' : role %>

Switch Case

<% switch (role) {
case 'Admin' : %>
        Super Admin
        <% break;

case 'eventAdmin' : %>
        Event Admin
        <% break;

case 'subAdmin' : %>
        Sub Admin
        <% break;

} %>

How to remove an item from an array in Vue.js

<v-btn color="info" @click="eliminarTarea(item.id)">Eliminar</v-btn>

And for your JS:

this.listaTareas = this.listaTareas.filter(i=>i.id != id)

How to read line by line of a text area HTML tag

A simple regex should be efficent to check your textarea:

/\s*\d+\s*\n/g.test(text) ? "OK" : "KO"

html form - make inputs appear on the same line

use table

<table align="center" width="100%" cellpadding="0" cellspacing="0" border="0"> 
<tr>
<td><label for="First_Name">First Name:</label></td>
<td><input name="first_name" id="First_Name" type="text" /></td>
<td><label for="last_name">Last Name:</label></td> <td> 
<input name="last_name" id="Last_Name" type="text" /></td> 
</tr> 
<tr> 
<td colspan="2"><label for="Email">Email:</label></td> 
<td colspan="2"><input name="email" id="Email" type="email" /></td> 
</tr> 
<tr> 
<td colspan="4"><input type="submit" value="Submit"/></td> 
</tr> 
</table>

React proptype array with shape

Yes, you need to use PropTypes.arrayOf instead of PropTypes.array in the code, you can do something like this:

import PropTypes from 'prop-types';

MyComponent.propTypes = {
  annotationRanges: PropTypes.arrayOf(
    PropTypes.shape({
      start: PropTypes.string.isRequired,
      end: PropTypes.number.isRequired
    }).isRequired
  ).isRequired
}

Also for more details about proptypes, visit Typechecking With PropTypes here

jQuery: more than one handler for same event

Made it work successfully using the 2 methods: Stephan202's encapsulation and multiple event listeners. I have 3 search tabs, let's define their input text id's in an Array:

var ids = new Array("searchtab1", "searchtab2", "searchtab3");

When the content of searchtab1 changes, I want to update searchtab2 and searchtab3. Did it this way for encapsulation:

for (var i in ids) {
    $("#" + ids[i]).change(function() {
        for (var j in ids) {
            if (this != ids[j]) {
                $("#" + ids[j]).val($(this).val());
            }
        }
    });
}

Multiple event listeners:

for (var i in ids) {
    for (var j in ids) {
        if (ids[i] != ids[j]) {
            $("#" + ids[i]).change(function() {
                $("#" + ids[j]).val($(this).val());
            });
        }
    }
}

I like both methods, but the programmer chose encapsulation, however multiple event listeners worked also. We used Chrome to test it.

Chart.js canvas resize

I had to use a combination of multiple answers here with some minor tweaks.

First, it is necessary that you wrap the canvas element within a block-level container. I say to you, do not let the canvas element have any siblings; let it be a lonely child, for it is stubborn and spoiled. (The wrapper may not need any sizing restrictions placed on it, but for safety it may be good to have a max-height applied to it.)

After assuring that the previous conditions are met, when initiating the chart, make sure the following options are used:

var options = { 
    "responsive": true,
    "maintainAspectRatio": false
}

If you want to adjust the height of the chart, do so at the canvas element level.

<canvas height="500"></canvas>

Do not try to deal with the child in any other manner. This should result in a satisfyingly, properly laid-out chart, one that stays in its crib peacefully.

Limit on the WHERE col IN (...) condition

You can use tuples like this: SELECT * FROM table WHERE (Col, 1) IN ((123,1),(123,1),(222,1),....)

There are no restrictions on number of these. It compares pairs.

How can I trim leading and trailing white space?

myDummy[myDummy$country == "Austria "] <- "Austria"

After this, you'll need to force R not to recognize "Austria " as a level. Let's pretend you also have "USA" and "Spain" as levels:

myDummy$country = factor(myDummy$country, levels=c("Austria", "USA", "Spain"))

It is a little less intimidating than the highest voted response, but it should still work.

Grouping into interval of 5 minutes within a time range

Not sure if you still need it.

SELECT FROM_UNIXTIME(FLOOR((UNIX_TIMESTAMP(timestamp))/300)*300) AS t,timestamp,count(1) as c from users GROUP BY t ORDER BY t;

2016-10-29 19:35:00 | 2016-10-29 19:35:50 | 4 |

2016-10-29 19:40:00 | 2016-10-29 19:40:37 | 5 |

2016-10-29 19:45:00 | 2016-10-29 19:45:09 | 6 |

2016-10-29 19:50:00 | 2016-10-29 19:51:14 | 4 |

2016-10-29 19:55:00 | 2016-10-29 19:56:17 | 1 |

Keep-alive header clarification

Where is this info kept ("this connection is between computer A and server F")?

A TCP connection is recognized by source IP and port and destination IP and port. Your OS, all intermediate session-aware devices and the server's OS will recognize the connection by this.

HTTP works with request-response: client connects to server, performs a request and gets a response. Without keep-alive, the connection to an HTTP server is closed after each response. With HTTP keep-alive you keep the underlying TCP connection open until certain criteria are met.

This allows for multiple request-response pairs over a single TCP connection, eliminating some of TCP's relatively slow connection startup.

When The IIS (F) sends keep alive header (or user sends keep-alive) , does it mean that (E,C,B) save a connection

No. Routers don't need to remember sessions. In fact, multiple TCP packets belonging to same TCP session need not all go through same routers - that is for TCP to manage. Routers just choose the best IP path and forward packets. Keep-alive is only for client, server and any other intermediate session-aware devices.

which is only for my session ?

Does it mean that no one else can use that connection

That is the intention of TCP connections: it is an end-to-end connection intended for only those two parties.

If so - does it mean that keep alive-header - reduce the number of overlapped connection users ?

Define "overlapped connections". See HTTP persistent connection for some advantages and disadvantages, such as:

  • Lower CPU and memory usage (because fewer connections are open simultaneously).
  • Enables HTTP pipelining of requests and responses.
  • Reduced network congestion (fewer TCP connections).
  • Reduced latency in subsequent requests (no handshaking).

if so , for how long does the connection is saved to me ? (in other words , if I set keep alive- "keep" till when?)

An typical keep-alive response looks like this:

Keep-Alive: timeout=15, max=100

See Hypertext Transfer Protocol (HTTP) Keep-Alive Header for example (a draft for HTTP/2 where the keep-alive header is explained in greater detail than both 2616 and 2086):

  • A host sets the value of the timeout parameter to the time that the host will allows an idle connection to remain open before it is closed. A connection is idle if no data is sent or received by a host.

  • The max parameter indicates the maximum number of requests that a client will make, or that a server will allow to be made on the persistent connection. Once the specified number of requests and responses have been sent, the host that included the parameter could close the connection.

However, the server is free to close the connection after an arbitrary time or number of requests (just as long as it returns the response to the current request). How this is implemented depends on your HTTP server.