Programs & Examples On #Flash 8

How to choose between Hudson and Jenkins?

Up front .. I am a Hudson committer and author of the Hudson book, but I was not involved in the whole split of the projects.

In any case here is my advice:

Check out both and see what fits your needs better.

Hudson is going to complete the migration to be a top level Eclipse projects later this year and has gotten a whole bunch of full time developers, QA and others working on the project. It is still going strong and has a lot of users and with being the default CI server at Eclipse it will continue to serve the needs of many Java developers. Looking at the roadmap and plans for the future you can see that after the Maven 3 integration accomplished with the 2.1.0 release a whole bunch of other interesting feature are ahead.

http://www.eclipse.org/hudson

Jenkins on the other side has won over many original Hudson users and has a large user community across multiple technologies and also has a whole bunch of developers working on it.

At this stage both CI servers are great tools to use and depending on your needs in terms of technology to integrate with one or the other might be better. Both products are available as open source and you can get commercial support from various companies for both.

In any case .. if you are not using a CI server yet.. start now with either of them and you will see huge benefits.

Update Jan 2013: After a long process of IP cleanup and further improvements Hudson 3.0 as the first Eclipse foundation approved release is now available.

Tomcat 7 "SEVERE: A child container failed during start"

I have same problem but in my case By mistake I added a context in server.xml ($Tomcat_Install_Dir/conf/) and doesn't deployed corresponing war in webapps($Tomcat_Install_Dir/webapps). As I removed that context and restarted tomcat it working fine.

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

Check if these free resources fit your need -

How can I set multiple CSS styles in JavaScript?

I think is this a very simple way with regards to all solutions above:

const elm = document.getElementById("myElement")

const allMyStyle = [
  { prop: "position", value: "fixed" },
  { prop: "boxSizing", value: "border-box" },
  { prop: "opacity", value: 0.9 },
  { prop: "zIndex", value: 1000 },
];

allMyStyle.forEach(({ prop, value }) => {
  elm.style[prop] = value;
});

How to stop text from taking up more than 1 line?

Just to be crystal clear, this works nicely with paragraphs and headers etc. You just need to specify display: block.

For instance:

<h5 style="display: block; text-overflow: ellipsis; white-space: nowrap; overflow: hidden">
  This is a really long title, but it won't exceed the parent width
</h5>

(forgive the inline styles)

Can overridden methods differ in return type?

Overriding and Return Types, and Covariant Returns
the subclass must define a method that matches the inherited version exactly. Or, as of Java 5, you're allowed to change the return type in the

sample code


                                                                                                            class Alpha {
          Alpha doStuff(char c) {
                  return new Alpha();
              }
           }
             class Beta extends Alpha {
                    Beta doStuff(char c) { // legal override in Java 1.5
                    return new Beta();
                    }
             } } 
As of Java 5, this code will compile. If you were to attempt to compile this code with a 1.4 compiler will say attempting to use incompatible return type – sandeep1987 1 min ago

MySQL: Delete all rows older than 10 minutes

The answer is right in the MYSQL manual itself.

"DELETE FROM `table_name` WHERE `time_col` < ADDDATE(NOW(), INTERVAL -1 HOUR)"

How to create a JavaScript callback for knowing when an image is loaded?

Image.onload() will often work.

To use it, you'll need to be sure to bind the event handler before you set the src attribute.

Related Links:

Example Usage:

_x000D_
_x000D_
    window.onload = function () {_x000D_
_x000D_
        var logo = document.getElementById('sologo');_x000D_
_x000D_
        logo.onload = function () {_x000D_
            alert ("The image has loaded!");  _x000D_
        };_x000D_
_x000D_
        setTimeout(function(){_x000D_
            logo.src = 'https://edmullen.net/test/rc.jpg';         _x000D_
        }, 5000);_x000D_
    };
_x000D_
 <html>_x000D_
    <head>_x000D_
    <title>Image onload()</title>_x000D_
    </head>_x000D_
    <body>_x000D_
_x000D_
    <img src="#" alt="This image is going to load" id="sologo"/>_x000D_
_x000D_
    <script type="text/javascript">_x000D_
_x000D_
    </script>_x000D_
    </body>_x000D_
    </html>
_x000D_
_x000D_
_x000D_

How do I quickly rename a MySQL database (change schema name)?

Simplest bullet-and-fool-proof way of doing a complete rename (including dropping the old database at the end so it's a rename rather than a copy):

mysqladmin -uroot -pmypassword create newdbname
mysqldump -uroot -pmypassword --routines olddbname | mysql -uroot -pmypassword newdbname
mysqladmin -uroot -pmypassword drop olddbname

Steps:

  1. Copy the lines into Notepad.
  2. Replace all references to "olddbname", "newdbname", "mypassword" (+ optionally "root") with your equivalents.
  3. Execute one by one on the command line (entering "y" when prompted).

REACT - toggle class onclick

React has a concept of components state, so if you want to switch it, do a setState:

constructor(props) {
  super(props);

  this.addActiveClass= this.addActiveClass.bind(this);
  this.state = {
    isActive: false
  }
}

addActiveClass() {
  this.setState({
    isActive: true
  })
}

In your component use this.state.isActive to render what you need.

This gets more complicated when you want to set state in component#1 and use it in component#2. Just dig more into react unidirectional data flow and possibly redux that will help you handle it.

How to find top three highest salary in emp table in oracle?

select top(3) min(Name),TotalSalary,ROW_NUMBER() OVER (Order by TotalSalary desc) AS RowNumber FROM tbl_EmployeeProfile group by TotalSalary

Get Wordpress Category from Single Post

<div class="post_category">
        <?php $category = get_the_category();
             $allcategory = get_the_category(); 
        foreach ($allcategory as $category) {
        ?>
           <a class="btn"><?php echo $category->cat_name;; ?></a>
        <?php 
        }
        ?>
 </div>

Perform Button click event when user press Enter key in Textbox

Codeproject has a complete solution for this:

http://www.codeproject.com/Articles/17241/Capturing-the-Enter-key-to-cause-a-button-click

and like the article says: "decide which solution best fits your needs"

=================== EDITED ANSWER ============================

The link mentioned above, talks about two ways of capturing the "Enter Key" event:

Javascript (bind the onKeyPress event to the object and create a javascript function to check which key was pressed and do your logic)

_Page_Load in code behind:_

 //Add the javascript so we know where we want the enter key press to go
if (!IsPostBack)
{
   txtboxFirstName.Attributes.Add("onKeyPress", 
                   "doClick('" + btnSearch.ClientID + "',event)");
   txtboxLastName.Attributes.Add("onKeyPress", 
                  "doClick('" + btnSearch.ClientID + "',event)");
}

Javascript code:

<SCRIPT type=text/javascript>
    function doClick(buttonName,e)
    {
        //the purpose of this function is to allow the enter key to 
        //point to the correct button to click.
        var key;

         if(window.event)
              key = window.event.keyCode;     //IE
         else
              key = e.which;     //firefox

        if (key == 13)
        {
            //Get the button the user wants to have clicked
            var btn = document.getElementById(buttonName);
            if (btn != null)
            { //If we find the button click it
                btn.click();
                event.keyCode = 0
            }
        }
   }
</SCRIPT>

Panel Control

<asp:Panel ID="panSearch" runat="server" DefaultButton="btnSearch2" Width="100%" >
    <asp:TextBox ID="txtboxFirstName2" runat="server" ></asp:TextBox>
</asp:Panel>

Quoting:

Notice that the Panel tag has a property called DefaultButton. You set this property to the button ID of the button you want to be clicked on an Enter key press event. So any text box inside of the Panel will direct its Enter key press to the button set in the DefaultButton property of the Panel

how to get bounding box for div element in jquery

As this is specifically tagged for jQuery -

$("#myElement")[0].getBoundingClientRect();

or

$("#myElement").get(0).getBoundingClientRect();

(These are functionally identical, in some older browsers .get() was slightly faster)

Note that if you try to get the values via jQuery calls then it will not take into account any css transform values, which can give unexpected results...

Note 2: In jQuery 3.0 it has changed to using the proper getBoundingClientRect() calls for its own dimension calls (see the jQuery Core 3.0 Upgrade Guide) - which means that the other jQuery answers will finally always be correct - but only when using the new jQuery version - hence why it's called a breaking change...

What's the purpose of git-mv?

Git is just trying to guess for you what you are trying to do. It is making every attempt to preserve unbroken history. Of course, it is not perfect. So git mv allows you to be explicit with your intention and to avoid some errors.

Consider this example. Starting with an empty repo,

git init
echo "First" >a
echo "Second" >b
git add *
git commit -m "initial commit"
mv a c
mv b a
git status

Result:

# On branch master
# Changes not staged for commit:
#   (use "git add/rm <file>..." to update what will be committed)
#   (use "git checkout -- <file>..." to discard changes in working directory)
#
#   modified:   a
#   deleted:    b
#
# Untracked files:
#   (use "git add <file>..." to include in what will be committed)
#
#   c
no changes added to commit (use "git add" and/or "git commit -a")

Autodetection failed :( Or did it?

$ git add *
$ git commit -m "change"
$ git log c

commit 0c5425be1121c20cc45df04734398dfbac689c39
Author: Sergey Orshanskiy <*****@gmail.com>
Date:   Sat Oct 12 00:24:56 2013 -0400

    change

and then

$ git log --follow c

Author: Sergey Orshanskiy <*****@gmail.com>
Date:   Sat Oct 12 00:24:56 2013 -0400

    change

commit 50c2a4604a27be2a1f4b95399d5e0f96c3dbf70a
Author: Sergey Orshanskiy <*****@gmail.com>
Date:   Sat Oct 12 00:24:45 2013 -0400

    initial commit

Now try instead (remember to delete the .git folder when experimenting):

git init
echo "First" >a
echo "Second" >b
git add *
git commit -m "initial commit"
git mv a c
git status

So far so good:

# On branch master
# Changes to be committed:
#   (use "git reset HEAD <file>..." to unstage)
#
#   renamed:    a -> c


git mv b a
git status

Now, nobody is perfect:

# On branch master
# Changes to be committed:
#   (use "git reset HEAD <file>..." to unstage)
#
#   modified:   a
#   deleted:    b
#   new file:   c
#

Really? But of course...

git add *
git commit -m "change"
git log c
git log --follow c

...and the result is the same as above: only --follow shows the full history.


Now, be careful with renaming, as either option can still produce weird effects. Example:

git init
echo "First" >a
git add a
git commit -m "initial a"
echo "Second" >b
git add b
git commit -m "initial b"

git mv a c
git commit -m "first move"
git mv b a
git commit -m "second move"

git log --follow a

commit 81b80f5690deec1864ebff294f875980216a059d
Author: Sergey Orshanskiy <*****@gmail.com>
Date:   Sat Oct 12 00:35:58 2013 -0400

    second move

commit f284fba9dc8455295b1abdaae9cc6ee941b66e7f
Author: Sergey Orshanskiy <*****@gmail.com>
Date:   Sat Oct 12 00:34:54 2013 -0400

    initial b

Contrast it with:

git init
echo "First" >a
git add a
git commit -m "initial a"
echo "Second" >b
git add b
git commit -m "initial b"

git mv a c
git mv b a
git commit -m "both moves at the same time"

git log --follow a

Result:

commit 84bf29b01f32ea6b746857e0d8401654c4413ecd
Author: Sergey Orshanskiy <*****@gmail.com>
Date:   Sat Oct 12 00:37:13 2013 -0400

    both moves at the same time

commit ec0de3c5358758ffda462913f6e6294731400455
Author: Sergey Orshanskiy <*****@gmail.com>
Date:   Sat Oct 12 00:36:52 2013 -0400

    initial a

Ups... Now the history is going back to initial a instead of initial b, which is wrong. So when we did two moves at a time, Git became confused and did not track the changes properly. By the way, in my experiments the same happened when I deleted/created files instead of using git mv. Proceed with care; you've been warned...

How to switch Python versions in Terminal?

If you have python various versions of python installed,you can launch any of them using pythonx.x.x where x.x.x represents your versions.

Can't specify the 'async' modifier on the 'Main' method of a console app

Haven't needed this much yet, but when I've used console application for Quick tests and required async I've just solved it like this:

class Program
{
    static void Main(string[] args)
    {
        MainAsync(args).Wait();
    }

    static async Task MainAsync(string[] args)
    {
        // Code here
    }
}

How to set host_key_checking=false in ansible inventory file?

You set these configs either in the /etc/ansible/ansible.cfg or ~/.ansible.cfg or ansible.cfg(in your current directory) file

[ssh_connection]
ssh_args = -C -o ControlMaster=auto -o ControlPersist=60s -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no

tested with ansible 2.9.6 in ubuntu 20.04

Get bytes from std::string in C++

std::string::data would seem to be sufficient and most efficient. If you want to have non-const memory to manipulate (strange for encryption) you can copy the data to a buffer using memcpy:

unsigned char buffer[mystring.length()];
memcpy(buffer, mystring.data(), mystring.length());

STL fanboys would encourage you to use std::copy instead:

std::copy(mystring.begin(), mystring.end(), buffer);

but there really isn't much of an upside to this. If you need null termination use std::string::c_str() and the various string duplication techniques others have provided, but I'd generally avoid that and just query for the length. Particularly with cryptography you just know somebody is going to try to break it by shoving nulls in to it, and using std::string::data() discourages you from lazily making assumptions about the underlying bits in the string.

Spring Boot Java Config Set Session Timeout

  • Spring Boot version 1.0: server.session.timeout=1200
  • Spring Boot version 2.0: server.servlet.session.timeout=10m
    NOTE: If a duration suffix is not specified, seconds will be used.

How to remove the querystring and get only the url?

Assuming you still want to get the URL without the query args (if they are not set), just use a shorthand if statement to check with strpos:

$request_uri = strpos( $_SERVER['REQUEST_URI'], '?' ) !== false ? strtok( $_SERVER["REQUEST_URI"], '?' ) : $_SERVER['REQUEST_URI'];

Random / noise functions for GLSL

Just found this version of 3d noise for GPU, alledgedly it is the fastest one available:

#ifndef __noise_hlsl_
#define __noise_hlsl_

// hash based 3d value noise
// function taken from https://www.shadertoy.com/view/XslGRr
// Created by inigo quilez - iq/2013
// License Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License.

// ported from GLSL to HLSL

float hash( float n )
{
    return frac(sin(n)*43758.5453);
}

float noise( float3 x )
{
    // The noise function returns a value in the range -1.0f -> 1.0f

    float3 p = floor(x);
    float3 f = frac(x);

    f       = f*f*(3.0-2.0*f);
    float n = p.x + p.y*57.0 + 113.0*p.z;

    return lerp(lerp(lerp( hash(n+0.0), hash(n+1.0),f.x),
                   lerp( hash(n+57.0), hash(n+58.0),f.x),f.y),
               lerp(lerp( hash(n+113.0), hash(n+114.0),f.x),
                   lerp( hash(n+170.0), hash(n+171.0),f.x),f.y),f.z);
}

#endif

How to get the size of a varchar[n] field in one SQL statement?

This will work on SQL SERVER...

SELECT COL_LENGTH('Table', 'Column')

Alternative to the HTML Bold tag

You can use following :

<p id="p1">Some Text here </p>
#p1{
   font-weight: bold;
}

OR

<Strong><p>Some text here </p></strong>

OR

You can use <h1> tag which is somewhat similar to bold

jquery datatables default sort

use this it works for me: "order": [[ 1, "ASC" ]],

How to add title to seaborn boxplot

For a single boxplot:

import seaborn as sb
sb.boxplot(data=Array).set_title('Title')

For more boxplot in the same plot:

import seaborn as sb
sb.boxplot(data=ArrayofArray).set_title('Title')

e.g.

import seaborn as sb
myarray=[78.195229, 59.104538, 19.884109, 25.941648, 72.234825, 82.313911]
sb.boxplot(data=myarray).set_title('myTitle')

How can I increment a char?

"bad enough not having a traditional for(;;) looper"?? What?

Are you trying to do

import string
for c in string.lowercase:
    ...do something with c...

Or perhaps you're using string.uppercase or string.letters?

Python doesn't have for(;;) because there are often better ways to do it. It also doesn't have character math because it's not necessary, either.

How to send a PUT/DELETE request in jQuery?

From here, you can do this:

/* Extend jQuery with functions for PUT and DELETE requests. */

function _ajax_request(url, data, callback, type, method) {
    if (jQuery.isFunction(data)) {
        callback = data;
        data = {};
    }
    return jQuery.ajax({
        type: method,
        url: url,
        data: data,
        success: callback,
        dataType: type
        });
}

jQuery.extend({
    put: function(url, data, callback, type) {
        return _ajax_request(url, data, callback, type, 'PUT');
    },
    delete_: function(url, data, callback, type) {
        return _ajax_request(url, data, callback, type, 'DELETE');
    }
});

It's basically just a copy of $.post() with the method parameter adapted.

How to get the full url in Express?

var full_address = req.protocol + "://" + req.headers.host + req.originalUrl;

or

var full_address = req.protocol + "://" + req.headers.host + req.baseUrl;

Remove an item from a dictionary when its key is unknown

y={'username':'admin','machine':['a','b','c']}
if 'c' in y['machine'] : del y['machine'][y['machine'].index('c')]

In jQuery, what's the best way of formatting a number to 2 decimal places?

If you're doing this to several fields, or doing it quite often, then perhaps a plugin is the answer.
Here's the beginnings of a jQuery plugin that formats the value of a field to two decimal places.
It is triggered by the onchange event of the field. You may want something different.

<script type="text/javascript">

    // mini jQuery plugin that formats to two decimal places
    (function($) {
        $.fn.currencyFormat = function() {
            this.each( function( i ) {
                $(this).change( function( e ){
                    if( isNaN( parseFloat( this.value ) ) ) return;
                    this.value = parseFloat(this.value).toFixed(2);
                });
            });
            return this; //for chaining
        }
    })( jQuery );

    // apply the currencyFormat behaviour to elements with 'currency' as their class
    $( function() {
        $('.currency').currencyFormat();
    });

</script>   
<input type="text" name="one" class="currency"><br>
<input type="text" name="two" class="currency">

How do I send a file as an email attachment using Linux command line?

the shortest way for me is

file=filename_or_filepath;uuencode $file $file|mail -s "optional subject" email_address

so for your example it'll be

file=your_sql.log;gzip -c $file;uuencode ${file}.gz ${file}|mail -s "file with magnets" [email protected]

the good part is that I can recall it with Ctrl+r to send another file...

Why do we not have a virtual constructor in C++?

  1. When a constructor is invoked, although there is no object created till that point, we still know the kind of object that is gonna be created because the specific constructor of the class to which the object belongs to has already been called.

    Virtual keyword associated with a function means the function of a particular object type is gonna be called.

    So, my thinking says that there is no need to make the virtual constructor because already the desired constructor whose object is gonna be created has been invoked and making constructor virtual is just a redundant thing to do because the object-specific constructor has already been invoked and this is same as calling class-specific function which is achieved through the virtual keyword.

    Although the inner implementation won’t allow virtual constructor for vptr and vtable related reasons.


  1. Another reason is that C++ is a statically typed language and we need to know the type of a variable at compile-time.

    The compiler must be aware of the class type to create the object. The type of object to be created is a compile-time decision.

    If we make the constructor virtual then it means that we don’t need to know the type of the object at compile-time(that’s what virtual function provide. We don’t need to know the actual object and just need the base pointer to point an actual object call the pointed object’s virtual functions without knowing the type of the object) and if we don’t know the type of the object at compile time then it is against the statically typed languages. And hence, run-time polymorphism cannot be achieved.

    Hence, Constructor won’t be called without knowing the type of the object at compile-time. And so the idea of making a virtual constructor fails.

How do search engines deal with AngularJS applications?

Crawlers (or bots) are designed to crawl HTML content of web pages but due to AJAX operations for asynchronous data fetching, this became a problem as it takes sometime to render page and show dynamic content on it. Similarly, AngularJS also use asynchronous model, which creates problem for Google crawlers.

Some developers create basic html pages with real data and serve these pages from server side at the time of crawling. We can render same pages with PhantomJS on serve side which has _escaped_fragment_ (Because Google looks for #! in our site urls and then takes everything after the #! and adds it in _escaped_fragment_ query parameter). For more detail please read this blog .

Remove columns from DataTable in C#

To remove all columns after the one you want, below code should work. It will remove at index 10 (remember Columns are 0 based), until the Column count is 10 or less.

DataTable dt;
int desiredSize = 10;

while (dt.Columns.Count > desiredSize)
{
   dt.Columns.RemoveAt(desiredSize);
}

How can I insert vertical blank space into an html document?

i always use this cheap word for vertical spaces.

    <p>Q1</p>
    <br>
    <p>Q2</p>

SQL Query to add a new column after an existing column in SQL Server 2005

It is a bad idea to select * from anything, period. This is why SSMS adds every field name, even if there are hundreds, instead of select *. It is extremely inefficient regardless of how large the table is. If you don't know what the fields are, its still more efficient to pull them out of the INFORMATION_SCHEMA database than it is to select *.

A better query would be:

SELECT 
 COLUMN_NAME, 
 Case 
  When DATA_TYPE In ('varchar', 'char', 'nchar', 'nvarchar', 'binary') 
  Then convert(varchar(MAX), CHARACTER_MAXIMUM_LENGTH)  
  When DATA_TYPE In ('numeric', 'int', 'smallint', 'bigint', 'tinyint') 
  Then convert(varchar(MAX), NUMERIC_PRECISION) 
  When DATA_TYPE = 'bit' 
  Then convert(varchar(MAX), 1)
  When DATA_TYPE IN ('decimal', 'float') 
  Then convert(varchar(MAX), Concat(Concat(NUMERIC_PRECISION, ', '), NUMERIC_SCALE)) 
  When DATA_TYPE IN ('date', 'datetime', 'smalldatetime', 'time', 'timestamp') 
  Then '' 
 End As DATALEN, 
 DATA_TYPE 
FROM INFORMATION_SCHEMA.COLUMNS 
Where 
 TABLE_NAME = ''

How does numpy.newaxis work and when to use it?

newaxis object in the selection tuple serves to expand the dimensions of the resulting selection by one unit-length dimension.

It is not just conversion of row matrix to column matrix.

Consider the example below:

In [1]:x1 = np.arange(1,10).reshape(3,3)
       print(x1)
Out[1]: array([[1, 2, 3],
               [4, 5, 6],
               [7, 8, 9]])

Now lets add new dimension to our data,

In [2]:x1_new = x1[:,np.newaxis]
       print(x1_new)
Out[2]:array([[[1, 2, 3]],

              [[4, 5, 6]],

              [[7, 8, 9]]])

You can see that newaxis added the extra dimension here, x1 had dimension (3,3) and X1_new has dimension (3,1,3).

How our new dimension enables us to different operations:

In [3]:x2 = np.arange(11,20).reshape(3,3)
       print(x2)
Out[3]:array([[11, 12, 13],
              [14, 15, 16],
              [17, 18, 19]]) 

Adding x1_new and x2, we get:

In [4]:x1_new+x2
Out[4]:array([[[12, 14, 16],
               [15, 17, 19],
               [18, 20, 22]],

              [[15, 17, 19],
               [18, 20, 22],
               [21, 23, 25]],

              [[18, 20, 22],
               [21, 23, 25],
               [24, 26, 28]]])

Thus, newaxis is not just conversion of row to column matrix. It increases the dimension of matrix, thus enabling us to do more operations on it.

Eclipse copy/paste entire line keyboard shortcut

Another shortcut way to do this is press Ctrl+Shift+L and select which command you want to perform and hit enter enter image description here

its best practice for beginner.

Exclude Blank and NA in R

Don't know exactly what kind of dataset you have, so I provide general answer.

x <- c(1,2,NA,3,4,5)
y <- c(1,2,3,NA,6,8)
my.data <- data.frame(x, y)
> my.data
   x  y
1  1  1
2  2  2
3 NA  3
4  3 NA
5  4  6
6  5  8
# Exclude rows with NA values
my.data[complete.cases(my.data),]
  x y
1 1 1
2 2 2
5 4 6
6 5 8

What's the easiest way to call a function every 5 seconds in jQuery?

Just a little tip for the first answer. If your function is already defined, reference the function but don't call it!!! So don't put any parentheses after the function name. Just like:

my_function(){};
setInterval(my_function,10000);

How to show the Project Explorer window in Eclipse

  1. Please Select window in tool bar
  2. Move to show view
  3. Select project explorer

Round number to nearest integer

For this purpose I would suggest just do the following thing -

int(round(x))

This will give you nearest integer.

Hope this helps!!

TypeError: sequence item 0: expected string, int found

Although the given list comprehension / generator expression answers are ok, I find this easier to read and understand:

values = ','.join(map(str, value_list))

Android - set TextView TextStyle programmatically?

So many way to achieve this task some are below:-

1.

String text_view_str = "<b>Bolded text</b>, <i>italic text</i>, even <u>underlined</u>!";
TextView tv = (TextView)findViewById(R.id.ur_text_view_id);
tv.setText(Html.fromHtml(text_view_str));

2.

tv.setTypeface(null, Typeface.BOLD);
tv.setTypeface(null, Typeface.ITALIC);
tv.setTypeface(null, Typeface.BOLD_ITALIC);
tv.setTypeface(null, Typeface.NORMAL);

3.

SpannableString spannablecontent=new SpannableString(o.content.toString());
spannablecontent.setSpan(new StyleSpan(android.graphics.Typeface.BOLD_ITALIC), 
                         0,spannablecontent.length(), 0);
// set Text here
tt.setText(spannablecontent);

4.

<?xml version="1.0" encoding="utf-8"?>
<resources>

    <style name="boldText">
        <item name="android:textStyle">bold|italic</item>
        <item name="android:textColor">#FFFFFF</item>
    </style>

    <style name="normalText">
        <item name="android:textStyle">normal</item>
        <item name="android:textColor">#C0C0C0</item>
    </style>

</resources>

 tv.setTextAppearance(getApplicationContext(), R.style.boldText);

or if u want through xml

android:textStyle="normal"
android:textStyle="normal|bold"
android:textStyle="normal|italic"
android:textStyle="bold"
android:textStyle="bold|italic"

Create a button programmatically and set a background image

Try below:

let image = UIImage(named: "ImageName.png") as UIImage
var button   = UIButton.buttonWithType(UIButtonType.System) as UIButton
button.frame = CGRectMake(100, 100, 100, 100)
button .setBackgroundImage(image, forState: UIControlState.Normal)
button.addTarget(self, action: "Action:", forControlEvents:UIControlEvents.TouchUpInside)
menuView.addSubview(button)

Let me know whether if it works or not?

How to use Session attributes in Spring-mvc

Use @SessionAttributes

See the docs: Using @SessionAttributes to store model attributes in the HTTP session between requests

"Understanding Spring MVC Model And Session Attributes" also gives a very good overview of Spring MVC sessions and explains how/when @ModelAttributes are transferred into the session (if the controller is @SessionAttributes annotated).

That article also explains that it is better to use @SessionAttributes on the model instead of setting attributes directly on the HttpSession because that helps Spring MVC to be view-agnostic.

Converting milliseconds to a date (jQuery/JavaScript)

Assume the date as milliseconds date is 1526813885836, so you can access the date as string with this sample code:

console.log(new Date(1526813885836).toString());

For clearness see below code:

const theTime = new Date(1526813885836);
console.log(theTime.toString());

non static method cannot be referenced from a static context

You are calling nextInt statically by using Random.nextInt.

Instead, create a variable, Random r = new Random(); and then call r.nextInt(10).

It would be definitely worth while to check out:

Update:

You really should replace this line,

Random Random = new Random(); 

with something like this,

Random r = new Random();

If you use variable names as class names you'll run into a boat load of problems. Also as a Java convention, use lowercase names for variables. That might help avoid some confusion.

Cropping images in the browser BEFORE the upload

The Pixastic library does exactly what you want. However, it will only work on browsers that have canvas support. For those older browsers, you'll either need to:

  1. supply a server-side fallback, or
  2. tell the user that you're very sorry, but he'll need to get a more modern browser.

Of course, option #2 isn't very user-friendly. However, if your intent is to provide a pure client-only tool and/or you can't support a fallback back-end cropper (e.g. maybe you're writing a browser extension or offline Chrome app, or maybe you can't afford a decent hosting provider that provides image manipulation libraries), then it's probably fair to limit your user base to modern browsers.

EDIT: If you don't want to learn Pixastic, I have added a very simple cropper on jsFiddle here. It should be possible to modify and integrate and use the drawCroppedImage function with Jcrop.

Determine the type of an object?

For the sake of completeness, isinstance will not work for type checking of a subtype that is not an instance. While that makes perfect sense, none of the answers (including the accepted one) covers it. Use issubclass for that.

>>> class a(list):
...   pass
... 
>>> isinstance(a, list)
False
>>> issubclass(a, list)
True

Get folder name from full file path

Here is an alternative method that worked for me without having to create a DirectoryInfo object. The key point is that GetFileName() works when there is no trailing slash in the path.

var name = Path.GetFileName(path.TrimEnd(Path.DirectorySeparatorChar));

Example:

var list = Directory.EnumerateDirectories(path, "*")
        .Select(p => new
        {
            id = "id_" + p.GetHashCode().ToString("x"),
            text = Path.GetFileName(p.TrimEnd(Path.DirectorySeparatorChar)),
            icon = "fa fa-folder",
            children = true
        })
        .Distinct()
        .OrderBy(p => p.text);

How to get response using cURL in PHP

am using this simple one

´´´´ class Connect {

public $url;
public $path;
public $username;
public $password;

    $ch = curl_init();

    curl_setopt($ch, CURLOPT_URL, $this->url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

    curl_setopt($ch, CURLOPT_USERPWD, "$this->username:$this->password");

    //PROPFIND request that lists all requested properties.
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PROPFIND");
    $response = curl_exec($ch);

    curl_close($ch);

Could not load dynamic library 'cudart64_101.dll' on tensorflow CPU-only installation

Was able to fix the issue by updating NVIDIA device drivers to the latest (v446.14). NVIDIA drivers download link here.

How to resolve : Can not find the tag library descriptor for "http://java.sun.com/jsp/jstl/core"

Add both javax.servlet.jsp.jstl-api-1.2.1.jar and standard-1.1.2.jar

Console app arguments, how arguments are passed to Main method

Command line arguments is one way to pass the arguments in. This msdn sample is worth checking out. The MSDN Page for command line arguments is also worth reading.

From within visual studio you can set the command line arguments by Choosing the properties of your console application then selecting the Debug tab

How to play an android notification sound

Try this:

public void ringtone(){
    try {
        Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        Ringtone r = RingtoneManager.getRingtone(getApplicationContext(), notification);
        r.play();
     } catch (Exception e) {
         e.printStackTrace();
     }
}

Angular JS: Full example of GET/POST/DELETE/PUT client for a REST/CRUD backend?

You can implement this way

$resource('http://localhost\\:3000/realmen/:entryId', {entryId: '@entryId'}, {
        UPDATE: {method: 'PUT', url: 'http://localhost\\:3000/realmen/:entryId' },
        ACTION: {method: 'PUT', url: 'http://localhost\\:3000/realmen/:entryId/action' }
    })

RealMen.query() //GET  /realmen/
RealMen.save({entryId: 1},{post data}) // POST /realmen/1
RealMen.delete({entryId: 1}) //DELETE /realmen/1

//any optional method
RealMen.UPDATE({entryId:1}, {post data}) // PUT /realmen/1

//query string
RealMen.query({name:'john'}) //GET /realmen?name=john

Documentation: https://docs.angularjs.org/api/ngResource/service/$resource

Hope it helps

Byte[] to ASCII

You can use:

System.Text.Encoding.ASCII.GetString(buf);

But sometimes you will get a weird number instead of the string you want. In that case, your original string may have some hexadecimal character when you see it. If it's the case, you may want to try this:

System.Text.Encoding.UTF8.GetString(buf);

Or as a last resort:

System.Text.Encoding.Default.GetString(bytearray);

Column name or number of supplied values does not match table definition

They don't have the same structure... I can guarantee they are different

I know you've already created it... There is already an object named ‘tbltable1’ in the database

What you may want is this (which also fixes your other issue):

Drop table tblTable1

select * into tblTable1 from tblTable1_Link

How to append to the end of an empty list?

append returns None, so at the second iteration you are calling method append of NoneType. Just remove the assignment:

for i in range(0, n):
    list1.append([i])

Efficiently counting the number of lines of a text file. (200mb+)

Simple Oriented Object solution

$file = new \SplFileObject('file.extension');

while($file->valid()) $file->fgets();

var_dump($file->key());

Update

Another way to make this is with PHP_INT_MAX in SplFileObject::seek method.

$file = new \SplFileObject('file.extension', 'r');
$file->seek(PHP_INT_MAX);

echo $file->key() + 1; 

Google Maps Api v3 - find nearest markers

Here is another function that works great for me, returns distance in kilometers:

 function distance(lat1, lng1, lat2, lng2) {
        var radlat1 = Math.PI * lat1 / 180;
        var radlat2 = Math.PI * lat2 / 180;
        var radlon1 = Math.PI * lng1 / 180;
        var radlon2 = Math.PI * lng2 / 180;
        var theta = lng1 - lng2;
        var radtheta = Math.PI * theta / 180;
        var dist = Math.sin(radlat1) * Math.sin(radlat2) + Math.cos(radlat1) * Math.cos(radlat2) * Math.cos(radtheta);
        dist = Math.acos(dist);
        dist = dist * 180 / Math.PI;
        dist = dist * 60 * 1.1515;

        //Get in in kilometers
        dist = dist * 1.609344;

        return dist;
    }

How to reload current page in ReactJS?

You can use window.location.reload(); in your componentDidMount() lifecycle method. If you are using react-router, it has a refresh method to do that.

Edit: If you want to do that after a data update, you might be looking to a re-render not a reload and you can do that by using this.setState(). Here is a basic example of it to fire a re-render after data is fetched.

import React from 'react'

const ROOT_URL = 'https://jsonplaceholder.typicode.com';
const url = `${ROOT_URL}/users`;

class MyComponent extends React.Component {
    state = {
        users: null
    }
    componentDidMount() {
        fetch(url)
            .then(response => response.json())
            .then(users => this.setState({users: users}));
    }
    render() {
        const {users} = this.state;
        if (users) {
            return (
                <ul>
                    {users.map(user => <li>{user.name}</li>)}
                </ul>
            )
        } else {
            return (<h1>Loading ...</h1>)
        }
    }
}

export default MyComponent;

What is a tracking branch?

The Pro Git book mentions:

Tracking branches are local branches that have a direct relationship to a remote branch

Not exactly. The SO question "Having a hard time understanding git-fetch" includes:

There's no such concept of local tracking branches, only remote tracking branches.
So origin/master is a remote tracking branch for master in the origin repo.

But actually, once you establish an upstream branch relationship between:

  • a local branch like master
  • and a remote tracking branch like origin/master

Then you can consider master as a local tracking branch: It tracks the remote tracking branch origin/master which, in turn, tracks the master branch of the upstream repo origin.

alt text

What's the difference between "end" and "exit sub" in VBA?

This is a bit outside the scope of your question, but to avoid any potential confusion for readers who are new to VBA: End and End Sub are not the same. They don't perform the same task.

End puts a stop to ALL code execution and you should almost always use Exit Sub (or Exit Function, respectively).

End halts ALL exectution. While this sounds tempting to do it also clears all global and static variables. (source)

See also the MSDN dox for the End Statement

When executed, the End statement resets allmodule-level variables and all static local variables in allmodules. To preserve the value of these variables, use the Stop statement instead. You can then resume execution while preserving the value of those variables.

Note The End statement stops code execution abruptly, without invoking the Unload, QueryUnload, or Terminate event, or any other Visual Basic code. Code you have placed in the Unload, QueryUnload, and Terminate events offorms andclass modules is not executed. Objects created from class modules are destroyed, files opened using the Open statement are closed, and memory used by your program is freed. Object references held by other programs are invalidated.

Nor is End Sub and Exit Sub the same. End Sub can't be called in the same way Exit Sub can be, because the compiler doesn't allow it.

enter image description here

This again means you have to Exit Sub, which is a perfectly legal operation:

Exit Sub
Immediately exits the Sub procedure in which it appears. Execution continues with the statement following the statement that called the Sub procedure. Exit Sub can be used only inside a Sub procedure.

Additionally, and once you get the feel for how procedures work, obviously, End Sub does not clear any global variables. But it does clear local (Dim'd) variables:

End Sub
Terminates the definition of this procedure.

Passing A List Of Objects Into An MVC Controller Method Using jQuery Ajax

What I did when trying to send some data from several selected rows in DataTable to MVC action:

HTML At the beginning of a page:

@Html.AntiForgeryToken()

(just a row is shown, bind from model):

 @foreach (var item in Model.ListOrderLines)
                {
                    <tr data-orderid="@item.OrderId" data-orderlineid="@item.OrderLineId" data-iscustom="@item.IsCustom">
                        <td>@item.OrderId</td>
                        <td>@item.OrderDate</td>
                        <td>@item.RequestedDeliveryDate</td>
                        <td>@item.ProductName</td>
                        <td>@item.Ident</td>
                        <td>@item.CompanyName</td>
                        <td>@item.DepartmentName</td>
                        <td>@item.ProdAlias</td>
                        <td>@item.ProducerName</td>
                        <td>@item.ProductionInfo</td>
                    </tr>
                }

Button which starts the JavaScript function:

 <button class="btn waves-effect waves-light btn-success" onclick="ProcessMultipleRows();">Start</button>

JavaScript function:

  function ProcessMultipleRows() {
            if ($(".dataTables_scrollBody>tr.selected").length > 0) {
                var list = [];
                $(".dataTables_scrollBody>tr.selected").each(function (e) {
                    var element = $(this);
                    var orderid = element.data("orderid");
                    var iscustom = element.data("iscustom");
                    var orderlineid = element.data("orderlineid");
                    var folderPath = "";
                    var fileName = "";

                    list.push({ orderId: orderid, isCustomOrderLine: iscustom, orderLineId: orderlineid, folderPath: folderPath, fileName : fileName});
                });

                $.ajax({
                    url: '@Url.Action("StartWorkflow","OrderLines")',
                    type: "post", //<------------- this is important
                    data: { model: list }, //<------------- this is important
                    beforeSend: function (xhr) {//<--- This is important
                      xhr.setRequestHeader("RequestVerificationToken",
                      $('input:hidden[name="__RequestVerificationToken"]').val());
                      showPreloader();
                    },
                    success: function (data) {

                    },
                    error: function (XMLHttpRequest, textStatus, errorThrown) {

                    },
                     complete: function () {
                         hidePreloader();
                    }
                });
            }
        }

MVC action:

[HttpPost]
[ValidateAntiForgeryToken] //<--- This is important
public async Task<IActionResult> StartWorkflow(IEnumerable<WorkflowModel> model)

And MODEL in C#:

public class WorkflowModel
 {
        public int OrderId { get; set; }
        public int OrderLineId { get; set; }
        public bool IsCustomOrderLine { get; set; }
        public string FolderPath { get; set; }
        public string FileName { get; set; }
 }

CONCLUSION:

The reason for ERROR:

"Failed to load resource: the server responded with a status of 400 (Bad Request)"

Is attribute: [ValidateAntiForgeryToken] for the MVC action StartWorkflow

Solution in Ajax call:

  beforeSend: function (xhr) {//<--- This is important
                      xhr.setRequestHeader("RequestVerificationToken",
                      $('input:hidden[name="__RequestVerificationToken"]').val());
                    },

To send List of objects you need to form data like in example (populating list object) and:

data: { model: list },

type: "post",

Not connecting to SQL Server over VPN

I also had this problem when trying to connect remotely via the Hamachi VPN. I had tried everything available on the internet (including this post) and it still did not work. Note that everything worked fine when the same database was installed on a machine on my local network. Finally I was able to achieve success using the following fix: on the remote machine, enable the IP address on the TCP/IP protocol, like so:

On the remote machine, start SQL Server Configuration Manager, expand SQL Server Network Configuration, select "Protocols for SQLEXPRESS" (or "MSSQLSERVER"), right-click on TCP/IP, on the resulting dialog box go to the IP Addresses tab, and make sure the "IP1" element is Active=Yes and Enabled=Yes. Make note of the IP address (for me it wasn't necessary to modify these). Then stop and start the SQL Server Services. After that, ensure that the firewall on the remote machine is either disabled, or an exception is allowed for port 1433 that includes both the local subnet and the subnet for the address noted in the previous dialog box. On your local machine you should be able to connect by setting the server name to 192.168.1.22\SQLEXPRESS (or [ip address of remote machine]\[SQL server instance name]).

Hope that helps.

Shared folder between MacOSX and Windows on Virtual Box

Edit

4+ years later after the original reply in 2015, virtualbox.org now offers an official user manual in both html and pdf formats, which effectively deprecates the previous version of this answer:

  • Step 3 (Guest Additions) mentioned in this response as well as several others, is discussed in great detail in manual sections 4.1 and 4.2
  • Step 1 (Shared Folders Setting in VirtualBox Manager) is discussed in section 4.3

Original Answer

Because there isn't an official answer yet and I literally just did this for my OS X/WinXP install, here's what I did:

  1. VirtualBox Manager: Open the Shared Folders setting and click the '+' icon to add a new folder. Then, populate the Folder Path (or use the drop-down to navigate) with the folder you want shared and make sure "Auto-Mount" and "Make Permanent" are checked.
  2. Boot Windows
  3. Once Windows is running, goto the Devices menu (at the top of the VirtualBox Manager window) and select "Insert Guest Additions CD Image...". Cycle through the prompts and once you finish installing, let it reboot.
  4. After Windows reboots, your new drive should show up as a Network Drive in Windows Explorer.

Hope that helps.

document.getElementById().value doesn't set the value

The only case I could imagine is, that you run this on a webkit browser like Chrome or Safari and your return value in responseText, contains a string value.

In that constelation, the value cannot be displayed (it would get blank)

Example: http://jsfiddle.net/BmhNL/2/


My point here is, that I expect a wrong/double encoded string value. Webkit browsers are more strict on the type = number. If there is "only" a white-space issue, you can try to implicitly call the Number() constructor, like

document.getElementById("points").value = +request.responseText;

how to convert current date to YYYY-MM-DD format with angular 2

For Angular 5

app.module.ts

import {DatePipe} from '@angular/common';
.
.
.
providers: [DatePipe]

demo.component.ts

import { DatePipe } from '@angular/common';
.
.
constructor(private datePipe: DatePipe) {}

ngOnInit() {
   var date = new Date();
   console.log(this.datePipe.transform(date,"yyyy-MM-dd")); //output : 2018-02-13
}

more information angular/datePipe

Razor MVC Populating Javascript array with Model Array

JSON syntax is pretty much the JavaScript syntax for coding your object. Therefore, in terms of conciseness and speed, your own answer is the best bet.

I use this approach when populating dropdown lists in my KnockoutJS model. E.g.

var desktopGrpViewModel = {
    availableComputeOfferings: ko.observableArray(@Html.Raw(JsonConvert.SerializeObject(ViewBag.ComputeOfferings))),
    desktopGrpComputeOfferingSelected: ko.observable(),
};
ko.applyBindings(desktopGrpViewModel);

...

<select name="ComputeOffering" class="form-control valid" id="ComputeOffering" data-val="true" 
data-bind="options: availableComputeOffering,
           optionsText: 'Name',
           optionsValue: 'Id',
           value: desktopGrpComputeOfferingSelect,
           optionsCaption: 'Choose...'">
</select>

Note that I'm using Json.NET NuGet package for serialization and the ViewBag to pass data.

Git undo local branch delete

This worked for me:

git fsck --full --no-reflogs --unreachable --lost-found
git show d6e883ff45be514397dcb641c5a914f40b938c86
git branch helpme 15e521b0f716269718bb4e4edc81442a6c11c139

Getting rid of \n when using .readlines()

I used the strip function to get rid of newline character as split lines was throwing memory errors on 4 gb File.

Sample Code:

with open('C:\\aapl.csv','r') as apple:
    for apps in apple.readlines():
        print(apps.strip())

How to use onClick event on react Link component?

I don't believe this is a good pattern to use in general. Link will run your onClick event and then navigate to the route, so there will be a slight delay navigating to the new route. A better strategy is to navigate to the new route with the 'to' prop as you have done, and in the new component's componentDidMount() function you can fire your hello function or any other function. It will give you the same result, but with a much smoother transition between routes.

For context, I noticed this while updating my redux store with an onClick event on Link like you have here, and it caused a ~.3 second blank-white-screen delay before mounting the new route's component. There was no api call involved, so I was surprised the delay was so big. However, if you're just console logging 'hello' the delay might not be noticeable.

'System.Net.Http.HttpContent' does not contain a definition for 'ReadAsAsync' and no extension method

After a long struggle, I found the solution.

Solution: Add a reference to System.Net.Http.Formatting.dll. This assembly is also available in the C:\Program Files\Microsoft ASP.NET\ASP.NET MVC 4\Assemblies folder.

The method ReadAsAsync is an extension method declared in the class HttpContentExtensions, which is in the namespace System.Net.Http in the library System.Net.Http.Formatting.

Reflector came to rescue!

jQuery change input text value

jQuery way to change value on text input field is:

$('#colorpickerField1').attr('value', '#000000')

this will change attribute value for the DOM element with ID #colorpickerField1 from #EEEEEE to #000000

Darken background image on hover

you can use this:

box-shadow: inset 0 0 0 1000px rgba(0,0,0,.2);

as seen on: https://stackoverflow.com/a/24084708/8953378

Difference between UTF-8 and UTF-16?

This is unrelated to UTF-8/16 (in general, although it does convert to UTF16 and the BE/LE part can be set w/ a single line), yet below is the fastest way to convert String to byte[]. For instance: good exactly for the case provided (hash code). String.getBytes(enc) is relatively slow.

static byte[] toBytes(String s){
        byte[] b=new byte[s.length()*2];
        ByteBuffer.wrap(b).asCharBuffer().put(s);
        return b;
    }

Checking for a null object in C++

A C++ reference is not a pointer nor a Java/C# style reference and cannot be NULL. They behave as if they were an alias to another existing object.

In some cases, if there are bugs in your code, you might get a reference into an already dead or non-existent object, but the best thing you can do is hope that the program dies soon enough to be able to debug what happened and why your program got corrupted.

That is, I have seen code checking for 'null references' doing something like: if ( &reference == 0 ), but the standard is clear that there cannot be null references in a well-formed program. If a reference is bound to a null object the program is ill-formed and should be corrected. If you need optional values, use pointers (or some higher level construct like boost::optional), not references.

How to loop over directories in Linux?

find . -mindepth 1 -maxdepth 1 -type d -printf "%P\n"

How to use awk sort by column 3

awk -F "," '{print $0}' user.csv | sort -nk3 -t ','

This should work

How to disable keypad popup when on edittext?

       <TextView android:layout_width="match_parent"
                 android:layout_height="wrap_content"

                 android:focusable="true"
                 android:focusableInTouchMode="true">

                <requestFocus/>
      </TextView>

      <EditText android:layout_width="match_parent"
                android:layout_height="wrap_content"/>

curl: (35) error:1408F10B:SSL routines:ssl3_get_record:wrong version number

* Uses proxy env variable http_proxy == 'https://proxy.in.tum.de:8080'   
                                         ^^^^^

The https:// is wrong, it should be http://. The proxy itself should be accessed by HTTP and not HTTPS even though the target URL is HTTPS. The proxy will nevertheless properly handle HTTPS connection and keep the end-to-end encryption. See HTTP CONNECT method for details how this is done.

What is the correct way to start a mongod service on linux / OS X?

First Step

install mongodb in your linux machine with

apt install mongodb-client && apt install mongodb-server

second step is

change the database path instead of your system default path if you want.
so do the following steps and change it for yourself.

mongod --directoryperdb --dbpath /var/lib/mongodb/data/db --logpath /var/lib/mongodb/log/mongodb.log --logappend --rest

and in your windows machine do it just like that just put an --install flag. you have to get a successful message.

Best Regards...

handle textview link click in my android app

Here is a more generic solution based on @Arun answer

public abstract class TextViewLinkHandler extends LinkMovementMethod {

    public boolean onTouchEvent(TextView widget, Spannable buffer, MotionEvent event) {
        if (event.getAction() != MotionEvent.ACTION_UP)
            return super.onTouchEvent(widget, buffer, event);

        int x = (int) event.getX();
        int y = (int) event.getY();

        x -= widget.getTotalPaddingLeft();
        y -= widget.getTotalPaddingTop();

        x += widget.getScrollX();
        y += widget.getScrollY();

        Layout layout = widget.getLayout();
        int line = layout.getLineForVertical(y);
        int off = layout.getOffsetForHorizontal(line, x);

        URLSpan[] link = buffer.getSpans(off, off, URLSpan.class);
        if (link.length != 0) {
            onLinkClick(link[0].getURL());
        }
        return true;
    }

    abstract public void onLinkClick(String url);
}

To use it just implement onLinkClick of TextViewLinkHandler class. For instance:

    textView.setMovementMethod(new TextViewLinkHandler() {
        @Override
        public void onLinkClick(String url) {
            Toast.makeText(textView.getContext(), url, Toast.LENGTH_SHORT).show();
        }
    });

Cannot access a disposed object - How to fix?

Another place you could stop the timer is the FormClosing event - this happens before the form is actually closed, so is a good place to stop things before they might access unavailable resources.

Get the current displaying UIViewController on the screen in AppDelegate.m

You could also post a notification via NSNotificationCenter. This let's you deal with a number of situations where traversing the view controller hierarchy might be tricky - for example when modals are being presented, etc.

E.g.,

// MyAppDelegate.h
NSString * const UIApplicationDidReceiveRemoteNotification;

// MyAppDelegate.m
NSString * const UIApplicationDidReceiveRemoteNotification = @"UIApplicationDidReceiveRemoteNotification";

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {

    [[NSNotificationCenter defaultCenter]
     postNotificationName:UIApplicationDidReceiveRemoteNotification
     object:self
     userInfo:userInfo];
}

In each of your View Controllers:

-(void)viewDidLoad {
    [[NSNotificationCenter defaultCenter] 
      addObserver:self
      selector:@selector(didReceiveRemoteNotification:)                                                  
      name:UIApplicationDidReceiveRemoteNotification
      object:nil];
}

-(void)viewDidUnload {
    [[NSNotificationCenter defaultCenter] 
      removeObserver:self
      name:UIApplicationDidReceiveRemoteNotification
      object:nil];
}

-(void)didReceiveRemoteNotification:(NSDictionary *)userInfo {
    // see http://stackoverflow.com/a/2777460/305149
   if (self.isViewLoaded && self.view.window) {
      // handle the notification
   }
}

You could also use this approach to instrument controls which need to update when a notification is received and are used by several view controllers. In that case, handle the add/remove observer calls in the init and dealloc methods, respectively.

Where do I find old versions of Android NDK?

http://dl.google.com/android/ndk/android-ndk-r9d-linux-x86_64.tar.bz2

I successfully opened gstreamer SDK tutorials in Eclipse.

All I needed is to use an older version of ndk. specificly 9d.

(10c and 10d does not work, 10b - works just for tutorial-1 )

9d does work for all tutorials ! and you can:

  1. Download it from: http://dl.google.com/android/ndk/android-ndk-r9d-linux-x86_64.tar.bz2

  2. Extract it.

  3. set it in eclipse->window->preferences->Android->NDK->NDK location.

  4. build - (ctrl+b).

The object 'DF__*' is dependent on column '*' - Changing int to double

Try this:

Remove the constraint DF_Movies_Rating__48CFD27E before changing your field type.

The constraint is typically created automatically by the DBMS (SQL Server).

To see the constraint associated with the table, expand the table attributes in Object explorer, followed by the category Constraints as shown below:

Tree of your table

You must remove the constraint before changing the field type.

how to iterate through dictionary in a dictionary in django template?

If you pass a variable data (dictionary type) as context to a template, then you code should be:

{% for key, value in data.items %}
    <p>{{ key }} : {{ value }}</p> 
{% endfor %}

How to draw border on just one side of a linear layout?

To get a border on just one side of a drawable, apply a negative inset to the other 3 sides (causing those borders to be drawn off-screen).

<?xml version="1.0" encoding="utf-8"?>
<inset xmlns:android="http://schemas.android.com/apk/res/android"
    android:insetTop="-2dp" 
    android:insetBottom="-2dp"
    android:insetLeft="-2dp">

    <shape android:shape="rectangle">
        <stroke android:width="2dp" android:color="#FF0000" />
        <solid android:color="#000000" />
    </shape>

</inset>

enter image description here

This approach is similar to naykah's answer, but without the use of a layer-list.

Getting or changing CSS class property with Javascript using DOM style

If you are looking for sending color data from backend

def color():
    color = "#{:06x}".format(random.randint(0, 0xFFFFFF))
    return color

css display table cell requires percentage width

You just need to add 'table-layout: fixed;'

.table {
   display: table;
   height: 100px;
   width: 100%;
   table-layout: fixed;
}

http://www.w3schools.com/cssref/pr_tab_table-layout.asp

How do you find the current user in a Windows environment?

You can use the username variable: %USERNAME%

RequestDispatcher.forward() vs HttpServletResponse.sendRedirect()

In the web development world, the term "redirect" is the act of sending the client an empty HTTP response with just a Location header containing the new URL to which the client has to send a brand new GET request. So basically:

  • Client sends a HTTP request to some.jsp.
  • Server sends a HTTP response back with Location: other.jsp header
  • Client sends a HTTP request to other.jsp (this get reflected in browser address bar!)
  • Server sends a HTTP response back with content of other.jsp.

You can track it with the web browser's builtin/addon developer toolset. Press F12 in Chrome/IE9/Firebug and check the "Network" section to see it.

Exactly the above is achieved by sendRedirect("other.jsp"). The RequestDispatcher#forward() doesn't send a redirect. Instead, it uses the content of the target page as HTTP response.

  • Client sends a HTTP request to some.jsp.
  • Server sends a HTTP response back with content of other.jsp.

However, as the original HTTP request was to some.jsp, the URL in browser address bar remains unchanged. Also, any request attributes set in the controller behind some.jsp will be available in other.jsp. This does not happen during a redirect because you're basically forcing the client to create a new HTTP request on other.jsp, hereby throwing away the original request on some.jsp including all of its attribtues.


The RequestDispatcher is extremely useful in the MVC paradigm and/or when you want to hide JSP's from direct access. You can put JSP's in the /WEB-INF folder and use a Servlet which controls, preprocesses and postprocesses the requests. The JSPs in the /WEB-INF folder are not directly accessible by URL, but the Servlet can access them using RequestDispatcher#forward().

You can for example have a JSP file in /WEB-INF/login.jsp and a LoginServlet which is mapped on an url-pattern of /login. When you invoke http://example.com/context/login, then the servlet's doGet() will be invoked. You can do any preprocessing stuff in there and finally forward the request like:

request.getRequestDispatcher("/WEB-INF/login.jsp").forward(request, response);

When you submit a form, you normally want to use POST:

<form action="login" method="post">

This way the servlet's doPost() will be invoked and you can do any postprocessing stuff in there (e.g. validation, business logic, login the user, etc).

If there are any errors, then you normally want to forward the request back to the same page and display the errors there next to the input fields and so on. You can use the RequestDispatcher for this.

If a POST is successful, you normally want to redirect the request, so that the request won't be resubmitted when the user refreshes the request (e.g. pressing F5 or navigating back in history).

User user = userDAO.find(username, password);
if (user != null) {
    request.getSession().setAttribute("user", user); // Login user.
    response.sendRedirect("home"); // Redirects to http://example.com/context/home after succesful login.
} else {
    request.setAttribute("error", "Unknown login, please try again."); // Set error.
    request.getRequestDispatcher("/WEB-INF/login.jsp").forward(request, response); // Forward to same page so that you can display error.
}

A redirect thus instructs the client to fire a new GET request on the given URL. Refreshing the request would then only refresh the redirected request and not the initial request. This will avoid "double submits" and confusion and bad user experiences. This is also called the POST-Redirect-GET pattern.

See also:

How to add results of two select commands in same query

Yes. It is possible :D

SELECT  SUM(totalHours) totalHours
FROM
        ( 
            select sum(hours) totalHours from resource
            UNION ALL
            select sum(hours) totalHours from projects-time
        ) s

As a sidenote, the tablename projects-time must be delimited to avoid syntax error. Delimiter symbols vary on RDBMS you are using.

Django Reverse with arguments '()' and keyword arguments '{}' not found

You have to specify project_id:

reverse('edit_project', kwargs={'project_id':4})

Doc here

Using C# to read/write Excel files (.xls/.xlsx)

**Reading the Excel File:**

string filePath = @"d:\MyExcel.xlsx";
Excel.Application xlApp = new Excel.Application();  
Excel.Workbook xlWorkBook = xlApp.Workbooks.Open(filePath);  
Excel.Worksheet xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);  

Excel.Range xlRange = xlWorkSheet.UsedRange;  
int totalRows = xlRange.Rows.Count;  
int totalColumns = xlRange.Columns.Count;  

string firstValue, secondValue;   
for (int rowCount = 1; rowCount <= totalRows; rowCount++)  
{  
    firstValue = Convert.ToString((xlRange.Cells[rowCount, 1] as Excel.Range).Text);  
    secondValue = Convert.ToString((xlRange.Cells[rowCount, 2] as Excel.Range).Text);  
    Console.WriteLine(firstValue + "\t" + secondValue);  
}  
xlWorkBook.Close();  
xlApp.Quit(); 


**Writting the Excel File:**

Excel.Application xlApp = new Excel.Application();
object misValue = System.Reflection.Missing.Value;  

Excel.Workbook xlWorkBook = xlApp.Workbooks.Add(misValue);  
Excel.Worksheet xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);  

xlWorkSheet.Cells[1, 1] = "ID";  
xlWorkSheet.Cells[1, 2] = "Name";  
xlWorkSheet.Cells[2, 1] = "100";  
xlWorkSheet.Cells[2, 2] = "John";  
xlWorkSheet.Cells[3, 1] = "101";  
xlWorkSheet.Cells[3, 2] = "Herry";  

xlWorkBook.SaveAs(filePath, Excel.XlFileFormat.xlOpenXMLWorkbook, misValue, misValue, misValue, misValue,  
Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);  



xlWorkBook.Close();  
xlApp.Quit();  

Input size vs width

I just got through fighting with a table that I couldn't make any smaller no matter which element I tried to make smaller the width of the table stayed the same. I searched using firebug but couldn't find the element that was setting the width so high.

Finally I tried changing the size attribute of the input text elements and that fixed it. For some reason the size attribute over-rode the css widths. I was using jQuery to dynamically add rows to a table and it was these rows that contained the inputs. So perhaps when it comes to dynamically adding inputs using the appendTo() function maybe it is better to set the size attribute along with the width.

import error: 'No module named' *does* exist

My usual trick is to simply print sys.path in the actual context where the import problem happens. In your case it'd seem that the place for the print is in /home/hughdbrown/.local/bin/pserve . Then check dirs & files in the places that path shows..

You do that by first having:

import sys

and in python 2 with print expression:

print sys.path

or in python 3 with the print function:

print(sys.path)

How to convert NSDate into unix timestamp iphone sdk?

- (void)GetCurrentTimeStamp
    {
        NSDateFormatter *objDateformat = [[NSDateFormatter alloc] init];
        [objDateformat setDateFormat:@"yyyy-MM-dd"];
        NSString    *strTime = [objDateformat stringFromDate:[NSDate date]];
        NSString    *strUTCTime = [self GetUTCDateTimeFromLocalTime:strTime];//You can pass your date but be carefull about your date format of NSDateFormatter.
        NSDate *objUTCDate  = [objDateformat dateFromString:strUTCTime];
        long long milliseconds = (long long)([objUTCDate timeIntervalSince1970] * 1000.0);

        NSString *strTimeStamp = [Nsstring stringwithformat:@"%lld",milliseconds];
        NSLog(@"The Timestamp is = %@",strTimestamp);
    }

 - (NSString *) GetUTCDateTimeFromLocalTime:(NSString *)IN_strLocalTime
    {
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        [dateFormatter setDateFormat:@"yyyy-MM-dd"];
        NSDate  *objDate    = [dateFormatter dateFromString:IN_strLocalTime];
        [dateFormatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC"]];
        NSString *strDateTime   = [dateFormatter stringFromDate:objDate];
        return strDateTime;
    }

NOTE :- The Timestamp must be in UTC Zone, So I convert our local Time to UTC Time.

update listview dynamically with adapter

SimpleListAdapter's are primarily used for static data! If you want to handle dynamic data, you're better off working with an ArrayAdapter, ListAdapter or with a CursorAdapter if your data is coming in from the database.

Here's a useful tutorial in understanding binding data in a ListAdapter

As referenced in this SO question

Set the Value of a Hidden field using JQuery

The selector should not be #input. That means a field with id="input" which is not your case. You want:

$('#chag_sort').val(sort2);

Or if your hidden input didn't have an unique id but only a name="chag_sort":

$('input[name="chag_sort"]').val(sort2);

Change window location Jquery

If you want to use the back button, check this out. https://stackoverflow.com/questions/116446/what-is-the-best-back-button-jquery-plugin

Use document.location.href to change the page location, place it in the function on a successful ajax run.

javascript, for loop defines a dynamic variable name

I think you could do it by creating parameters in an object maybe?

var myObject = {}; for(var i=0;i<myArray.length;i++) {     myObject[ myArray[i] ]; } 

If you don't set them to anything, you'll just have an object with some parameters that are undefined. I'd have to write this myself to be sure though.

shift a std_logic_vector of n bit to right or left

I would not suggest to use sll or srl with std_logic_vector.

During simulation sll gave me 'U' value for those bits, where I expected 0's.

Use shift_left(), shift_right() functions.

For example:

OP1 : in std_logic_vector(7 downto 0); signal accum: std_logic_vector(7 downto 0);

accum <= std_logic_vector(shift_left(unsigned(accum), to_integer(unsigned(OP1)))); accum <= std_logic_vector(shift_right(unsigned(accum), to_integer(unsigned(OP1))));

CSS blur on background image but not on content

backdrop-filter

Unfortunately Mozilla has really dropped the ball and taken it's time with the feature. I'm personally hoping it makes it in to the next Firefox ESR as that is what the next major version of Waterfox will use.

MDN (Mozilla Developer Network) article: https://developer.mozilla.org/en-US/docs/Web/CSS/backdrop-filter

Mozilla implementation: https://bugzilla.mozilla.org/show_bug.cgi?id=1178765

From the MDN documentation page:

/* URL to SVG filter */
backdrop-filter: url(commonfilters.svg#filter);

/* <filter-function> values */
backdrop-filter: blur(2px);
backdrop-filter: brightness(60%);
backdrop-filter: contrast(40%);
backdrop-filter: drop-shadow(4px 4px 10px blue);
backdrop-filter: grayscale(30%);
backdrop-filter: hue-rotate(120deg);
backdrop-filter: invert(70%);
backdrop-filter: opacity(20%);
backdrop-filter: sepia(90%);
backdrop-filter: saturate(80%);

/* Multiple filters */
backdrop-filter: url(filters.svg#filter) blur(4px) saturate(150%);

Compression/Decompression string with C#

I like @fubo's answer the best but I think this is much more elegant.

This method is more compatible because it doesn't manually store the length up front.

Also I've exposed extensions to support compression for string to string, byte[] to byte[], and Stream to Stream.

public static class ZipExtensions
{
    public static string CompressToBase64(this string data)
    {
        return Convert.ToBase64String(Encoding.UTF8.GetBytes(data).Compress());
    }

    public static string DecompressFromBase64(this string data)
    {
        return Encoding.UTF8.GetString(Convert.FromBase64String(data).Decompress());
    }
    
    public static byte[] Compress(this byte[] data)
    {
        using (var sourceStream = new MemoryStream(data))
        using (var destinationStream = new MemoryStream())
        {
            sourceStream.CompressTo(destinationStream);
            return destinationStream.ToArray();
        }
    }

    public static byte[] Decompress(this byte[] data)
    {
        using (var sourceStream = new MemoryStream(data))
        using (var destinationStream = new MemoryStream())
        {
            sourceStream.DecompressTo(destinationStream);
            return destinationStream.ToArray();
        }
    }
    
    public static void CompressTo(this Stream stream, Stream outputStream)
    {
        using (var gZipStream = new GZipStream(outputStream, CompressionMode.Compress))
        {
            stream.CopyTo(gZipStream);
            gZipStream.Flush();
        }
    }

    public static void DecompressTo(this Stream stream, Stream outputStream)
    {
        using (var gZipStream = new GZipStream(stream, CompressionMode.Decompress))
        {
            gZipStream.CopyTo(outputStream);
        }
    }
}

T-SQL datetime rounded to nearest minute and nearest hours with using functions

I realize this question is ancient and there is an accepted and an alternate answer. I also realize that my answer will only answer half of the question, but for anyone wanting to round to the nearest minute and still have a datetime compatible value using only a single function:

CAST(YourValueHere as smalldatetime);

For hours or seconds, use Jeff Ogata's answer (the accepted answer) above.

Rename specific column(s) in pandas

A much faster implementation would be to use list-comprehension if you need to rename a single column.

df.columns = ['log(gdp)' if x=='gdp' else x for x in df.columns]

If the need arises to rename multiple columns, either use conditional expressions like:

df.columns = ['log(gdp)' if x=='gdp' else 'cap_mod' if x=='cap' else x for x in df.columns]

Or, construct a mapping using a dictionary and perform the list-comprehension with it's get operation by setting default value as the old name:

col_dict = {'gdp': 'log(gdp)', 'cap': 'cap_mod'}   ## key?old name, value?new name

df.columns = [col_dict.get(x, x) for x in df.columns]

Timings:

%%timeit
df.rename(columns={'gdp':'log(gdp)'}, inplace=True)
10000 loops, best of 3: 168 µs per loop

%%timeit
df.columns = ['log(gdp)' if x=='gdp' else x for x in df.columns]
10000 loops, best of 3: 58.5 µs per loop

How to get a password from a shell script without echoing

I found to be the the askpass command useful

password=$(/lib/cryptsetup/askpass "Give a password")

Every input character is replaced by *. See: Give a password ****

Verify if file exists or not in C#

Can't comment yet, but I just wanted to disagree/clarify with erikkallen.

You should not just catch the exception in the situation you've described. If you KNEW that the file should be there and due to some exceptional case, it wasn't, then it would be acceptable to just attempt to access the file and catch any exception that occurs.

In this case, however, you are receiving input from a user and have little reason to believe that the file exists. Here you should always use File.Exists().

I know it is cliché, but you should only use Exceptions for an exceptional event, not as part as the normal flow of your application. It is expensive and makes code more difficult to read/follow.

Traits vs. interfaces

The main difference is that, with interfaces, you must define the actual implementation of each method within each class that implements said interface, so you can have many classes implement the same interface but with different behavior, while traits are just chunks of code injected in a class; another important difference is that trait methods can only be class-methods or static-methods, unlike interface methods which can also (and usually are) be instance methods.

List attributes of an object

>>> class new_class():
...   def __init__(self, number):
...     self.multi = int(number) * 2
...     self.str = str(number)
... 
>>> a = new_class(2)
>>> a.__dict__
{'multi': 4, 'str': '2'}
>>> a.__dict__.keys()
dict_keys(['multi', 'str'])

You may also find pprint helpful.

Right align text in android TextView

If it is in RelativeLayout you can use android:layout_toRightOf="@id/<id_of_desired_item>"

Or

If you want to align to the right corner of the device the place android:layout_alignParentRight="true"

How to get the sizes of the tables of a MySQL database?

  • Size of all tables:

    Suppose your database or TABLE_SCHEMA name is "news_alert". Then this query will show the size of all tables in the database.

    SELECT
      TABLE_NAME AS `Table`,
      ROUND(((DATA_LENGTH + INDEX_LENGTH) / 1024 / 1024),2) AS `Size (MB)`
    FROM
      information_schema.TABLES
    WHERE
      TABLE_SCHEMA = "news_alert"
    ORDER BY
      (DATA_LENGTH + INDEX_LENGTH)
    DESC;
    

    Output:

        +---------+-----------+
        | Table   | Size (MB) |
        +---------+-----------+
        | news    |      0.08 |
        | keyword |      0.02 |
        +---------+-----------+
        2 rows in set (0.00 sec)
    
  • For the specific table:

    Suppose your TABLE_NAME is "news". Then SQL query will be-

    SELECT
      TABLE_NAME AS `Table`,
      ROUND(((DATA_LENGTH + INDEX_LENGTH) / 1024 / 1024),2) AS `Size (MB)`
    FROM
      information_schema.TABLES
    WHERE
        TABLE_SCHEMA = "news_alert"
      AND
        TABLE_NAME = "news"
    ORDER BY
      (DATA_LENGTH + INDEX_LENGTH)
    DESC;
    

    Output:

    +-------+-----------+
    | Table | Size (MB) |
    +-------+-----------+
    | news  |      0.08 |
    +-------+-----------+
    1 row in set (0.00 sec)
    

What is the max size of localStorage values?

Find the maximum length of a single string that can be stored in localStorage

This snippet will find the maximum length of a String that can be stored in localStorage per domain.

//Clear localStorage
for (var item in localStorage) delete localStorage[item];

window.result = window.result || document.getElementById('result');

result.textContent = 'Test running…';

//Start test
//Defer running so DOM can be updated with "test running" message
setTimeout(function () {

    //Variables
    var low = 0,
        high = 2e9,
        half;

    //Two billion may be a little low as a starting point, so increase if necessary
    while (canStore(high)) high *= 2;


    //Keep refining until low and high are equal
    while (low !== high) {
        half = Math.floor((high - low) / 2 + low);

        //Check if we can't scale down any further
        if (low === half || high === half) {
            console.info(low, high, half);
            //Set low to the maximum possible amount that can be stored 
            low = canStore(high) ? high : low;
            high = low;
            break;
        }


        //Check if the maximum storage is no higher than half
        if (storageMaxBetween(low, half)) {
            high = half;
            //The only other possibility is that it's higher than half but not higher than "high"
        } else {
            low = half + 1;
        }

    }

    //Show the result we found!
    result.innerHTML = 'The maximum length of a string that can be stored in localStorage is <strong>' + low + '</strong> characters.';

    //Functions
    function canStore(strLen) {
        try {
            delete localStorage.foo;
            localStorage.foo = Array(strLen + 1).join('A');
            return true;
        } catch (ex) {
            return false;
        }
    }


    function storageMaxBetween(low, high) {
        return canStore(low) && !canStore(high);
    }

}, 0);
<h1>LocalStorage single value max length test</h1>

<div id='result'>Please enable JavaScript</div>

Note that the length of a string is limited in JavaScript; if you want to view the maximum amount of data that can be stored in localStorage when not limited to a single string, you can use the code in this answer.

Edit: Stack Snippets don't support localStorage, so here is a link to JSFiddle.

Results

Chrome (45.0.2454.101): 5242878 characters
Firefox (40.0.1): 5242883 characters
Internet Explorer (11.0.9600.18036): 16386 122066 122070 characters

I get different results on each run in Internet Explorer.

final keyword in method parameters

final keyword in the method input parameter is not needed. Java creates a copy of the reference to the object, so putting final on it doesn't make the object final but just the reference, which doesn't make sense

JAVA_HOME is set to an invalid directory:

You should set it with C:\Program Files\Java\jdk1.8.0_12.

\bin is not required.

Customize the Authorization HTTP header

Kindly try below on postman :-

In header section example work for me..

Authorization : JWT eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyIkX18iOnsic3RyaWN0TW9kZSI6dHJ1ZSwiZ2V0dGVycyI6e30sIndhc1BvcHVsYXRlZCI6ZmFsc2UsImFjdGl2ZVBhdGhzIjp7InBhdGhzIjp7InBhc3N3b3JkIjoiaW5pdCIsImVtYWlsIjoiaW5pdCIsIl9fdiI6ImluaXQiLCJfaWQiOiJpbml0In0sInN0YXRlcyI6eyJpZ25vcmUiOnt9LCJkZWZhdWx0Ijp7fSwiaW5pdCI6eyJfX3YiOnRydWUsInBhc3N3b3JkIjp0cnVlLCJlbWFpbCI6dHJ1ZSwiX2lkIjp0cnVlfSwibW9kaWZ5Ijp7fSwicmVxdWlyZSI6e319LCJzdGF0ZU5hbWVzIjpbInJlcXVpcmUiLCJtb2RpZnkiLCJpbml0IiwiZGVmYXVsdCIsImlnbm9yZSJdfSwiZW1pdHRlciI6eyJkb21haW4iOm51bGwsIl9ldmVudHMiOnt9LCJfZXZlbnRzQ291bnQiOjAsIl9tYXhMaXN0ZW5lcnMiOjB9fSwiaXNOZXciOmZhbHNlLCJfZG9jIjp7Il9fdiI6MCwicGFzc3dvcmQiOiIkMmEkMTAkdTAybWNnWHFjWVQvdE41MlkzZ2l3dVROd3ZMWW9ZTlFXejlUcThyaDIwR09IMlhHY3haZWUiLCJlbWFpbCI6Im1hZGFuLmRhbGUxQGdtYWlsLmNvbSIsIl9pZCI6IjU5MjEzYzYyYWM2ODZlMGMyNzI2MjgzMiJ9LCJfcHJlcyI6eyIkX19vcmlnaW5hbF9zYXZlIjpbbnVsbCxudWxsLG51bGxdLCIkX19vcmlnaW5hbF92YWxpZGF0ZSI6W251bGxdLCIkX19vcmlnaW5hbF9yZW1vdmUiOltudWxsXX0sIl9wb3N0cyI6eyIkX19vcmlnaW5hbF9zYXZlIjpbXSwiJF9fb3JpZ2luYWxfdmFsaWRhdGUiOltdLCIkX19vcmlnaW5hbF9yZW1vdmUiOltdfSwiaWF0IjoxNDk1MzUwNzA5LCJleHAiOjE0OTUzNjA3ODl9.BkyB0LjKB4FIsCtnM5FcpcBLvKed_j7rCCxZddwiYnU

Console.log(); How to & Debugging javascript

console.log() just takes whatever you pass to it and writes it to a console's log window. If you pass in an array, you'll be able to inspect the array's contents. Pass in an object, you can examine the object's attributes/methods. pass in a string, it'll log the string. Basically it's "document.write" but can intelligently take apart its arguments and write them out elsewhere.

It's useful to outputting occasional debugging information, but not particularly useful if you have a massive amount of debugging output.

To watch as a script's executing, you'd use a debugger instead, which allows you step through the code line-by-line. console.log's used when you need to display what some variable's contents were for later inspection, but do not want to interrupt execution.

How to get address location from latitude and longitude in Google Map.?

You have to make one ajax call to get the required result, in this case you can use Google API to get the same

http://maps.googleapis.com/maps/api/geocode/json?latlng=40.714224,-73.961452&sensor=true/false

Build this kind of url and replace the lat long with the one you want to. do the call and response will be in JSON, parse the JSON and you will get the complete address up to street level

Python loop for inside lambda

anon and chepner's answers are on the right track. Python 3.x has a print function and this is what you will need if you want to embed print within a function (and, a fortiori, lambdas).

However, you can get the print function very easily in python 2.x by importing from the standard library's future module. Check it out:

>>>from __future__ import print_function
>>>
>>>iterable = ["a","b","c"]
>>>map(print, iterable)
a
b
c
[None, None, None]
>>>

I guess that looks kind of weird, so feel free to assign the return to _ if you would like to suppress [None, None, None]'s output (you are interested in the side-effects only, I assume):

>>>_ = map(print, iterable)
a
b
c
>>>

Centos/Linux setting logrotate to maximum file size for all logs

As mentioned by Zeeshan, the logrotate options size, minsize, maxsize are triggers for rotation.

To better explain it. You can run logrotate as often as you like, but unless a threshold is reached such as the filesize being reached or the appropriate time passed, the logs will not be rotated.

The size options do not ensure that your rotated logs are also of the specified size. To get them to be close to the specified size you need to call the logrotate program sufficiently often. This is critical.

For log files that build up very quickly (e.g. in the hundreds of MB a day), unless you want them to be very large you will need to ensure logrotate is called often! this is critical.

Therefore to stop your disk filling up with multi-gigabyte log files you need to ensure logrotate is called often enough, otherwise the log rotation will not work as well as you want.

on Ubuntu, you can easily switch to hourly rotation by moving the script /etc/cron.daily/logrotate to /etc/cron.hourly/logrotate

Or add

*/5 * * * * /etc/cron.daily/logrotate 

To your /etc/crontab file. To run it every 5 minutes.

The size option ignores the daily, weekly, monthly time options. But minsize & maxsize take it into account.

The man page is a little confusing there. Here's my explanation.

minsize rotates only when the file has reached an appropriate size and the set time period has passed. e.g. minsize 50MB + daily If file reaches 50MB before daily time ticked over, it'll keep growing until the next day.

maxsize will rotate when the log reaches a set size or the appropriate time has passed. e.g. maxsize 50MB + daily. If file is 50MB and we're not at the next day yet, the log will be rotated. If the file is only 20MB and we roll over to the next day then the file will be rotated.

size will rotate when the log > size. Regardless of whether hourly/daily/weekly/monthly is specified. So if you have size 100M - it means when your log file is > 100M the log will be rotated if logrotate is run when this condition is true. Once it's rotated, the main log will be 0, and a subsequent run will do nothing.

So in the op's case. Specficially 50MB max I'd use something like the following:

/var/log/logpath/*.log {
    maxsize 50M
    hourly
    missingok
    rotate 8
    compress
    notifempty
    nocreate
}

Which means he'd create 8hrs of logs max. And there would be 8 of them at no more than 50MB each. Since he's saying that he's getting multi gigabytes each day and assuming they build up at a fairly constant rate, and maxsize is used he'll end up with around close to the max reached for each file. So they will be likely close to 50MB each. Given the volume they build, he would need to ensure that logrotate is run often enough to meet the target size.

Since I've put hourly there, we'd need logrotate to be run a minimum of every hour. But since they build up to say 2 gigabytes per day and we want 50MB... assuming a constant rate that's 83MB per hour. So you can imagine if we run logrotate every hour, despite setting maxsize to 50 we'll end up with 83MB log's in that case. So in this instance set the running to every 30 minutes or less should be sufficient.

Ensure logrotate is run every 30 mins.

*/30 * * * * /etc/cron.daily/logrotate 

Getting Chrome to accept self-signed localhost certificate

If you're on a mac and not seeing the export tab or how to get the certificate this worked for me:

  1. Click the lock before the https://
  2. Go to the "Connection" tab
  3. Click "Certificate Information"

    Now you should see this: Different information of course and yours should be marked as trusted yet (otherwise      you probably wouldn't be here)

  4. Drag that little certificate icon do your desktop (or anywhere).

  5. Double click the .cer file that was downloaded, this should import it into your keychain and open Keychain Access to your list of certificates.

    In some cases, this is enough and you can now refresh the page.

    Otherwise:

  6. Double click the newly added certificate.
  7. Under the trust drop down change the "When using this certificate" option to "Always Trust"

Now reload the page in question and it should be problem solved! Hope this helps.


Edit from Wolph

To make this a little easier you can use the following script (source):

  1. Save the following script as whitelist_ssl_certificate.ssh:

    #!/usr/bin/env bash -e
    
    SERVERNAME=$(echo "$1" | sed -E -e 's/https?:\/\///' -e 's/\/.*//')
    echo "$SERVERNAME"
    
    if [[ "$SERVERNAME" =~ .*\..* ]]; then
        echo "Adding certificate for $SERVERNAME"
        echo -n | openssl s_client -connect $SERVERNAME:443 | sed -ne '/-BEGIN CERTIFICATE-/,/-END CERTIFICATE-/p' | tee /tmp/$SERVERNAME.cert
        sudo security add-trusted-cert -d -r trustRoot -k "/Library/Keychains/System.keychain" /tmp/$SERVERNAME.cert
    else
        echo "Usage: $0 www.site.name"
        echo "http:// and such will be stripped automatically"
    fi
    
  2. Make the script executable (from the shell):

    chmod +x whitelist_ssl_certificate.ssh
    
  3. Run the script for the domain you want (simply copy/pasting the full url works):

    ./whitelist_ssl_certificate.ssh https://your_website/whatever
    

x86 Assembly on a Mac

Running assembly Code on Mac is just 3 steps away from you. It could be done using XCODE but better is to use NASM Command Line Tool. For My Ease I have already installed Xcode, if you have Xcode installed its good.

But You can do it without XCode as well.

Just Follow:

  1. First Install NASM using Homebrew brew install nasm
  2. convert .asm file into Obj File using this command nasm -f macho64 myFile.asm
  3. Run Obj File to see OutPut using command ld -macosx_version_min 10.7.0 -lSystem -o OutPutFile myFile.o && ./64

Simple Text File named myFile.asm is written below for your convenience.

global start
section .text

start:
    mov     rax, 0x2000004 ; write
    mov     rdi, 1 ; stdout
    mov     rsi, msg
    mov     rdx, msg.len
    syscall

    mov     rax, 0x2000001 ; exit
    mov     rdi, 0
    syscall

section .data

msg:    db      "Assalam O Alaikum Dear", 10
.len:   equ     $ - msg

Facebook share button and custom text

We use something like this [use in one line]:

<a title="send to Facebook" 
  href="http://www.facebook.com/sharer.php?s=100&p[title]=YOUR_TITLE&p[summary]=YOUR_SUMMARY&p[url]=YOUR_URL&p[images][0]=YOUR_IMAGE_TO_SHARE_OBJECT"
  target="_blank">
  <span>
    <img width="14" height="14" src="'icons/fb.gif" alt="Facebook" /> Facebook 
  </span>
</a>

How to update only one field using Entity Framework?

I'm late to the game here, but this is how I am doing it, I spent a while hunting for a solution I was satisified with; this produces an UPDATE statement ONLY for the fields that are changed, as you explicitly define what they are through a "white list" concept which is more secure to prevent web form injection anyway.

An excerpt from my ISession data repository:

public bool Update<T>(T item, params string[] changedPropertyNames) where T 
  : class, new()
{
    _context.Set<T>().Attach(item);
    foreach (var propertyName in changedPropertyNames)
    {
        // If we can't find the property, this line wil throw an exception, 
        //which is good as we want to know about it
        _context.Entry(item).Property(propertyName).IsModified = true;
    }
    return true;
}

This could be wrapped in a try..catch if you so wished, but I personally like my caller to know about the exceptions in this scenario.

It would be called in something like this fashion (for me, this was via an ASP.NET Web API):

if (!session.Update(franchiseViewModel.Franchise, new[]
    {
      "Name",
      "StartDate"
  }))
  throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.NotFound));

Git commit -a "untracked files"?

As the name suggests 'untracked files' are the files which are not being tracked by git. They are not in your staging area, and were not part of any previous commits. If you want them to be versioned (or to be managed by git) you can do so by telling 'git' by using 'git add'. Check this chapter Recording Changes to the Repository in the Progit book which uses a nice visual to provide a good explanation about recording changes to git repo and also explaining the terms 'tracked' and 'untracked'.

Debug/run standard java in Visual Studio Code IDE and OS X?

Code Runner Extension will only let you "run" java files.

To truly debug 'Java' files follow the quick one-time setup:

  • Install Java Debugger Extension in VS Code and reload.
  • open an empty folder/project in VS code.
  • create your java file (s).
  • create a folder .vscode in the same folder.
  • create 2 files inside .vscode folder: tasks.json and launch.json
  • copy paste below config in tasks.json:
{
    "version": "2.0.0",
    "type": "shell",
    "presentation": {
        "echo": true,
        "reveal": "always",
        "focus": false,
        "panel": "shared"
    },
    "isBackground": true,
    "tasks": [
        {
            "taskName": "build",
            "args": ["-g", "${file}"],
            "command": "javac"
        }
    ]
}
  • copy paste below config in launch.json:
{
    "version": "0.2.0",
    "configurations": [
        {
            "name": "Debug Java",
            "type": "java",
            "request": "launch",
            "externalConsole": true,                //user input dosen't work if set it to false :(
            "stopOnEntry": true,
            "preLaunchTask": "build",                 // Runs the task created above before running this configuration
            "jdkPath": "${env:JAVA_HOME}/bin",        // You need to set JAVA_HOME enviroment variable
            "cwd": "${workspaceRoot}",
            "startupClass": "${workspaceRoot}${file}",
            "sourcePath": ["${workspaceRoot}"],   // Indicates where your source (.java) files are
            "classpath": ["${workspaceRoot}"],    // Indicates the location of your .class files
            "options": [],                             // Additional options to pass to the java executable
            "args": []                                // Command line arguments to pass to the startup class
        }

    ],
    "compounds": []
}

You are all set to debug java files, open any java file and press F5 (Debug->Start Debugging).


Tip: *To hide .class files in the side explorer of VS code, open settings of VS code and paste the below config:

"files.exclude": {
        "*.class": true
    }

enter image description here

How to: "Separate table rows with a line"

You could use the border-bottom css property.

_x000D_
_x000D_
table {_x000D_
  border-collapse: collapse;_x000D_
}_x000D_
_x000D_
table tr {_x000D_
  border-bottom: 1px solid black;_x000D_
}_x000D_
_x000D_
table tr:last-child {_x000D_
  border: 0;_x000D_
}
_x000D_
<table>_x000D_
  <tr>_x000D_
    <td>1</td>_x000D_
    <td>Foo</td>_x000D_
  </tr>_x000D_
  <tr>_x000D_
    <td>2</td>_x000D_
    <td>Bar</td>_x000D_
  </tr>_x000D_
</table>
_x000D_
_x000D_
_x000D_

Rendering raw html with reactjs

I needed to use a link with onLoad attribute in my head where div is not allowed so this caused me significant pain. My current workaround is to close the original script tag, do what I need to do, then open script tag (to be closed by the original). Hope this might help someone who has absolutely no other choice:

<script dangerouslySetInnerHTML={{ __html: `</script>
   <link rel="preload" href="https://fonts.googleapis.com/css?family=Open+Sans" as="style" onLoad="this.onload=null;this.rel='stylesheet'" crossOrigin="anonymous"/>
<script>`,}}/>

How to use "like" and "not like" in SQL MSAccess for the same field?

what's the problem with:

field like "*AA*" and field not like "*BB*"

it should be working.

Could you post some example of your data?

Bootstrap: Open Another Modal in Modal

Try this:

// Hide the login modal
$('#login').modal('hide');

// Show the next modal after the fade effect is finished
setTimeout(function(){ $('#lost').modal('show'); }, 500);

This simple hack works for me.

Unique constraint violation during insert: why? (Oracle)

Your error looks like you are duplicating an already existing Primary Key in your DB. You should modify your sql code to implement its own primary key by using something like the IDENTITY keyword.

CREATE TABLE [DB] (
    [DBId] bigint NOT NULL IDENTITY,
    ...

    CONSTRAINT [DB_PK] PRIMARY KEY ([DB] ASC),

); 

Go to Matching Brace in Visual Studio?

On Spanish (Spain) keyboard with VS2012 is Ctrl + ¡ as stated by @Keith but if you use Ctrl + ¿ (typed as Ctrl + Shift + ¡) then goes to Matching Brace plus selects all the code within the two braces and then you can't go again to the other brace.

What is the way of declaring an array in JavaScript?

The preferred way is to always use the literal syntax with square brackets; its behaviour is predictable for any number of items, unlike Array's. What's more, Array is not a keyword, and although it is not a realistic situation, someone could easily overwrite it:

function Array() { return []; }

alert(Array(1, 2, 3)); // An empty alert box

However, the larger issue is that of consistency. Someone refactoring code could come across this function:

function fetchValue(n) {
    var arr = new Array(1, 2, 3);

    return arr[n];
}

As it turns out, only fetchValue(0) is ever needed, so the programmer drops the other elements and breaks the code, because it now returns undefined:

var arr = new Array(1);

How can I make a multipart/form-data POST request using Java?

If size of the JARs matters (e.g. in case of applet), one can also directly use httpmime with java.net.HttpURLConnection instead of HttpClient.

httpclient-4.2.4:      423KB
httpmime-4.2.4:         26KB
httpcore-4.2.4:        222KB
commons-codec-1.6:     228KB
commons-logging-1.1.1:  60KB
Sum:                   959KB

httpmime-4.2.4:         26KB
httpcore-4.2.4:        222KB
Sum:                   248KB

Code:

HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestMethod("POST");

FileBody fileBody = new FileBody(new File(fileName));
MultipartEntity multipartEntity = new MultipartEntity(HttpMultipartMode.STRICT);
multipartEntity.addPart("file", fileBody);

connection.setRequestProperty("Content-Type", multipartEntity.getContentType().getValue());
OutputStream out = connection.getOutputStream();
try {
    multipartEntity.writeTo(out);
} finally {
    out.close();
}
int status = connection.getResponseCode();
...

Dependency in pom.xml:

<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpmime</artifactId>
    <version>4.2.4</version>
</dependency>

JavaScript: How to join / combine two arrays to concatenate into one array?

var a = ['a','b','c'];
var b = ['d','e','f'];
var c = a.concat(b); //c is now an an array with: ['a','b','c','d','e','f']
console.log( c[3] ); //c[3] will be 'd'

Prevent Default on Form Submit jQuery

Try this:

$("#cpa-form").submit(function(e){
    return false;
});

JavaScript string with new line - but not using \n

This is a small adition to @Andrew Dunn's post above

Combining the 2 is possible to generate readable JS and matching output

 var foo = "Bob\n\
    is\n\
    cool.\n\";

Android: How to bind spinner to custom object list?

inspired by Joaquin Alberto, this worked for me:

public class SpinAdapter extends ArrayAdapter<User>{


    public SpinAdapter(Context context, int textViewResourceId,
            User[] values) {
        super(context, textViewResourceId, values);
    }



    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        TextView label = (TextView) super.getView(position, convertView, parent);
        label.setTextColor(Color.BLACK);
        label.setText(this.getItem(position).getName());
        return label;
    }

    @Override
    public View getDropDownView(int position, View convertView,ViewGroup parent) {
        TextView label = (TextView) super.getView(position, convertView, parent);
        label.setTextColor(Color.BLACK);
        label.setText(this.getItem(position).getName());
        return label;
    }
}

How can I change the size of a Bootstrap checkbox?

Following works in bootstrap 4 and displays well in CSS, mobile and has no issues with label spacing.

enter image description here

CSS

.checkbox-lg .custom-control-label::before, 
.checkbox-lg .custom-control-label::after {
  top: .8rem;
  width: 1.55rem;
  height: 1.55rem;
}

.checkbox-lg .custom-control-label {
  padding-top: 13px;
  padding-left: 6px;
}


.checkbox-xl .custom-control-label::before, 
.checkbox-xl .custom-control-label::after {
  top: 1.2rem;
  width: 1.85rem;
  height: 1.85rem;
}

.checkbox-xl .custom-control-label {
  padding-top: 23px;
  padding-left: 10px;
}

HTML

<div class="custom-control custom-checkbox checkbox-lg">
      <input type="checkbox" class="custom-control-input" id="checkbox-3">
      <label class="custom-control-label" for="checkbox-3">Large checkbox</label>
    </div>

You can also make it extra large by declaring checkbox-xl

If anyone from BS team is reading this, it would be really good if you make this available right out of the box, I don't see anything for it in BS 5 either

source

How to make CSS3 rounded corners hide overflow in Chrome/Opera

I found another solution for this problem. This looks like another bug in WebKit (or probably Chrome), but it works. All you need to do - is to add a WebKit CSS Mask to the #wrapper element. You can use a single pixel png image and even include it to the CSS to save a HTTP request.

#wrapper {
width: 300px; height: 300px;
border-radius: 100px;
overflow: hidden;
position: absolute; /* this breaks the overflow:hidden in Chrome/Opera */

/* this fixes the overflow:hidden in Chrome */
-webkit-mask-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAIAAACQd1PeAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAA5JREFUeNpiYGBgAAgwAAAEAAGbA+oJAAAAAElFTkSuQmCC);
}

#box {
width: 300px; height: 300px;
background-color: #cde;
}?

JSFiddle Example

How to implode array with key and value without foreach in PHP

Using array_walk

$a = array("item1"=>"object1", "item2"=>"object2","item-n"=>"object-n");
$r=array();
array_walk($a, create_function('$b, $c', 'global $r; $r[]="$c=$b";'));
echo implode(', ', $r);

IDEONE

How can I define colors as variables in CSS?

Yeeeaaahhh.... you can now use var() function in CSS.....

The good news is you can change it using JavaScript access, which will change globally as well...

But how to declare them...

It's quite simple:

For example, you wanna assign a #ff0000 to a var(), just simply assign it in :root, also pay attention to --:

:root {
    --red: #ff0000; 
}

html, body {
    background-color: var(--red); 
}

The good things are the browser support is not bad, also don't need to be compiled to be used in the browser like LESS or SASS...

browser support

Also, here is a simple JavaScript script, which changes the red value to blue:

const rootEl = document.querySelector(':root');
root.style.setProperty('--red', 'blue');

jQuery selector first td of each row

Use:

$("tr").find("td:first");

js fiddle - this example has .text() on the end to show that it is returning the elements.

Alternatively, you can use:

$("td:first-child");

.find() - jQuery API Documentation

How to send a “multipart/form-data” POST in Android with Volley

Here is Simple Solution And Complete Example for Uploading File Using Volley Android

1) Gradle Import

compile 'dev.dworks.libs:volleyplus:+'

2)Now Create a Class RequestManager

public class RequestManager {
    private static RequestManager mRequestManager;
    /**
     * Queue which Manages the Network Requests :-)
     */
    private static RequestQueue mRequestQueue;
    // ImageLoader Instance

    private RequestManager() {

    }

    public static RequestManager get(Context context) {

        if (mRequestManager == null)
            mRequestManager = new RequestManager();

        return mRequestManager;
    }

    /**
     * @param context application context
     */
    public static RequestQueue getnstance(Context context) {

        if (mRequestQueue == null) {
            mRequestQueue = Volley.newRequestQueue(context);
        }

        return mRequestQueue;

    }


}

3)Now Create a Class to handle Request for uploading File WebService

public class WebService {
    private RequestQueue mRequestQueue;
    private static WebService apiRequests = null;

    public static WebService getInstance() {
        if (apiRequests == null) {
            apiRequests = new WebService();
            return apiRequests;
        }
        return apiRequests;
    }
    public void updateProfile(Context context, String doc_name, String doc_type, String appliance_id, File file, Response.Listener<String> listener, Response.ErrorListener errorListener) {
        SimpleMultiPartRequest request = new SimpleMultiPartRequest(Request.Method.POST, "YOUR URL HERE", listener, errorListener);
//        request.setParams(data);
        mRequestQueue = RequestManager.getnstance(context);
        request.addMultipartParam("token", "text", "tdfysghfhsdfh");
        request.addMultipartParam("parameter_1", "text", doc_name);
        request.addMultipartParam("dparameter_2", "text", doc_type);
        request.addMultipartParam("parameter_3", "text", appliance_id);
            request.addFile("document_file", file.getPath());

        request.setFixedStreamingMode(true);
        mRequestQueue.add(request);
    }
}

4) And Now Call The method Like This to Hit the service

public class Main2Activity extends AppCompatActivity implements Response.ErrorListener, Response.Listener<String>{

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);
        Button button=(Button)findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                uploadData();
            }
        });
    }

    private void uploadData() {
        WebService.getInstance().updateProfile(getActivity(), "appl_doc", "appliance", "1", mChoosenFile, this, this);
    }

    @Override
    public void onErrorResponse(VolleyError error) {

    }

    @Override
    public void onResponse(String response) {
     //Your response here 
    }
}

Calling startActivity() from outside of an Activity context

See, if you are creating an intent within a listiner in some method

override onClick (View v).

then call the context through this view as well:

v.getContext ()

There will not even need SetFlags ...

AssertNull should be used or AssertNotNull

assertNotNull asserts that the object is not null. If it is null the test fails, so you want that.

denied: requested access to the resource is denied : docker

In case anyone else runs into this - the cause, in my case, was that I was using the (deprecated) docker compose approach to push images. Switching to the expected docker push resolved the issue for me.

Getting current device language in iOS?

If you're looking for preferred language code ("en", "de", "es" ...), and localized preferred language name (for current locale), here's a simple extension in Swift:

extension Locale {
    static var preferredLanguageIdentifier: String {
        let id = Locale.preferredLanguages.first!
        let comps = Locale.components(fromIdentifier: id)
        return comps.values.first!
    }

    static var preferredLanguageLocalizedString: String {
        let id = Locale.preferredLanguages.first!
        return Locale.current.localizedString(forLanguageCode: id)!
    }
}

Send private messages to friends

For mobile application i did a solution by injecting javascript in the dialog view. There is a hidden web view in my ios app. That load the fb message send dialog api .. then i inject some javascript to set the "to" and "message" field and submit the form.. So that end user need not to do anything. Message sent to facebook inbox silently...

Difference between EXISTS and IN in SQL?

The exists keyword can be used in that way, but really it's intended as a way to avoid counting:

--this statement needs to check the entire table
select count(*) from [table] where ...

--this statement is true as soon as one match is found
exists ( select * from [table] where ... )

This is most useful where you have if conditional statements, as exists can be a lot quicker than count.

The in is best used where you have a static list to pass:

 select * from [table]
 where [field] in (1, 2, 3)

When you have a table in an in statement it makes more sense to use a join, but mostly it shouldn't matter. The query optimiser should return the same plan either way. In some implementations (mostly older, such as Microsoft SQL Server 2000) in queries will always get a nested join plan, while join queries will use nested, merge or hash as appropriate. More modern implementations are smarter and can adjust the plan even when in is used.

Tool to generate JSON schema from JSON data

For the offline tools that support multiple inputs, the best I've seen so far is https://github.com/wolverdude/GenSON/ I'd like to see a tool that takes filenames on standard input because I have thousands of files. However, I run out of open file descriptors, so make sure the files are closed. I'd also like to see JSON Schema generators that handle recursion. I am now working on generating Java classes from JSON objects in hopes of going to JSON Schema from my Java classes. Here is my GenSON script if you are curious or want to identify bugs in it.

#!/bin/sh
ulimit -n 4096
rm x3d*json
cat /dev/null > x3d.json
find ~/Downloads/www.web3d.org/x3d/content/examples -name '*json' -      print| xargs node goodJSON.js | xargs python bin/genson.py -i 2 -s     x3d.json >> x3d.json
split -p '^{' x3d.json x3d.json
python bin/genson.py -i 2 -s x3d.jsonaa -s x3d.jsonab /Users/johncarlson/Downloads/www.web3d.org/x3d/content/examples/X3dForWebAuthors/Chapter02-GeometryPrimitives/Box.json > x3dmerge.json 

Is it possible to deserialize XML into List<T>?

Yes, it does deserialize to List<>. No need to keep it in an array and wrap/encapsulate it in a list.

public class UserHolder
{
    private List<User> users = null;

    public UserHolder()
    {
    }

    [XmlElement("user")]
    public List<User> Users
    {
        get { return users; }
        set { users = value; }
    }
}

Deserializing code,

XmlSerializer xs = new XmlSerializer(typeof(UserHolder));
UserHolder uh = (UserHolder)xs.Deserialize(new StringReader(str));

Why can't I use background image and color together?

use

background:red url(../images/samle.jpg) no-repeat left top;

declaring a priority_queue in c++ with a custom comparator

You should declare a class Compare and overload operator() for it like this:

class Foo
{

};

class Compare
{
public:
    bool operator() (Foo, Foo)
    {
        return true;
    }
};

int main()
{
    std::priority_queue<Foo, std::vector<Foo>, Compare> pq;
    return 0;
}

Or, if you for some reasons can't make it as class, you could use std::function for it:

class Foo
{

};

bool Compare(Foo, Foo)
{
    return true;
}

int main()
{
    std::priority_queue<Foo, std::vector<Foo>, std::function<bool(Foo, Foo)>> pq(Compare);
    return 0;
}

How to correctly display .csv files within Excel 2013?

Open the CSV file with a decent text editor like Notepad++ and add the following text in the first line:

sep=,

Now open it with excel again.

This will set the separator as a comma, or you can change it to whatever you need.

Five equal columns in twitter bootstrap

For Bootstrap 4.4+

Use the brand new row-cols-n classes.

  1. Add row-cols-5 class to your .row div. No custom CSS needed.
  2. See the 4.4 doc here for row-cols : https://getbootstrap.com/docs/4.4/layout/grid/#row-columns

For Bootstrap 4 versions prior to Bootstrap 4.4

  1. Copy CSS below (awesome CSS by Bootstrap authors) and add it to your project

  2. Read the docs cited above to use it correctly.

    .row-cols-1>*{-ms-flex:0 0 100%;flex:0 0 100%;max-width:100%}.row-cols-2>*{-ms-flex:0 0 50%;flex:0 0 50%;max-width:50%}.row-cols-3>*{-ms-flex:0 0 33.333333%;flex:0 0 33.333333%;max-width:33.333333%}.row-cols-4>*{-ms-flex:0 0 25%;flex:0 0 25%;max-width:25%}.row-cols-5>*{-ms-flex:0 0 20%;flex:0 0 20%;max-width:20%}.row-cols-6>*{-ms-flex:0 0 16.666667%;flex:0 0 16.666667%;max-width:16.666667%}@media (min-width:576px){.row-cols-sm-1>*{-ms-flex:0 0 100%;flex:0 0 100%;max-width:100%}.row-cols-sm-2>*{-ms-flex:0 0 50%;flex:0 0 50%;max-width:50%}.row-cols-sm-3>*{-ms-flex:0 0 33.333333%;flex:0 0 33.333333%;max-width:33.333333%}.row-cols-sm-4>*{-ms-flex:0 0 25%;flex:0 0 25%;max-width:25%}.row-cols-sm-5>*{-ms-flex:0 0 20%;flex:0 0 20%;max-width:20%}.row-cols-sm-6>*{-ms-flex:0 0 16.666667%;flex:0 0 16.666667%;max-width:16.666667%}}@media (min-width:768px){.row-cols-md-1>*{-ms-flex:0 0 100%;flex:0 0 100%;max-width:100%}.row-cols-md-2>*{-ms-flex:0 0 50%;flex:0 0 50%;max-width:50%}.row-cols-md-3>*{-ms-flex:0 0 33.333333%;flex:0 0 33.333333%;max-width:33.333333%}.row-cols-md-4>*{-ms-flex:0 0 25%;flex:0 0 25%;max-width:25%}.row-cols-md-5>*{-ms-flex:0 0 20%;flex:0 0 20%;max-width:20%}.row-cols-md-6>*{-ms-flex:0 0 16.666667%;flex:0 0 16.666667%;max-width:16.666667%}}@media (min-width:992px){.row-cols-lg-1>*{-ms-flex:0 0 100%;flex:0 0 100%;max-width:100%}.row-cols-lg-2>*{-ms-flex:0 0 50%;flex:0 0 50%;max-width:50%}.row-cols-lg-3>*{-ms-flex:0 0 33.333333%;flex:0 0 33.333333%;max-width:33.333333%}.row-cols-lg-4>*{-ms-flex:0 0 25%;flex:0 0 25%;max-width:25%}.row-cols-lg-5>*{-ms-flex:0 0 20%;flex:0 0 20%;max-width:20%}.row-cols-lg-6>*{-ms-flex:0 0 16.666667%;flex:0 0 16.666667%;max-width:16.666667%}}@media (min-width:1200px){.row-cols-xl-1>*{-ms-flex:0 0 100%;flex:0 0 100%;max-width:100%}.row-cols-xl-2>*{-ms-flex:0 0 50%;flex:0 0 50%;max-width:50%}.row-cols-xl-3>*{-ms-flex:0 0 33.333333%;flex:0 0 33.333333%;max-width:33.333333%}.row-cols-xl-4>*{-ms-flex:0 0 25%;flex:0 0 25%;max-width:25%}.row-cols-xl-5>*{-ms-flex:0 0 20%;flex:0 0 20%;max-width:20%}.row-cols-xl-6>*{-ms-flex:0 0 16.666667%;flex:0 0 16.666667%;max-width:16.666667%}}

Way to go from recursion to iteration

It seems nobody has addressed where the recursive function calls itself more than once in the body, and handles returning to a specific point in the recursion (i.e. not primitive-recursive). It is said that every recursion can be turned into iteration, so it appears that this should be possible.

I just came up with a C# example of how to do this. Suppose you have the following recursive function, which acts like a postorder traversal, and that AbcTreeNode is a 3-ary tree with pointers a, b, c.

public static void AbcRecursiveTraversal(this AbcTreeNode x, List<int> list) {
        if (x != null) {
            AbcRecursiveTraversal(x.a, list);
            AbcRecursiveTraversal(x.b, list);
            AbcRecursiveTraversal(x.c, list);
            list.Add(x.key);//finally visit root
        }
}

The iterative solution:

        int? address = null;
        AbcTreeNode x = null;
        x = root;
        address = A;
        stack.Push(x);
        stack.Push(null)    

        while (stack.Count > 0) {
            bool @return = x == null;

            if (@return == false) {

                switch (address) {
                    case A://   
                        stack.Push(x);
                        stack.Push(B);
                        x = x.a;
                        address = A;
                        break;
                    case B:
                        stack.Push(x);
                        stack.Push(C);
                        x = x.b;
                        address = A;
                        break;
                    case C:
                        stack.Push(x);
                        stack.Push(null);
                        x = x.c;
                        address = A;
                        break;
                    case null:
                        list_iterative.Add(x.key);
                        @return = true;
                        break;
                }

            }


            if (@return == true) {
                address = (int?)stack.Pop();
                x = (AbcTreeNode)stack.Pop();
            }


        }

Add/delete row from a table

JavaScript with a few modifications:

function deleteRow(btn) {
  var row = btn.parentNode.parentNode;
  row.parentNode.removeChild(row);
}

And the HTML with a little difference:

<table id="dsTable">
  <tbody>
    <tr>
      <td>Relationship Type</td>
      <td>Date of Birth</td>
      <td>Gender</td>
    </tr>
    <tr>
      <td>Spouse</td>
      <td>1980-22-03</td>
      <td>female</td>
      <td><input type="button" value="Add" onclick="add()"/></td>
      <td><input type="button" value="Delete" onclick="deleteRow(this)"/></td>
    </tr>
    <tr>
      <td>Child</td>
      <td>2008-23-06</td>
      <td>female</td>
      <td><input type="button" value="Add" onclick="add()"/></td>
      <td><input type="button" value="Delete" onclick="deleteRow(this)"/></td>
    </tr>
  </tbody>
</table>???????????????????????????????????

jquery validate check at least one checkbox

 if ($('input:checkbox').filter(':checked').length < 1){
        alert("Check at least one!");
 return false;
 }

How to format a string as a telephone number in C#

As far as I know you can't do this with string.Format ... you would have to handle this yourself. You could just strip out all non-numeric characters and then do something like:

string.Format("({0}) {1}-{2}",
     phoneNumber.Substring(0, 3),
     phoneNumber.Substring(3, 3),
     phoneNumber.Substring(6));

This assumes the data has been entered correctly, which you could use regular expressions to validate.

Rerouting stdin and stdout from C

And in the meantime, there's a C source code library that will do all this for you, redirecting stdout or stderr. But the cool part is that it lets you assign as many callback functions as you want to the intercepted streams, allowing you then to very easily send a single message to multiple destinations, a DB, a text file, etc.

On top of that, it makes it trivial to create new streams that look and behave the same as stdout and stderr, where you can redirect these new streams to multiple locations as well.

look for U-Streams C library on *oogle.

How to check if element exists using a lambda expression?

Try to use anyMatch of Lambda Expression. It is much better approach.

 boolean idExists = tabPane.getTabs().stream()
            .anyMatch(t -> t.getId().equals(idToCheck));

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

  • <% %> : Executes the ruby code
  • <%= %> : Prints into Erb file. Or browser
  • <% -%> : Avoids line break after expression.
  • <%# %> : ERB comment

Difference between Parameters.Add(string, object) and Parameters.AddWithValue

There is no difference in terms of functionality. In fact, both do this:

return this.Add(new SqlParameter(parameterName, value));

The reason they deprecated the old one in favor of AddWithValue is to add additional clarity, as well as because the second parameter is object, which makes it not immediately obvious to some people which overload of Add was being called, and they resulted in wildly different behavior.

Take a look at this example:

 SqlCommand command = new SqlCommand();
 command.Parameters.Add("@name", 0);

At first glance, it looks like it is calling the Add(string name, object value) overload, but it isn't. It's calling the Add(string name, SqlDbType type) overload! This is because 0 is implicitly convertible to enum types. So these two lines:

 command.Parameters.Add("@name", 0);

and

 command.Parameters.Add("@name", 1);

Actually result in two different methods being called. 1 is not convertible to an enum implicitly, so it chooses the object overload. With 0, it chooses the enum overload.

How to tell if a <script> tag failed to load

To check if the javascript in nonexistant.js returned no error you have to add a variable inside http://fail.org/nonexistant.js like var isExecuted = true; and then check if it exists when the script tag is loaded.

However if you only want to check that the nonexistant.js returned without a 404 (meaning it exists), you can try with a isLoaded variable ...

var isExecuted = false;
var isLoaded = false;
script_tag.onload = script_tag.onreadystatechange = function() {
    if(!this.readyState ||
        this.readyState == "loaded" || this.readyState == "complete") {
        // script successfully loaded
        isLoaded = true;

        if(isExecuted) // no error
    }
}

This will cover both cases.

Is there a way to check which CSS styles are being used or not used on a web page?

Try using this tool,which is just a simple js script https://github.com/shashwatsahai/CSSExtractor/ This tool helps in getting the CSS from a specific page listing all sources for active styles and save it to a JSON with source as key and rules as value. It loads all the CSS from the href links and tells all the styles applied from them You can modify the code to save all css into a .css file. Thereby combining all your css.

Declaration of Methods should be Compatible with Parent Methods in PHP

I faced this problem while trying to extend an existing class from GitHub. I'm gonna try to explain myself, first writing the class as I though it should be, and then the class as it is now.

What I though

namespace mycompany\CutreApi;

use mycompany\CutreApi\ClassOfVendor;

class CutreApi extends \vendor\AwesomeApi\AwesomeApi
{
   public function whatever(): ClassOfVendor
   {
        return new ClassOfVendor();
   }
}

What I've finally done

namespace mycompany\CutreApi;

use \vendor\AwesomeApi\ClassOfVendor;

class CutreApi extends \vendor\AwesomeApi\AwesomeApi
{
   public function whatever(): ClassOfVendor
   {
        return new \mycompany\CutreApi\ClassOfVendor();
   }
}

So seems that this errror raises also when you're using a method that return a namespaced class, and you try to return the same class but with other namespace. Fortunately I have found this solution, but I do not fully understand the benefit of this feature in php 7.2, for me it is normal to rewrite existing class methods as you need them, including the redefinition of input parameters and / or even behavior of the method.

One downside of the previous aproach, is that IDE's could not recognise the new methods implemented in \mycompany\CutreApi\ClassOfVendor(). So, for now, I will go with this implementation.

Currently done

namespace mycompany\CutreApi;

use mycompany\CutreApi\ClassOfVendor;

class CutreApi extends \vendor\AwesomeApi\AwesomeApi
{
   public function getWhatever(): ClassOfVendor
   {
        return new ClassOfVendor();
   }
}

So, instead of trying to use "whatever" method, I wrote a new one called "getWhatever". In fact both of them are doing the same, just returning a class, but with diferents namespaces as I've described before.

Hope this can help someone.

How can change width of dropdown list?

Create a css and set the value style="width:50px;" in css code. Call the class of CSS in the drop down list. Then it will work.

Rendering an array.map() in React

You are implicitly returning undefined. You need to return the element.

this.state.data.map(function(item, i){
  console.log('test');
  return <li>Test</li>
})

Maven error "Failure to transfer..."

This worked for me in Windows:

  1. Locate the {user}/.m2/repository
  2. In the Search field in upper right of window, type ".lastupdated". Windows will look through all subfolders for these files in the directory.
  3. Remove all the .lastupdated files.
  4. Go back into Eclipse, Right-click on the project and select Maven > Update Project.
  5. Select "Force Update of Snapshots/Releases".
  6. Click Ok and the dependencies will finally resolve correctly.

How to compare types

Try the following

typeField == typeof(string)
typeField == typeof(DateTime)

The typeof operator in C# will give you a Type object for the named type. Type instances are comparable with the == operator so this is a good method for comparing them.

Note: If I remember correctly, there are some cases where this breaks down when the types involved are COM interfaces which are embedded into assemblies (via NoPIA). Doesn't sound like this is the case here.

no target device found android studio 2.1.1

If you are using 32-bit ubuntu (my case) then it is most likely that Android Studio has downloaded 64-bit version of adb and fastboot inside your sdk/platform-tools folder. I think you already have installed adb (and fastboot). If you haven't then run these commands in terminal:

sudo add-apt-repository ppa:nilarimogard/webupd8
sudo apt-get update
sudo apt-get install android-tools-adb android-tools-fastboot

This will install 32-bit version of adb and fastboot. Now just replace the 64-bit adb and fastboot executable files in sdk/platform-tools with the installed 32-bit versions:

cp /usr/bin/adb <path-to-your-adt-sdk-package>/sdk/platform-tools/adb
cp /usr/bin/fastboot <path-to-your-adt-sdk-package>/sdk/platformtools/fastboot

Now your android studio should be able to run your App in your device.

Print empty line?

Python's print function adds a newline character to its input. If you give it no input it will just print a newline character

print()

Will print an empty line. If you want to have an extra line after some text you're printing, you can a newline to your text

my_str = "hello world"
print(my_str + "\n")

If you're doing this a lot, you can also tell print to add 2 newlines instead of just one by changing the end= parameter (by default end="\n")

print("hello world", end="\n\n")

But you probably don't need this last method, the two before are much clearer.

How to generate graphs and charts from mysql database in php

I use Google Chart Tools https://developers.google.com/chart/ It's well documented and the charts look great. Being javascript, you can feed it json data via ajax.

React won't load local images

When using Webpack you need to require images in order for Webpack to process them, which would explain why external images load while internal do not, so instead of <img src={"/images/resto.png"} /> you need to use <img src={require('/images/image-name.png')} /> replacing image-name.png with the correct image name for each of them. That way Webpack is able to process and replace the source img.

How do I escape a single quote in SQL Server?

Many of us know that the Popular Method of Escaping Single Quotes is by Doubling them up easily like below.

PRINT 'It''s me, Arul.';

Doubling the Single Quotes Method

we are going to look on some other alternate ways of escaping the single quotes.

1.UNICODE Characters

39 is the UNICODE character of Single Quote. So we can use it like below.

PRINT 'Hi,it'+CHAR(39)+'s Arul.';
PRINT 'Helo,it'+NCHAR(39)+'s Arul.';

UNICODE Characters

2.QUOTED_IDENTIFIER

Another simple and best alternate solution is to use QUOTED_IDENTIFIER. When QUOTED_IDENTIFIER is set to OFF, the strings can be enclosed in double quotes. In this scenario, we don’t need to escape single quotes. So,this way would be very helpful while using lot of string values with single quotes. It will be very much helpful while using so many lines of INSERT/UPDATE scripts where column values having single quotes.

SET QUOTED_IDENTIFIER OFF;
PRINT "It's Arul."
SET QUOTED_IDENTIFIER ON;

QUOTE_IDENTIFIER

CONCLUSION

The above mentioned methods are applicable to both AZURE and On Premises .

Closing JFrame with button click

You will need a reference to the specific frame you want to close but assuming you have the reference dispose() should close the frame.

jButton1.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e)
    {
       frameToClose.dispose();
    }
});

Subset data.frame by date

The first thing you should do with date variables is confirm that R reads it as a Date. To do this, for the variable (i.e. vector/column) called Date, in the data frame called EPL2011_12, input

class(EPL2011_12$Date)

The output should read [1] "Date". If it doesn't, you should format it as a date by inputting

EPL2011_12$Date <- as.Date(EPL2011_12$Date, "%d-%m-%y")

Note that the hyphens in the date format ("%d-%m-%y") above can also be slashes ("%d/%m/%y"). Confirm that R sees it as a Date. If it doesn't, try a different formatting command

EPL2011_12$Date <- format(EPL2011_12$Date, format="%d/%m/%y")

Once you have it in Date format, you can use the subset command, or you can use brackets

WhateverYouWant <- EPL2011_12[EPL2011_12$Date > as.Date("2014-12-15"),]

'cl' is not recognized as an internal or external command,

I think cl isn't in your path. You need to add it there. The recommended way to do this is to launch a developer command prompt.

Quoting the article Setting the Path and Environment Variables for Command-Line Builds:

To open a Developer Command Prompt window

  1. With the Windows 8 Start screen showing, type Visual Studio Tools. Notice that the search results change as you type; when Visual Studio Tools appears, choose it.

    On earlier versions of Windows, choose Start, and then in the search box, type Visual Studio Tools. When Visual Studio Tools appears in the search results, choose it.

  2. In the Visual Studio Tools folder, open the Developer Command Prompt for your version of Visual Studio. (To run as administrator, open the shortcut menu for the Developer Command Prompt and choose Run as Administrator.)

As the article notes, there are several different shortcuts for setting up different toolsets - you need to pick the suitable one.

If you already have a plain Command Prompt window open, you can run the batch file vcvarsall.bat with the appropriate argument to set up the environment variables. Quoting the same article:

To run vcvarsall.bat

  1. At the command prompt, change to the Visual C++ installation directory. (The location depends on the system and the Visual Studio installation, but a typical location is C:\Program Files (x86)\Microsoft Visual Studio version\VC.) For example, enter:

    cd "\Program Files (x86)\Microsoft Visual Studio 12.0\VC"
    
  2. To configure this Command Prompt window for 32-bit x86 command-line builds, at the command prompt, enter:

    vcvarsall x86
    

From the article, the possible arguments are the following:

  • x86 (x86 32-bit native)
  • x86_amd64 (x64 on x86 cross)
  • x86_arm (ARM on x86 cross)
  • amd64 (x64 64-bit native)
  • amd64_x86 (x86 on x64 cross)
  • amd64_arm (ARM on x64 cross)

Get device token for push notification

NOTE: The below solution no longer works on iOS 13+ devices - it will return garbage data.

Please use following code instead:

+ (NSString *)hexadecimalStringFromData:(NSData *)data
{
  NSUInteger dataLength = data.length;
  if (dataLength == 0) {
    return nil;
  }

  const unsigned char *dataBuffer = (const unsigned char *)data.bytes;
  NSMutableString *hexString  = [NSMutableString stringWithCapacity:(dataLength * 2)];
  for (int i = 0; i < dataLength; ++i) {
    [hexString appendFormat:@"%02x", dataBuffer[i]];
  }
  return [hexString copy];
}

Solution that worked prior to iOS 13:

Objective-C

- (void)application:(UIApplication *)app didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken 
{
    NSString *token = [[deviceToken description] stringByTrimmingCharactersInSet: [NSCharacterSet characterSetWithCharactersInString:@"<>"]];
    token = [token stringByReplacingOccurrencesOfString:@" " withString:@""];
    NSLog(@"this will return '32 bytes' in iOS 13+ rather than the token", token);
} 

Swift 3.0

func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data)
{
    let tokenString = deviceToken.reduce("", {$0 + String(format: "%02X", $1)})
    print("this will return '32 bytes' in iOS 13+ rather than the token \(tokenString)")
}

Several ports (8005, 8080, 8009) required by Tomcat Server at localhost are already in use

If the above issue occurs in Windows 7 or 10 based OS, the problem occurs because Tomcat is running as Windows Service. To stop Tomcat running as Windows Services, Open Windows Control Panel. Find the service "Apache Tomcat" and Stop it. The Another way is to kill the process running on port 8080 using cmd.

Open cmd running it as administrator.

  1. C:\users\username>netstat -o -n -a|findstr 0.0:8080
  2. TCP 0.0.0.0:8080 0.0.0.0:0 LISTENING 2160.
  3. The above 2160 is process id of process running on port 8080 and kill that process using the following command
    C:\users\username>taskkill /F /PID 2160
  4. Go to IDE and start Server, it will run

How to split data into training/testing sets using sample function

library(caret)
intrain<-createDataPartition(y=sub_train$classe,p=0.7,list=FALSE)
training<-m_train[intrain,]
testing<-m_train[-intrain,]

Error - is not marked as serializable

You need to add a Serializable attribute to the class which you want to serialize.

[Serializable]
public class OrgPermission

How to embed YouTube videos in PHP?

If you want to upload videos programatically, check the YouTube Data API for PHP

The forked VM terminated without saying properly goodbye. VM crash or System.exit called

May be it is because you have applied some changes in your project and did not update their all references.

In my case I was getting this error because I have updated package names in my project but I forgot to update their references in TestNG.xml file. By correcting it, I solved this error.

Get Image Height and Width as integer values?

Like this :

imageCreateFromPNG($var);
//I don't know where from you get your image, here it's in the png case
// and then :
list($width, $height) = getimagesize($image);
echo $width;
echo $height;

How to remove spaces from a string using JavaScript?

SHORTEST and FASTEST: str.replace(/ /g, '');


Benchmark:

Here my results - (2018.07.13) MacOs High Sierra 10.13.3 on Chrome 67.0.3396 (64-bit), Safari 11.0.3 (13604.5.6), Firefox 59.0.2 (64-bit) ):

SHORT strings

Short string similar to examples from OP question

enter image description here

The fastest solution on all browsers is / /g (regexp1a) - Chrome 17.7M (operation/sec), Safari 10.1M, Firefox 8.8M. The slowest for all browsers was split-join solution. Change to \s or add + or i to regexp slows down processing.

LONG strings

For string about ~3 milion character results are:

  • regexp1a: Safari 50.14 ops/sec, Firefox 18.57, Chrome 8.95
  • regexp2b: Safari 38.39, Firefox 19.45, Chrome 9.26
  • split-join: Firefox 26.41, Safari 23.10, Chrome 7.98,

You can run it on your machine: https://jsperf.com/remove-string-spaces/1

How to update json file with python

def updateJsonFile():
    jsonFile = open("replayScript.json", "r") # Open the JSON file for reading
    data = json.load(jsonFile) # Read the JSON into the buffer
    jsonFile.close() # Close the JSON file

    ## Working with buffered content
    tmp = data["location"] 
    data["location"] = path
    data["mode"] = "replay"

    ## Save our changes to JSON file
    jsonFile = open("replayScript.json", "w+")
    jsonFile.write(json.dumps(data))
    jsonFile.close()

Can I use multiple versions of jQuery on the same page?

After looking at this and trying it out I found it actually didn't allow more than one instance of jquery to run at a time. After searching around I found that this did just the trick and was a whole lot less code.

    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js" type="text/javascript"></script>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" type="text/javascript"></script>
    <script>var $j = jQuery.noConflict(true);</script>
    <script>
      $(document).ready(function(){
       console.log($().jquery); // This prints v1.4.2
       console.log($j().jquery); // This prints v1.9.1
      });
   </script>

So then adding the "j" after the "$" was all I needed to do.

$j(function () {
        $j('.button-pro').on('click', function () {
            var el = $('#cnt' + this.id.replace('btn', ''));
            $j('#contentnew > div').not(el).animate({
                height: "toggle",
                opacity: "toggle"
            }, 100).hide();
            el.toggle();
        });
    });

JQuery Validate Dropdown list

The documentation for required() states:

To force a user to select an option from a select box, provide an empty options like <option value="">Choose...</option>

By having value="none" in your <option> tag, you are preventing the validation call from ever being made. You can also remove your custom validation rule, simplifying your code. Here's a jsFiddle showing it in action:

http://jsfiddle.net/Kn3v5/

If you can't change the value attribute to the empty string, I don't know what to tell you...I couldn't find any way to get it to validate otherwise.