Programs & Examples On #Ie compatibility mode

Where's the IE7/8/9/10-emulator in IE11 dev tools?

I posted an answer to this already when someone else asked the same question (see How to bring back "Browser mode" in IE11?).

Read my answer there for a fuller explaination, but in short:

  • They removed it deliberately, because compat mode is not actually really very good for testing compatibility.

  • If you really want to test for compatibility with any given version of IE, you need to test in a real copy of that IE version. MS provide free VMs on http://modern.ie/ for you to use for this purpose.

  • The only way to get compat mode in IE11 is to set the X-UA-Compatible header. When you have this and the site defaults to compat mode, you will be able to set the mode in dev tools, but only between edge or the specified compat mode; other modes will still not be available.

How to disable Compatibility View in IE

If you're using ASP.NET MVC, I found Response.AddHeader("X-UA-Compatible", "IE=edge,chrome=1") in a code block in _Layout to work quite well:

@Code
    Response.AddHeader("X-UA-Compatible", "IE=edge,chrome=1")
End Code
<!DOCTYPE html>
everything else

HTML page disable copy/paste

You can use jquery for this:

$('body').bind('copy paste',function(e) {
    e.preventDefault(); return false; 
});

Using jQuery bind() and specififying your desired eventTypes .

What are examples of TCP and UDP in real life?

The classic standpoint is to consider TCP as safe and UDP as unreliable.

But when TCP-IP protocols are used in safety critical applications, TCP is not recommended because it can stop on error for multiple reasons. Whereas UDP lets the application software deal with errors, retransmission timers, etc.

Moreover, TCP has more processing overhead than UDP.

Currently, UDP is used in aircraft controls and flight instruments, in the ARINC 664 standard also named AFDX (Avionics Full-Duplex Switched Ethernet). In ARINC 664, TCP is optional but UDP is used with the RTOS (real time operating systems) designed for the ARINC 653 standard (high reliability control software in civil aircrafts).

For more information about real time controls using IP and UDP in AFDX, you can read the pages 27 to 50 in http://www.afdx.com/pdf/AFDX_Training_October_2010_Full.pdf

Docker Error bind: address already in use

docker-compose down --rmi all 

and then restart your computer

Socket.IO - how do I get a list of connected sockets/clients?

For cluster mode, using redis-adaptor

io.in(<room>).clients(function(err, clients) {

});

As each socket is itself a room, so one can find whether a socket exist using the same.

Spark - load CSV file as DataFrame?

Default file format is Parquet with spark.read.. and file reading csv that why you are getting the exception. Specify csv format with api you are trying to use

Ignore 'Security Warning' running script from command line

For those who want to access a file from an already loaded PowerShell session, either use Unblock-File to mark the file as safe (though you already need to have set a relaxed execution policy like Unrestricted for this to work), or change the execution policy just for the current PowerShell session:

Set-ExecutionPolicy -ExecutionPolicy Bypass -Scope Process

Rails: How does the respond_to block work?

This is a block of Ruby code that takes advantage of a Rails helper method. If you aren't familiar with blocks yet, you will see them a lot in Ruby.

respond_to is a Rails helper method that is attached to the Controller class (or rather, its super class). It is referencing the response that will be sent to the View (which is going to the browser).

The block in your example is formatting data - by passing in a 'format' paramater in the block - to be sent from the controller to the view whenever a browser makes a request for html or json data.

If you are on your local machine and you have your Post scaffold set up, you can go to http://localhost:3000/posts and you will see all of your posts in html format. But, if you type in this: http://localhost:3000/posts.json, then you will see all of your posts in a json object sent from the server.

This is very handy for making javascript heavy applications that need to pass json back and forth from the server. If you wanted, you could easily create a json api on your rails back-end, and only pass one view - like the index view of your Post controller. Then you could use a javascript library like Jquery or Backbone (or both) to manipulate data and create your own interface. These are called asynchronous UIs and they are becomming really popular (Gmail is one). They are very fast and give the end-user a more desktop-like experience on the web. Of course, this is just one advantage of formatting your data.

The Rails 3 way of writing this would be this:

    class PostsController < ApplicationController
      # GET /posts
      # GET /posts.xml


      respond_to :html, :xml, :json

      def index
        @posts = Post.all

        respond_with(@posts)
      end

#
# All your other REST methods
#

end

By putting respond_to :html, :xml, :json at the top of the class, you can declare all the formats that you want your controller to send to your views.

Then, in the controller method, all you have to do is respond_with(@whatever_object_you_have)

It just simplifies your code a little more than what Rails auto-generates.

If you want to know about the inner-workings of this...

From what I understand, Rails introspects the objects to determine what the actual format is going to be. The 'format' variables value is based on this introspection. Rails can do a whole lot with a little bit of info. You'd be surprised at how far a simple @post or :post will go.

For example, if I had a _user.html.erb partial file that looked like this:

_user.html.erb

<li>    
    <%= link_to user.name, user %>
</li>

Then, this alone in my index view would let Rails know that it needed to find the 'users' partial and iterate through all of the 'users' objects:

index.html.erb

 <ul class="users">
   <%= render @users %>     
 </ul>

would let Rails know that it needed to find the 'user' partial and iterate through all of the 'users' objects:

You may find this blog post useful: http://archives.ryandaigle.com/articles/2009/8/6/what-s-new-in-edge-rails-cleaner-restful-controllers-w-respond_with

You can also peruse the source: https://github.com/rails/rails

How to get the full url in Express?

I use the node package 'url' (npm install url)

What it does is when you call

url.parse(req.url, true, true)

it will give you the possibility to retrieve all or parts of the url. More info here: https://github.com/defunctzombie/node-url

I used it in the following way to get whatever comes after the / in http://www.example.com/ to use as a variable and pull up a particular profile (kind of like facebook: http://www.facebook.com/username)

    var url = require('url');
    var urlParts = url.parse(req.url, true, true);
    var pathname = urlParts.pathname;
    var username = pathname.slice(1);

Though for this to work, you have to create your route this way in your server.js file:

self.routes['/:username'] = require('./routes/users');

And set your route file this way:

router.get('/:username', function(req, res) {
 //here comes the url parsing code
}

Rails: Using greater than/less than with a where statement

A better usage is to create a scope in the user model where(arel_table[:id].gt(id))

Parse large JSON file in Nodejs

I solved this problem using the split npm module. Pipe your stream into split, and it will "Break up a stream and reassemble it so that each line is a chunk".

Sample code:

var fs = require('fs')
  , split = require('split')
  ;

var stream = fs.createReadStream(filePath, {flags: 'r', encoding: 'utf-8'});
var lineStream = stream.pipe(split());
linestream.on('data', function(chunk) {
    var json = JSON.parse(chunk);           
    // ...
});

Getting java.lang.ClassNotFoundException: org.apache.commons.logging.LogFactory exception

I had the same problem, and solved it by just adding the commons-logging.jar to the class path.

How do I use arrays in cURL POST requests

You are just creating your array incorrectly. You could use http_build_query:

$fields = array(
            'username' => "annonymous",
            'api_key' => urlencode("1234"),
            'images' => array(
                 urlencode(base64_encode('image1')),
                 urlencode(base64_encode('image2'))
            )
        );
$fields_string = http_build_query($fields);

So, the entire code that you could use would be:

<?php
//extract data from the post
extract($_POST);

//set POST variables
$url = 'http://api.example.com/api';
$fields = array(
            'username' => "annonymous",
            'api_key' => urlencode("1234"),
            'images' => array(
                 urlencode(base64_encode('image1')),
                 urlencode(base64_encode('image2'))
            )
        );

//url-ify the data for the POST
$fields_string = http_build_query($fields);

//open connection
$ch = curl_init();

//set the url, number of POST vars, POST data
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_POST, 1);
curl_setopt($ch,CURLOPT_POSTFIELDS, $fields_string);

//execute post
$result = curl_exec($ch);
echo $result;

//close connection
curl_close($ch);
?>

Namespace for [DataContract]

First, I add the references to my Model, then I use them in my code. There are two references you should add:

using System.ServiceModel;
using System.Runtime.Serialization;

then, this problem was solved in my program. I hope this answer can help you. Thanks.

How to show loading spinner in jQuery?

For jQuery I use

jQuery.ajaxSetup({
  beforeSend: function() {
     $('#loader').show();
  },
  complete: function(){
     $('#loader').hide();
  },
  success: function() {}
});

Mailto links do nothing in Chrome but work in Firefox?

This is because chrome handles the mailto in different way. You can go to chrome://settings/handlers and make sure that which is the default handler. In your case it will be none (i.e. not listed). Now go to gmail.com. You should see something like this when you click on the button beside the bookmark button.

Set mailto in chrome

If you wish to open all email links through gmail then set "Use Gmail". Now when you click on mailto button, chrome will automatically opens in gmail.

Start script missing error when running npm start

You might have an old (global) installation of npm which causes the issue. As of 12/19, npm does not support global installations.

First, uninstall the package using:
npm uninstall -g create-react-app

Some osx/Linux users may need to also remove the old npm using:
rm -rf /usr/local/bin/create-react-app

This is now the only supported method for generating a project:
npx create-react-app my-app

Finally you can run:
npm start

Laravel Escaping All HTML in Blade Template

I had the same issue. Thanks for the answers above, I solved my issue. If there are people facing the same problem, here is two way to solve it:

  • You can use {!! $news->body !!}
  • You can use traditional php openning (It is not recommended) like: <?php echo $string ?>

I hope it helps.

Laravel 5 route not defined, while it is?

The route() method, which is called when you do ['route' => 'someroute'] in a form opening, wants what's called a named route. You give a route a name like this:

Route::patch('/preferences/{id}',[
    'as' => 'user.preferences.update',
    'uses' => 'UserController@update'
]);

That is, you make the second argument of the route into an array, where you specify both the route name (the as), and also what to do when the route is hit (the uses).

Then, when you open the form, you call the route:

{!! Form::model(Auth::user(), [
    'method' => 'PATCH',
    'route' => ['user.preferences.update', Auth::user()->id]
]) !!}

Now, for a route without parameters, you could just do 'route' => 'routename', but since you have a parameter, you make an array instead and supply the parameters in order.

All that said, since you appear to be updating the current user's preferences, I would advise you to let the handling controller check the id of the currently logged-in user, and base the updating on that - there's no need to send in the id in the url and the route unless your users should need to update the preferences of other users as well. :)

VBA: Conditional - Is Nothing

Based on your comment to Issun:

Thanks for the explanation. In my case, The object is declared and created prior to the If condition. So, How do I use If condition to check for < No Variables> ? In other words, I do not want to execute My_Object.Compute if My_Object has < No Variables>

You need to check one of the properties of the object. Without telling us what the object is, we cannot help you.

I did test several common objects and found that an instantiated Collection with no items added shows <No Variables> in the watch window. If your object is indeed a collection, you can check for the <No Variables> condition using the .Count property:

Sub TestObj()
Dim Obj As Object
    Set Obj = New Collection
    If Obj Is Nothing Then
        Debug.Print "Object not instantiated"
    Else
        If Obj.Count = 0 Then
            Debug.Print "<No Variables> (ie, no items added to the collection)"
        Else
            Debug.Print "Object instantiated and at least one item added"
        End If
    End If
End Sub

It is also worth noting that if you declare any object As New then the Is Nothing check becomes useless. The reason is that when you declare an object As New then it gets created automatically when it is first called, even if the first time you call it is to see if it exists!

Dim MyObject As New Collection
If MyObject Is Nothing Then  ' <--- This check always returns False

This does not seem to be the cause of your specific problem. But, since others may find this question through a Google search, I wanted to include it because it is a common beginner mistake.

How to trigger an event after using event.preventDefault()

Another solution is to use window.setTimeout in the event listener and execute the code after the event's process has finished. Something like...

window.setTimeout(function() {
  // do your thing
}, 0);

I use 0 for the period since I do not care about waiting.

OSError: [Errno 8] Exec format error

If you think the space before and after "=" is mandatory, try it as separate item in the list.

Out = subprocess.Popen(['/usr/local/bin/script', 'hostname', '=', 'actual server name', '-p', 'LONGLIST'],shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE)

PHP Function with Optional Parameters

I think, you can use objects as params-transportes, too.

$myParam = new stdClass();
$myParam->optParam2 = 'something';
$myParam->optParam8 = 3;
theFunction($myParam);

function theFunction($fparam){      
  return "I got ".$fparam->optParam8." of ".$fparam->optParam2." received!";
}

Of course, you have to set default values for "optParam8" and "optParam2" in this function, in other case you will get "Notice: Undefined property: stdClass::$optParam2"

If using arrays as function parameters, I like this way to set default values:

function theFunction($fparam){
   $default = array(
      'opt1' => 'nothing',
      'opt2' => 1
   );
   if(is_array($fparam)){
      $fparam = array_merge($default, $fparam);
   }else{
      $fparam = $default;
   }
   //now, the default values are overwritten by these passed by $fparam
   return "I received ".$fparam['opt1']." and ".$fparam['opt2']."!";
}

How to use Python to login to a webpage and retrieve cookies for later usage?

Here's a version using the excellent requests library:

from requests import session

payload = {
    'action': 'login',
    'username': USERNAME,
    'password': PASSWORD
}

with session() as c:
    c.post('http://example.com/login.php', data=payload)
    response = c.get('http://example.com/protected_page.php')
    print(response.headers)
    print(response.text)

How to clear all <div>s’ contents inside a parent <div>?

If all the divs inside that masterdiv needs to be cleared, it this.

$('#masterdiv div').html('');

else, you need to iterate on all the div children of #masterdiv, and check if the id starts with childdiv.

$('#masterdiv div').each(
    function(element){
        if(element.attr('id').substr(0, 8) == "childdiv")
        {
            element.html('');
        }
    }
 );

Extracting Nupkg files using command line

NuPKG files are just zip files, so anything that can process a zip file should be able to process a nupkg file, i.e, 7zip.

Check if a value is within a range of numbers

Here is an option with only a single comparison.

// return true if in range, otherwise false
function inRange(x, min, max) {
    return ((x-min)*(x-max) <= 0);
}

console.log(inRange(5, 1, 10));     // true
console.log(inRange(-5, 1, 10));    // false
console.log(inRange(20, 1, 10));    // false

Angular get object from array by Id

getDimensions(id) {
    var obj = questions.filter(function(node) {
        return node.id==id;
    });

    return obj;   
}

Boolean vs tinyint(1) for boolean values in MySQL

While it's true that bool and tinyint(1) are functionally identical, bool should be the preferred option because it carries the semantic meaning of what you're trying to do. Also, many ORMs will convert bool into your programing language's native boolean type.

Apply a theme to an activity in Android?

Before you call setContentView(), call setTheme(android.R.style...) and just replace the ... with the theme that you want(Theme, Theme_NoTitleBar, etc.).

Or if your theme is a custom theme, then replace the entire thing, so you get setTheme(yourThemesResouceId)

How do you convert a byte array to a hexadecimal string, and vice versa?

You can use the BitConverter.ToString method:

byte[] bytes = {0, 1, 2, 4, 8, 16, 32, 64, 128, 256}
Console.WriteLine( BitConverter.ToString(bytes));

Output:

00-01-02-04-08-10-20-40-80-FF

More information: BitConverter.ToString Method (Byte[])

Pure CSS checkbox image replacement

If you are still looking for further more customization,

Check out the following library: https://lokesh-coder.github.io/pretty-checkbox/

Thanks

How do you create a dictionary in Java?

There's an Abstract Class Dictionary

http://docs.oracle.com/javase/6/docs/api/java/util/Dictionary.html

However this requires implementation.

Java gives us a nice implementation called a Hashtable

http://docs.oracle.com/javase/6/docs/api/java/util/Hashtable.html

Determine if a cell (value) is used in any formula

Have you tried Tools > Formula Auditing?

How to confirm RedHat Enterprise Linux version?

That's the RHEL release version.

You can see the kernel version by typing uname -r. It'll be 2.6.something.

.htaccess: Invalid command 'RewriteEngine', perhaps misspelled or defined by a module not included in the server configuration

or defined by a module not included in the server configuration

Check to make sure you have mod_rewrite enabled.

From: https://webdevdoor.com/php/mod_rewrite-windows-apache-url-rewriting

  1. Find the httpd.conf file (usually you will find it in a folder called conf, config or something along those lines)
  2. Inside the httpd.conf file uncomment the line LoadModule rewrite_module modules/mod_rewrite.so (remove the pound '#' sign from in front of the line)
  3. Also find the line ClearModuleList is uncommented then find and make sure that the line AddModule mod_rewrite.c is not commented out.

If the LoadModule rewrite_module modules/mod_rewrite.so line is missing from the httpd.conf file entirely, just add it.

Sample command

To enable the module in a standard ubuntu do this:

a2enmod rewrite
systemctl restart apache2

Single huge .css file vs. multiple smaller specific .css files?

Having only one CSS file is better for the loading-time of your pages, as it means less HTTP requests.

Having several little CSS files means development is easier (at least, I think so : having one CSS file per module of your application makes things easier).

So, there are good reasons in both cases...


A solution that would allow you to get the best of both ideas would be :

  • To develop using several small CSS files
    • i.e. easier to develop
  • To have a build process for your application, that "combines" those files into one
    • That build process could also minify that big file, btw
    • It obviously means that your application must have some configuration stuff that allows it to swith from "multi-files mode" to "mono-file mode".
  • And to use, in production, only the big file
    • i.e. faster loading pages

There are also some software that do that combining of CSS files at run-time, and not at build-time ; but doing it at run-time means eating a bit more CPU (and obvisouly requires some caching mecanism, to not re-generate the big file too often)

How to insert DECIMAL into MySQL database

MySql decimal types are a little bit more complicated than just left-of and right-of the decimal point.

The first argument is precision, which is the number of total digits. The second argument is scale which is the maximum number of digits to the right of the decimal point.

Thus, (4,2) can be anything from -99.99 to 99.99.

As for why you're getting 99.99 instead of the desired 3.80, the value you're inserting must be interpreted as larger than 99.99, so the max value is used. Maybe you could post the code that you are using to insert or update the table.

Edit

Corrected a misunderstanding of the usage of scale and precision, per http://dev.mysql.com/doc/refman/5.0/en/numeric-types.html.

How to import a bak file into SQL Server Express

Using management studio the procedure can be done as follows

  1. right click on the Databases container within object explorer
  2. from context menu select Restore database
  3. Specify To Database as either a new or existing database
  4. Specify Source for restore as from device
  5. Select Backup media as File
  6. Click the Add button and browse to the location of the BAK file

refer

You'll need to specify the WITH REPLACE option to overwrite the existing adventure_second database with a backup taken from a different database.

Click option menu and tick Overwrite the existing database(With replace)

Reference

Hadoop: «ERROR : JAVA_HOME is not set»

The solution that worked for me was setting my JAVA_HOME in /etc/environment

Though JAVA_HOME can be set inside the /etc/profile files, the preferred location for JAVA_HOME or any system variable is /etc/environment.

Open /etc/environment in any text editor like nano or vim and add the following line:

JAVA_HOME="/usr/lib/jvm/your_java_directory"

Load the variables:

source /etc/environment

Check if the variable loaded correctly:

echo $JAVA_HOME

inverting image in Python with OpenCV

Alternatively, you could invert the image using the bitwise_not function of OpenCV:

imagem = cv2.bitwise_not(imagem)

I liked this example.

What's the difference between implementation and compile in Gradle?

tl;dr

Just replace:

  • compile with implementation (if you don't need transitivity) or api (if you need transitivity)
  • testCompile with testImplementation
  • debugCompile with debugImplementation
  • androidTestCompile with androidTestImplementation
  • compileOnly is still valid. It was added in 3.0 to replace provided and not compile. (provided introduced when Gradle didn't have a configuration name for that use-case and named it after Maven's provided scope.)

It is one of the breaking changes coming with Android Gradle plugin 3.0 that Google announced at IO17.

The compile configuration is now deprecated and should be replaced by implementation or api

From the Gradle documentation:

dependencies {
    api 'commons-httpclient:commons-httpclient:3.1'
    implementation 'org.apache.commons:commons-lang3:3.5'
}

Dependencies appearing in the api configurations will be transitively exposed to consumers of the library, and as such will appear on the compile classpath of consumers.

Dependencies found in the implementation configuration will, on the other hand, not be exposed to consumers, and therefore not leak into the consumers' compile classpath. This comes with several benefits:

  • dependencies do not leak into the compile classpath of consumers anymore, so you will never accidentally depend on a transitive dependency
  • faster compilation thanks to reduced classpath size
  • less recompilations when implementation dependencies change: consumers would not need to be recompiled
  • cleaner publishing: when used in conjunction with the new maven-publish plugin, Java libraries produce POM files that distinguish exactly between what is required to compile against the library and what is required to use the library at runtime (in other words, don't mix what is needed to compile the library itself and what is needed to compile against the library).

The compile configuration still exists, but should not be used as it will not offer the guarantees that the api and implementation configurations provide.


Note: if you are only using a library in your app module -the common case- you won't notice any difference.
you will only see the difference if you have a complex project with modules depending on each other, or you are creating a library.

How to print pthread_t

Just a supplement to the first post: use a user defined union type to store the pthread_t:

union tid {
    pthread_t pthread_id;
    unsigned long converted_id;
};

Whenever you want to print pthread_t, create a tid and assign tid.pthread_id = ..., then print tid.converted_id.

LaTeX: Multiple authors in a two-column article

What about using a tabular inside \author{}, just like in IEEE macros:

\documentclass{article}
\begin{document}
\title{Hello, World}
\author{
\begin{tabular}[t]{c@{\extracolsep{8em}}c} 
I. M. Author  & M. Y. Coauthor \\
My Department & Coauthor Department \\ 
My Institute & Coauthor Institute \\
email, address & email, address
\end{tabular}
}
\maketitle    
\end{document}

This will produce two columns authors with any documentclass.

Results:

enter image description here

Loop through checkboxes and count each one checked or unchecked

You can loop through all of the checkboxes by writing $(':checkbox').each(...).

If I understand your question correctly, you're looking for the following code:

var str = "";

$(':checkbox').each(function() {
    str += this.checked ? "1," : "0,";
});

str = str.substr(0, str.length - 1);    //Remove the trailing comma

This code will loop through all of the checkboxes and add either 1, or 0, to a string.

Python error when trying to access list by index - "List indices must be integers, not str"

A list is a chain of spaces that can be indexed by (0, 1, 2 .... etc). So if players was a list, players[0] or players[1] would have worked. If players is a dictionary, players["name"] would have worked.

Undefined function mysql_connect()

There must be some syntax error. Copy/paste this code and see if it works:

<?php
    $link = mysql_connect('localhost', 'root', '');
    if (!$link) {
        die('Could not connect:' . mysql_error());
    }
    echo 'Connected successfully';
    ?

I had the same error message. It turns out I was using the msql_connect() function instead of mysql_connect().

Valid characters in a Java class name

You can have almost any character, including most Unicode characters! The exact definition is in the Java Language Specification under section 3.8: Identifiers.

An identifier is an unlimited-length sequence of Java letters and Java digits, the first of which must be a Java letter. ...

Letters and digits may be drawn from the entire Unicode character set, ... This allows programmers to use identifiers in their programs that are written in their native languages.

An identifier cannot have the same spelling (Unicode character sequence) as a keyword (§3.9), boolean literal (§3.10.3), or the null literal (§3.10.7), or a compile-time error occurs.

However, see this question for whether or not you should do that.

Android textview usage as label and value

You should implement a Custom List View, such that you define a Layout once and draw it for every row in the list view.

Getting the client's time zone (and offset) in JavaScript

try getTimezoneOffset() of the Date object:

var curdate = new Date()
var offset = curdate.getTimezoneOffset()

This method returns time zone offset in minutes which is the difference between GMT and local time in minutes.

How to deploy a Java Web Application (.war) on tomcat?

Note that you can deploy remotely using HTTP.

http://localhost:8080/manager/deploy

Upload the web application archive (WAR) file that is specified as the request data in this HTTP PUT request, install it into the appBase directory of our corresponding virtual host, and start it using the war file name without the .war extension as the path. The application can later be undeployed (and the corresponding application directory removed) by use of the /undeploy. To deploy the ROOT web application (the application with a context path of "/"), name the war ROOT.war.

and if you're using Ant you can do this using Tomcat Ant tasks (perhaps following a successful build).

To determine which path you then hit on your browser, you need to know the port Tomcat is running on, the context and your servlet path. See here for more details.

How do I resolve the "java.net.BindException: Address already in use: JVM_Bind" error?

I faced similar issue in Eclipse when two consoles were opened when I started the Server program first and then the Client program. I used to stop the program in the single console thinking that it had closed the server, but it had only closed the client and not the server. I found running Java processes in my Task manager. This problem was solved by closing both Server and Client programs from their individual consoles(Eclipse shows console of latest active program). So when I started the Server program again, the port was again open to be captured.

how can select from drop down menu and call javascript function

Greetings if i get you right you need a JavaScript function that doing it

function report(v) {
//To Do
  switch(v) {
    case "daily":
      //Do something
      break;
    case "monthly":
      //Do somthing
      break;
    }
  }

Regards

Multiple Image Upload PHP form with one input

PHP Code

<?php
error_reporting(0);
session_start();
include('config.php');
//define session id
$session_id='1'; 
define ("MAX_SIZE","9000"); 
function getExtension($str)
{
         $i = strrpos($str,".");
         if (!$i) { return ""; }
         $l = strlen($str) - $i;
         $ext = substr($str,$i+1,$l);
         return $ext;
}

//set the image extentions
$valid_formats = array("jpg", "png", "gif", "bmp","jpeg");
if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST") 
{

    $uploaddir = "uploads/"; //image upload directory
    foreach ($_FILES['photos']['name'] as $name => $value)
    {

        $filename = stripslashes($_FILES['photos']['name'][$name]);
        $size=filesize($_FILES['photos']['tmp_name'][$name]);
        //get the extension of the file in a lower case format
          $ext = getExtension($filename);
          $ext = strtolower($ext);

         if(in_array($ext,$valid_formats))
         {
           if ($size < (MAX_SIZE*1024))
           {
           $image_name=time().$filename;
           echo "<img src='".$uploaddir.$image_name."' class='imgList'>";
           $newname=$uploaddir.$image_name;

           if (move_uploaded_file($_FILES['photos']['tmp_name'][$name], $newname)) 
           {
           $time=time();
               //insert in database
           mysql_query("INSERT INTO user_uploads(image_name,user_id_fk,created) VALUES('$image_name','$session_id','$time')");
           }
           else
           {
            echo '<span class="imgList">You have exceeded the size limit! so moving unsuccessful! </span>';
            }

           }
           else
           {
            echo '<span class="imgList">You have exceeded the size limit!</span>';

           }

          }
          else
         { 
             echo '<span class="imgList">Unknown extension!</span>';

         }

     }
}

?>

Jquery Code

<script>
 $(document).ready(function() { 

            $('#photoimg').die('click').live('change', function()            { 

                $("#imageform").ajaxForm({target: '#preview', 
                     beforeSubmit:function(){ 

                    console.log('ttest');
                    $("#imageloadstatus").show();
                     $("#imageloadbutton").hide();
                     }, 
                    success:function(){ 
                    console.log('test');
                     $("#imageloadstatus").hide();
                     $("#imageloadbutton").show();
                    }, 
                    error:function(){ 
                    console.log('xtest');
                     $("#imageloadstatus").hide();
                    $("#imageloadbutton").show();
                    } }).submit();


            });
        }); 
</script>

SQL SERVER DATETIME FORMAT

This is my favorite use of 112 and 114

select (convert(varchar, getdate(), 112)+ replace(convert(varchar, getdate(), 114),':','')) as 'Getdate() 

112 + 114 or YYYYMMDDHHMMSSMSS'

Result:

Getdate() 112 + 114 or YYYYMMDDHHMMSSMSS

20171016083349100

Can I dispatch an action in reducer?

Dispatching and action inside of reducer seems occurs bug.

I made a simple counter example using useReducer which "INCREASE" is dispatched then "SUB" also does.

In the example I expected "INCREASE" is dispatched then also "SUB" does and, set cnt to -1 and then continue "INCREASE" action to set cnt to 0, but it was -1 ("INCREASE" was ignored)

See this: https://codesandbox.io/s/simple-react-context-example-forked-p7po7?file=/src/index.js:144-154

let listener = () => {
  console.log("test");
};
const middleware = (action) => {
  console.log(action);
  if (action.type === "INCREASE") {
    listener();
  }
};

const counterReducer = (state, action) => {
  middleware(action);
  switch (action.type) {
    case "INCREASE":
      return {
        ...state,
        cnt: state.cnt + action.payload
      };
    case "SUB":
      return {
        ...state,
        cnt: state.cnt - action.payload
      };
    default:
      return state;
  }
};

const Test = () => {
  const { cnt, increase, substract } = useContext(CounterContext);

  useEffect(() => {
    listener = substract;
  });

  return (
    <button
      onClick={() => {
        increase();
      }}
    >
      {cnt}
    </button>
  );
};

{type: "INCREASE", payload: 1}
{type: "SUB", payload: 1}
// expected: cnt: 0
// cnt = -1

How do I request and process JSON with python?

Python's standard library has json and urllib2 modules.

import json
import urllib2

data = json.load(urllib2.urlopen('http://someurl/path/to/json'))

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

Use this method:

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

How to copy data from another workbook (excel)?

Would you be happy to make "my file.xls" active if it didn't affect the screen? Turning off screen updating is the way to achieve this, it also has performance improvements (significant if you are doing looping while switching around worksheets / workbooks).

The command to do this is:

    Application.ScreenUpdating = False

Don't forget to turn it back to True when your macros is finished.

Redirecting output to $null in PowerShell, but ensuring the variable remains set

If it's errors you want to hide you can do it like this

$ErrorActionPreference = "SilentlyContinue"; #This will hide errors
$someObject.SomeFunction();
$ErrorActionPreference = "Continue"; #Turning errors back on

How to convert LINQ query result to List?

What you can do is select everything into a new instance of Course, and afterwards convert them to a List.

var qry = from a in obj.tbCourses
                     select new Course() {
                         Course.Property = a.Property
                         ...
                     };

qry.toList<Course>();

Select 2 columns in one and combine them

select column1 || ' ' || column2 as whole_name FROM tablename;

Here || is the concat operator used for concatenating them to single column and ('') inside || used for space between two columns.

Why java.security.NoSuchProviderException No such provider: BC?

you can add security provider by editing java.security by adding security.provider.=org.bouncycastle.jce.provider.BouncyCastleProvider

or add a line in your top of your class

Security.addProvider(new BouncyCastleProvider());

you can use below line to specify provider while specifying algorithms

Cipher cipher = Cipher.getInstance("AES", "SunJCE");

if you are using other provider like Bouncy Castle then

Cipher cipher =  Cipher.getInstance("AES", "BC");

How to change the hosts file on android

You have root, but you still need to remount /system to be read/write

$ adb shell
$ su
$ mount -o rw,remount -t yaffs2 /dev/block/mtdblock3 /system

Go here for more information: Mount a filesystem read-write.

Difference between SET autocommit=1 and START TRANSACTION in mysql (Have I missed something?)

Being aware of the transaction (autocommit, explicit and implicit) handling for your database can save you from having to restore data from a backup.

Transactions control data manipulation statement(s) to ensure they are atomic. Being "atomic" means the transaction either occurs, or it does not. The only way to signal the completion of the transaction to database is by using either a COMMIT or ROLLBACK statement (per ANSI-92, which sadly did not include syntax for creating/beginning a transaction so it is vendor specific). COMMIT applies the changes (if any) made within the transaction. ROLLBACK disregards whatever actions took place within the transaction - highly desirable when an UPDATE/DELETE statement does something unintended.

Typically individual DML (Insert, Update, Delete) statements are performed in an autocommit transaction - they are committed as soon as the statement successfully completes. Which means there's no opportunity to roll back the database to the state prior to the statement having been run in cases like yours. When something goes wrong, the only restoration option available is to reconstruct the data from a backup (providing one exists). In MySQL, autocommit is on by default for InnoDB - MyISAM doesn't support transactions. It can be disabled by using:

SET autocommit = 0

An explicit transaction is when statement(s) are wrapped within an explicitly defined transaction code block - for MySQL, that's START TRANSACTION. It also requires an explicitly made COMMIT or ROLLBACK statement at the end of the transaction. Nested transactions is beyond the scope of this topic.

Implicit transactions are slightly different from explicit ones. Implicit transactions do not require explicity defining a transaction. However, like explicit transactions they require a COMMIT or ROLLBACK statement to be supplied.

Conclusion

Explicit transactions are the most ideal solution - they require a statement, COMMIT or ROLLBACK, to finalize the transaction, and what is happening is clearly stated for others to read should there be a need. Implicit transactions are OK if working with the database interactively, but COMMIT statements should only be specified once results have been tested & thoroughly determined to be valid.

That means you should use:

SET autocommit = 0;

START TRANSACTION;
  UPDATE ...;

...and only use COMMIT; when the results are correct.

That said, UPDATE and DELETE statements typically only return the number of rows affected, not specific details. Convert such statements into SELECT statements & review the results to ensure correctness prior to attempting the UPDATE/DELETE statement.

Addendum

DDL (Data Definition Language) statements are automatically committed - they do not require a COMMIT statement. IE: Table, index, stored procedure, database, and view creation or alteration statements.

$rootScope.$broadcast vs. $scope.$emit

Use RxJS in a Service

What about in a situation where you have a Service that's holding state for example. How could I push changes to that Service, and other random components on the page be aware of such a change? Been struggling with tackling this problem lately

Build a service with RxJS Extensions for Angular.

<script src="//unpkg.com/angular/angular.js"></script>
<script src="//unpkg.com/rx/dist/rx.all.js"></script>
<script src="//unpkg.com/rx-angular/dist/rx.angular.js"></script>
var app = angular.module('myApp', ['rx']);

app.factory("DataService", function(rx) {
  var subject = new rx.Subject(); 
  var data = "Initial";

  return {
      set: function set(d){
        data = d;
        subject.onNext(d);
      },
      get: function get() {
        return data;
      },
      subscribe: function (o) {
         return subject.subscribe(o);
      }
  };
});

Then simply subscribe to the changes.

app.controller('displayCtrl', function(DataService) {
  var $ctrl = this;

  $ctrl.data = DataService.get();
  var subscription = DataService.subscribe(function onNext(d) {
      $ctrl.data = d;
  });

  this.$onDestroy = function() {
      subscription.dispose();
  };
});

Clients can subscribe to changes with DataService.subscribe and producers can push changes with DataService.set.

The DEMO on PLNKR.

Trim specific character from a string

You can use a regular expression such as:

var x = "|f|oo||";
var y = x.replace(/^\|+|\|+$/g, "");
alert(y); // f|oo

UPDATE:

Should you wish to generalize this into a function, you can do the following:

var escapeRegExp = function(strToEscape) {
    // Escape special characters for use in a regular expression
    return strToEscape.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
};

var trimChar = function(origString, charToTrim) {
    charToTrim = escapeRegExp(charToTrim);
    var regEx = new RegExp("^[" + charToTrim + "]+|[" + charToTrim + "]+$", "g");
    return origString.replace(regEx, "");
};

var x = "|f|oo||";
var y = trimChar(x, "|");
alert(y); // f|oo

Html: Difference between cell spacing and cell padding

Cellpadding is the amount of space between the outer edges of the table cell and the content of the cell.

Cellspacing is the amount of space in between the individual table cells.

More Details *Link 1*

Link 2

Link 3

How to getElementByClass instead of GetElementById with JavaScript?

adding to CMS's answer, this is a more generic approach of toggle_visibility I've just used myself:

function toggle_visibility(className,display) {
   var elements = getElementsByClassName(document, className),
       n = elements.length;
   for (var i = 0; i < n; i++) {
     var e = elements[i];

     if(display.length > 0) {
       e.style.display = display;
     } else {
       if(e.style.display == 'block') {
         e.style.display = 'none';
       } else {
         e.style.display = 'block';
       }
     }
  }
}

Jackson - Deserialize using generic class

You can wrap it in another class which knows the type of your generic type.

Eg,

class Wrapper {
 private Data<Something> data;
}
mapper.readValue(jsonString, Wrapper.class);

Here Something is a concrete type. You need a wrapper per reified type. Otherwise Jackson does not know what objects to create.

How to add 'libs' folder in Android Studio?

The solution for me was very simple (after 10 hours of searching). Above where your folders are there is a combobox that says "android" click it and choose "Project".

enter image description here

Escaping Double Quotes in Batch Script

The escape character in batch scripts is ^. But for double-quoted strings, double up the quotes:

"string with an embedded "" character"

How to check if a variable is equal to one string or another string?

This does not do what you expect:

if var is 'stringone' or 'stringtwo':
    dosomething()

It is the same as:

if (var is 'stringone') or 'stringtwo':
    dosomething()

Which is always true, since 'stringtwo' is considered a "true" value.

There are two alternatives:

if var in ('stringone', 'stringtwo'):
    dosomething()

Or you can write separate equality tests,

if var == 'stringone' or var == 'stringtwo':
    dosomething()

Don't use is, because is compares object identity. You might get away with it sometimes because Python interns a lot of strings, just like you might get away with it in Java because Java interns a lot of strings. But don't use is unless you really want object identity.

>>> 'a' + 'b' == 'ab'
True
>>> 'a' + 'b' is 'abc'[:2]
False # but could be True
>>> 'a' + 'b' is 'ab'
True  # but could be False

Oracle (ORA-02270) : no matching unique or primary key for this column-list error

We have following script for create new table:

CREATE TABLE new_table
(
id                     NUMBER(32) PRIMARY KEY,
referenced_table_id    NUMBER(32)    NOT NULL,
CONSTRAINT fk_new_table_referenced_table_id
    FOREIGN KEY (referenced_table_id)
        REFERENCES referenced_table (id)
);

and we were getting this error on execute:

[42000][2270] ORA-02270: no matching unique or primary key for this column-list

The issue was due to disabled primary key of referenced table in our case. We have enabled it by

ALTER TABLE referenced_table ENABLE PRIMARY KEY USING INDEX;

after that we created new table using first script without any issues

Parse rfc3339 date strings in Python?

You should have a look at moment which is a python port of the excellent js lib momentjs.

One advantage of it is the support of ISO 8601 strings formats, as well as a generic "% format" :

import moment
time_string='2012-10-09T19:00:55Z'

m = moment.date(time_string, '%Y-%m-%dT%H:%M:%SZ')
print m.format('YYYY-M-D H:M')
print m.weekday

Result:

2012-10-09 19:10
2

You seem to not be depending on "@angular/core". This is an error

The problem I had was that I followed the cli's advice to switch to yarn package management.

Then while following a tutorial I did npm install --save bootstrap, and after that point the error started appearing. Afterwards I did yarn add xxx of course and it worked.

To restore the project's state I removed node_modules and package-lock.json as per this answer and then run yarn install

Signed to unsigned conversion in C - is it always safe?

As was previously answered, you can cast back and forth between signed and unsigned without a problem. The border case for signed integers is -1 (0xFFFFFFFF). Try adding and subtracting from that and you'll find that you can cast back and have it be correct.

However, if you are going to be casting back and forth, I would strongly advise naming your variables such that it is clear what type they are, eg:

int iValue, iResult;
unsigned int uValue, uResult;

It is far too easy to get distracted by more important issues and forget which variable is what type if they are named without a hint. You don't want to cast to an unsigned and then use that as an array index.

Is it possible to get the current spark context settings in PySpark?

Spark 2.1+

spark.sparkContext.getConf().getAll() where spark is your sparksession (gives you a dict with all configured settings)

Combining two expressions (Expression<Func<T, bool>>)

I suggest one more improvement to PredicateBuilder and ExpressionVisitor solutions. I called it UnifyParametersByName and you can find it in MIT library of mine: LinqExprHelper. It allows for combining arbitary lambda expressions. Usually the questions are asked about predicate expression, but this idea extends to projection expressions as well.

The following code employs a method ExprAdres which creates a complicated parametrized expression, using inline lambda. This complicated expression is coded only once, and then reused, thanks to the LinqExprHelper mini-library.

public IQueryable<UbezpExt> UbezpFull
{
    get
    {
        System.Linq.Expressions.Expression<
            Func<UBEZPIECZONY, UBEZP_ADRES, UBEZP_ADRES, UbezpExt>> expr =
            (u, parAdrM, parAdrZ) => new UbezpExt
            {
                Ub = u,
                AdrM = parAdrM,
                AdrZ = parAdrZ,
            };

        // From here an expression builder ExprAdres is called.
        var expr2 = expr
            .ReplacePar("parAdrM", ExprAdres("M").Body)
            .ReplacePar("parAdrZ", ExprAdres("Z").Body);
        return UBEZPIECZONY.Select((Expression<Func<UBEZPIECZONY, UbezpExt>>)expr2);
    }
}

And this is the subexpression building code:

public static Expression<Func<UBEZPIECZONY, UBEZP_ADRES>> ExprAdres(string sTyp)
{
    return u => u.UBEZP_ADRES.Where(a => a.TYP_ADRESU == sTyp)
        .OrderByDescending(a => a.DATAOD).FirstOrDefault();
}

What I tried to achieve was to perform parametrized queries without need to copy-paste and with ability to use inline lambdas, which are so pretty. Without all these helper-expression stuff, I would be forced to create whole query in one go.

checking if number entered is a digit in jquery

Forget regular expressions. JavaScript has a builtin function for this: isNaN():

isNaN(123)           // false
isNaN(-1.23)         // false
isNaN(5-2)           // false
isNaN(0)             // false
isNaN("100")         // false
isNaN("Hello")       // true
isNaN("2005/12/12")  // true

Just call it like so:

if (isNaN( $("#whatever").val() )) {
    // It isn't a number
} else {
    // It is a number
}

css ellipsis on second line

What a shame that you can't get it to work over two lines! Would be awesome if the element was display block and had a height set to 2em or something, and when the text overflowed it would show an ellipsis!

For a single liner you can use:

.show-ellipsis {
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}

For multiple lines maybe you could use a Polyfill such as jQuery autoellipsis which is on github http://pvdspek.github.com/jquery.autoellipsis/

jQuery vs document.querySelectorAll

$("#id") vs document.querySelectorAll("#id")

The deal is with the $() function it makes an array and then breaks it up for you but with document.querySelectorAll() it makes an array and you have to break it up.

Call Python function from JavaScript code

You cannot run .py files from JavaScript without the Python program like you cannot open .txt files without a text editor. But the whole thing becomes a breath with a help of a Web API Server (IIS in the example below).

  1. Install python and create a sample file test.py

    import sys
    # print sys.argv[0] prints test.py
    # print sys.argv[1] prints your_var_1
    
    def hello():
        print "Hi" + " " + sys.argv[1]
    
    if __name__ == "__main__":
        hello()
    
  2. Create a method in your Web API Server

    [HttpGet]
    public string SayHi(string id)
    {
        string fileName = HostingEnvironment.MapPath("~/Pyphon") + "\\" + "test.py";          
    
        Process p = new Process();
        p.StartInfo = new ProcessStartInfo(@"C:\Python27\python.exe", fileName + " " + id)
        {
            RedirectStandardOutput = true,
            UseShellExecute = false,
            CreateNoWindow = true
        };
        p.Start();
    
        return p.StandardOutput.ReadToEnd();                  
    }
    
  3. And now for your JavaScript:

    function processSayingHi() {          
       var your_param = 'abc';
       $.ajax({
           url: '/api/your_controller_name/SayHi/' + your_param,
           type: 'GET',
           success: function (response) {
               console.log(response);
           },
           error: function (error) {
               console.log(error);
           }
        });
    }
    

Remember that your .py file won't run on your user's computer, but instead on the server.

Regular expression for matching HH:MM time format

Amazingly I found actually all of these don't quite cover it, as they don't work for shorter format midnight of 0:0 and a few don't work for 00:00 either, I used and tested the following:

^([0-9]|0[0-9]|1?[0-9]|2[0-3]):[0-5]?[0-9]$

Assign result of dynamic sql to variable

You could use sp_executesql instead of exec. That allows you to specify an output parameter.

declare @out_var varchar(max);
execute sp_executesql 
    N'select @out_var = ''hello world''', 
    N'@out_var varchar(max) OUTPUT', 
    @out_var = @out_var output;
select @out_var;

This prints "hello world".

Pass array to where in Codeigniter Active Record

From the Active Record docs:

$this->db->where_in();

Generates a WHERE field IN ('item', 'item') SQL query joined with AND if appropriate

$names = array('Frank', 'Todd', 'James');
$this->db->where_in('username', $names);
// Produces: WHERE username IN ('Frank', 'Todd', 'James')

Simulate delayed and dropped packets on Linux

iptables(8) has a statistic match module that can be used to match every nth packet. To drop this packet, just append -j DROP.

How to check if mysql database exists

Golang solution

create a test package and add:

import "database/sql"

// testing database creation
func TestCreate(t *testing.T){
    Createdb("*Testdb") // This just calls the **sql.DB obect *Testdb 
    db,err := sql.Open("mysql", "root:root@tcp(127.0.0.1:3306)/*Testdb")
    if err != nil{
        panic(err)
    }
    defer db.Close()
    _, err = db.Exec("USE *Testdb")
    if err != nil{
        t.Error("Database not Created")
    }

} 

How to add 20 minutes to a current date?

Just get the millisecond timestamp and add 20 minutes to it:

twentyMinutesLater = new Date(currentDate.getTime() + (20*60*1000))

Display string multiple times

The accepted answer is short and sweet, but here is an alternate syntax allowing to provide a separator in Python 3.x.

print(*3*('-',), sep='_')

Compare a string using sh shell

eq is used to compare integers use equal '=' instead , example:

if [ 'AAA' = 'ABC' ];
then 
    echo "the same" 
else 
    echo "not the same"
fi

good luck

CSS Float: Floating an image to the left of the text

Just need to float both elements left:

.post-container{
    margin: 20px 20px 0 0;  
    border:5px solid #333;
}

.post-thumb img {
    float: left;
}

.post-content {
    float: left;
}

Edit: actually, you do not need the width, just float both left

import an array in python

(I know the question is old, but I think this might be good as a reference for people with similar questions)

If you want to load data from an ASCII/text file (which has the benefit or being more or less human-readable and easy to parse in other software), numpy.loadtxt is probably what you want:

If you just want to quickly save and load numpy arrays/matrices to and from a file, take a look at numpy.save and numpy.load:

How do I import an SQL file using the command line in MySQL?

You do not need to specify the name of the database on the command line if the .sql file contains CREATE DATABASE IF NOT EXISTS db_name and USE db_name statements.

Just make sure you are connecting with a user that has the permissions to create the database, if the database mentioned in the .sql file does not exist.

How to update PATH variable permanently from Windows command line?

I caution against using the command

setx PATH "%PATH%;C:\Something\bin"

to modify the PATH variable because of a "feature" of its implementation. On many (most?) installations these days the variable will be lengthy - setx will truncate the stored string to 1024 bytes, potentially corrupting the PATH (see the discussion here).

(I signed up specifically to flag this issue, and so lack the site reputation to directly comment on the answer posted on May 2 '12. My thanks to beresfordt for adding such a comment)

Custom UITableViewCell from nib in Swift

Here's my approach using Swift 2 and Xcode 7.3. This example will use a single ViewController to load two .xib files -- one for a UITableView and one for the UITableCellView.

enter image description here

For this example you can drop a UITableView right into an empty TableNib.xib file. Inside, set the file's owner to your ViewController class and use an outlet to reference the tableView.

enter image description here

and

enter image description here

Now, in your view controller, you can delegate the tableView as you normally would, like so

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

    @IBOutlet weak var tableView: UITableView!

    ...

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

        // Table view delegate
        self.tableView.delegate = self
        self.tableView.dataSource = self

        ...

To create your Custom cell, again, drop a Table View Cell object into an empty TableCellNib.xib file. This time, in the cell .xib file you don't have to specify an "owner" but you do need to specify a Custom Class and an identifier like "TableCellId"

enter image description here enter image description here

Create your subclass with whatever outlets you need like so

class TableCell: UITableViewCell {

    @IBOutlet weak var nameLabel: UILabel!

}

Finally... back in your View Controller, you can load and display the entire thing like so

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

    // First load table nib
    let bundle = NSBundle(forClass: self.dynamicType)
    let tableNib = UINib(nibName: "TableNib", bundle: bundle)
    let tableNibView = tableNib.instantiateWithOwner(self, options: nil)[0] as! UIView

    // Then delegate the TableView
    self.tableView.delegate = self
    self.tableView.dataSource = self

    // Set resizable table bounds
    self.tableView.frame = self.view.bounds
    self.tableView.autoresizingMask = [.FlexibleWidth, .FlexibleHeight]

    // Register table cell class from nib
    let cellNib = UINib(nibName: "TableCellNib", bundle: bundle)
    self.tableView.registerNib(cellNib, forCellReuseIdentifier: self.tableCellId)

    // Display table with custom cells
    self.view.addSubview(tableNibView)

}

The code shows how you can simply load and display a nib file (the table), and second how to register a nib for cell use.

Hope this helps!!!

Which is the preferred way to concatenate a string in Python?

In Python >= 3.6, the new f-string is an efficient way to concatenate a string.

>>> name = 'some_name'
>>> number = 123
>>>
>>> f'Name is {name} and the number is {number}.'
'Name is some_name and the number is 123.'

Why is it faster to check if dictionary contains the key, rather than catch the exception in case it doesn't?

Dictionaries are specifically designed to do super fast key lookups. They are implemented as hashtables and the more entries the faster they are relative to other methods. Using the exception engine is only supposed to be done when your method has failed to do what you designed it to do because it is a large set of object that give you a lot of functionality for handling errors. I built an entire library class once with everything surrounded by try catch blocks once and was appalled to see the debug output which contained a seperate line for every single one of over 600 exceptions!

Round up double to 2 decimal places

if you give it 234.545332233 it will give you 234.54

let textData = Double(myTextField.text!)!
let text = String(format: "%.2f", arguments: [textData])
mylabel.text = text

Java String encoding (UTF-8)

How is this different from the following?

This line of code here:

String newString = new String(oldString.getBytes("UTF-8"), "UTF-8"));

constructs a new String object (i.e. a copy of oldString), while this line of code:

String newString = oldString;

declares a new variable of type java.lang.String and initializes it to refer to the same String object as the variable oldString.

Is there any scenario in which the two lines will have different outputs?

Absolutely:

String newString = oldString;
boolean isSameInstance = newString == oldString; // isSameInstance == true

vs.

String newString = new String(oldString.getBytes("UTF-8"), "UTF-8"));
 // isSameInstance == false (in most cases)    
boolean isSameInstance = newString == oldString;

a_horse_with_no_name (see comment) is right of course. The equivalent of

String newString = new String(oldString.getBytes("UTF-8"), "UTF-8"));

is

String newString = new String(oldString);

minus the subtle difference wrt the encoding that Peter Lawrey explains in his answer.

MetadataException: Unable to load the specified metadata resource

I was having problems with this same error message. My issue was resolved by closing and re-opening Visual Studio 2010.

Send attachments with PHP Mail()?

HTML Code:

<form enctype="multipart/form-data" method="POST" action=""> 
    <label>Your Name <input type="text" name="sender_name" /> </label> 
    <label>Your Email <input type="email" name="sender_email" /> </label> 
    <label>Your Contact Number <input type="tel" name="contactnumber" /> </label>
    <label>Subject <input type="text" name="subject" /> </label> 
    <label>Message <textarea name="description"></textarea> </label> 
    <label>Attachment <input type="file" name="attachment" /></label> 
    <label><input type="submit" name="button" value="Submit" /></label> 
</form> 

PHP Code:

<?php
if($_POST['button']){
{
    //Server Variables
    $server_name = "Your Name";
    $server_mail = "[email protected]";

    //Name Attributes of HTML FORM
    $sender_email = "sender_email";
    $sender_name = "sender_name";
    $contact = "contactnumber";
    $mail_subject = "subject";
    $input_file = "attachment";
    $message = "description";

    //Fetching HTML Values
    $sender_name = $_POST[$sender_name];
    $sender_mail = $_POST[$sender_email];
    $message = $_POST[$message];
    $contact= $_POST[$contact];
    $mail_subject = $_POST[$mail_subject];

    //Checking if File is uploaded
    if(isset($_FILES[$input_file])) 
    { 
        //Main Content
        $main_subject = "Subject seen on server's mail";
        $main_body = "Hello $server_name,<br><br> 
        $sender_name ,contacted you through your website and the details are as below: <br><br> 
        Name : $sender_name <br> 
        Contact Number : $contact <br> 
        Email : $sender_mail <br> 
        Subject : $mail_subject <br> 
        Message : $message.";

        //Reply Content
        $reply_subject = "Subject seen on sender's mail";
        $reply_body = "Hello $sender_name,<br> 
        \t Thank you for filling the contact form. We will revert back to you shortly.<br><br>
        This is an auto generated mail sent from our Mail Server.<br>
        Please do not reply to this mail.<br>
        Regards<br>
        $server_name";

//#############################DO NOT CHANGE ANYTHING BELOW THIS LINE#############################
        $filename= $_FILES[$input_file]['name'];
        $file = chunk_split(base64_encode(file_get_contents($_FILES[$input_file]['tmp_name'])));
        $uid = md5(uniqid(time()));
        //Sending mail to Server
        $retval = mail($server_mail, $main_subject, "--$uid\r\nContent-type:text/html; charset=iso-8859-1\r\nContent-Transfer-Encoding: 7bit\r\n\r\n $main_body \r\n\r\n--$uid\r\nContent-Type: application/octet-stream; name=\"$filename\"\r\nContent-Transfer-Encoding: base64\r\nContent-Disposition: attachment; filename=\"$filename\"\r\n\r\n$file\r\n\r\n--$uid--", "From: $sender_name <$sender_mail>\r\nReply-To: $sender_mail\r\nMIME-Version: 1.0\r\nContent-Type: multipart/mixed; boundary=\"$uid\"\r\n\r\n");
        //Sending mail to Sender
        $retval = mail($sender_mail, $reply_subject, $reply_body , "From: $server_name<$server_mail>\r\nMIME-Version: 1.0\r\nContent-type: text/html\r\n");
//#############################DO NOT CHANGE ANYTHING ABOVE THIS LINE#############################

        //Output
        if ($retval == true) {
            echo "Message sent successfully...";
            echo "<script>window.location.replace('index.html');</script>";
        } else {
            echo "Error<br>";
            echo "Message could not be sent...Try again later";
            echo "<script>window.location.replace('index.html');</script>";
        }
    }else{
        echo "Error<br>";
        echo "File Not Found";
    }
}else{
    echo "Error<br>";
    echo "Unauthorised Access";
}

npm install Error: rollbackFailedOptional

Try this all command answered here to solve the problem https://stackoverflow.com/a/54173142/12142401 if problem persists Do the following Steps

Completely Uninstall the nodejs checkout this answer for complete uninstallation of nodejs https://stackoverflow.com/a/20711410/12142401

Download the updated nodejs setup from their website Install it in any drive but not on previously installed drive like if you installed in C drive then install in D,S,G Drive Run your npm command it will completely work fine

log4j configuration via JVM argument(s)?

Late to the party as since 2015, Log4J 1.x has reached EOL.

Log4J 2.x onwards the JVM option should be -Dlog4j.configurationFile=<filename>


P.S. <filename> could be a file relative to the class path without the file: as suggested in the other answers.

How to implement the Java comparable interface?

While you are in it, I suggest to remember some key facts about compareTo() methods

  1. CompareTo must be in consistent with equals method e.g. if two objects are equal via equals() , there compareTo() must return zero otherwise if those objects are stored in SortedSet or SortedMap they will not behave properly.

  2. CompareTo() must throw NullPointerException if current object get compared to null object as opposed to equals() which return false on such scenario.

Read more: http://javarevisited.blogspot.com/2011/11/how-to-override-compareto-method-in.html#ixzz4B4EMGha3

Install Visual Studio 2013 on Windows 7

Visual Studio 2013 System Requirements

Supported Operating Systems:

  • Windows 8.1 (x86 and x64)
  • Windows 8 (x86 and x64)
  • Windows 7 SP1 (x86 and x64)
  • Windows Server 2012 R2 (x64)
  • Windows Server 2012 (x64)
  • Windows Server 2008 R2 SP1 (x64)

Hardware requirements:

  • 1.6 GHz or faster processor
  • 1 GB of RAM (1.5 GB if running on a virtual machine)
  • 20 GB of available hard disk space
  • 5400 RPM hard disk drive
  • DirectX 9-capable video card that runs at 1024 x 768 or higher display resolution

Additional Requirements for the laptop:

  • Internet Explorer 10
  • KB2883200 (available through Windows Update) is required

And don't forget to reboot after updating your windows

How to print a string in C++

While using string, the best possible way to print your message is:

#include <iostream>
#include <string>
using namespace std;

int main(){
  string newInput;
  getline(cin, newInput);
  cout<<newInput;
  return 0;
}


this can simply do the work instead of doing the method you adopted.

From ND to 1D arrays

Use np.ravel (for a 1D view) or np.ndarray.flatten (for a 1D copy) or np.ndarray.flat (for an 1D iterator):

In [12]: a = np.array([[1,2,3], [4,5,6]])

In [13]: b = a.ravel()

In [14]: b
Out[14]: array([1, 2, 3, 4, 5, 6])

Note that ravel() returns a view of a when possible. So modifying b also modifies a. ravel() returns a view when the 1D elements are contiguous in memory, but would return a copy if, for example, a were made from slicing another array using a non-unit step size (e.g. a = x[::2]).

If you want a copy rather than a view, use

In [15]: c = a.flatten()

If you just want an iterator, use np.ndarray.flat:

In [20]: d = a.flat

In [21]: d
Out[21]: <numpy.flatiter object at 0x8ec2068>

In [22]: list(d)
Out[22]: [1, 2, 3, 4, 5, 6]

Converting Varchar Value to Integer/Decimal Value in SQL Server

Table structure...very basic:

create table tabla(ID int, Stuff varchar (50));

insert into tabla values(1, '32.43');
insert into tabla values(2, '43.33');
insert into tabla values(3, '23.22');

Query:

SELECT SUM(cast(Stuff as decimal(4,2))) as result FROM tabla

Or, try this:

SELECT SUM(cast(isnull(Stuff,0) as decimal(12,2))) as result FROM tabla

Working on SQLServer 2008

string.Replace in AngularJs

var oldString = "stackoverflow";
var str=oldString.replace(/stackover/g,"NO");
$scope.newString= str;

It works for me. Use an intermediate variable.

How to pass parameters to maven build using pom.xml?

If we have parameter like below in our POM XML

<version>${project.version}.${svn.version}</version>
  <packaging>war</packaging>

I run maven command line as follows :

mvn clean install package -Dproject.version=10 -Dsvn.version=1

How to bring a window to the front?

There are numerous caveats in the javadoc for the toFront() method which may be causing your problem.

But I'll take a guess anyway, when "only the tab in the taskbar flashes", has the application been minimized? If so the following line from the javadoc may apply:

"If this Window is visible, brings this Window to the front and may make it the focused Window."

Tomcat 7.0.43 "INFO: Error parsing HTTP request header"

I had a similar issue, I was sending a POST request (using RESTClient plugin for Firefox) with data in the request body and was receiving the same message.

In my case this happened because I was trying to use HTTPS protocol in a local tomcat instance where HTTPS was not configured.

Why am I getting Unknown error in line 1 of pom.xml?

In my pom.xml file I had to downgrade the version from 2.1.6.RELEASE for spring-boot-starter-parent artifact to 2.1.4.RELEASE

<parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.6.RELEASE</version>
        <relativePath /> <!-- lookup parent from repository -->
</parent>

to be changed to

<parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.4.RELEASE</version>
        <relativePath /> <!-- lookup parent from repository -->
</parent>

And that weird Unknown error disappeared

Which is the best IDE for Python For Windows

U can use eclipse. but u need to download pydev addon for that.

PackagesNotFoundError: The following packages are not available from current channels:

I was trying to install fancyimpute package for imputation but there was not luck. But when i tried below commands, it got installed: Commands:

conda update conda
conda update anaconda
pip install fancyimpute 

(here i was trying to give command conda install fancyimpute which did't work)

RecyclerView: Inconsistency detected. Invalid item position

I ran into a similar issue and just figured it out. I hard-coded a few examples for a test case but didn't ensure they each returned a unique ID and that caused the below crash for me. Fixing the IDs resolved the issue, hope this helps someone else!

How to drop rows from pandas data frame that contains a particular string in a particular column?

The below code will give you list of all the rows:-

df[df['C'] != 'XYZ']

To store the values from the above code into a dataframe :-

newdf = df[df['C'] != 'XYZ']

Using JsonConvert.DeserializeObject to deserialize Json to a C# POCO class

Another, and more streamlined, approach to deserializing a camel-cased JSON string to a pascal-cased POCO object is to use the CamelCasePropertyNamesContractResolver.

It's part of the Newtonsoft.Json.Serialization namespace. This approach assumes that the only difference between the JSON object and the POCO lies in the casing of the property names. If the property names are spelled differently, then you'll need to resort to using JsonProperty attributes to map property names.

using Newtonsoft.Json; 
using Newtonsoft.Json.Serialization;

. . .

private User LoadUserFromJson(string response) 
{
    JsonSerializerSettings serSettings = new JsonSerializerSettings();
    serSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
    User outObject = JsonConvert.DeserializeObject<User>(jsonValue, serSettings);

    return outObject; 
}

What is a classpath and how do I set it?

For linux users, and to sum up and add to what others have said here, you should know the following:

  1. $CLASSPATH is what Java uses to look through multiple directories to find all the different classes it needs for your script (unless you explicitly tell it otherwise with the -cp override). Using -cp requires that you keep track of all the directories manually and copy-paste that line every time you run the program (not preferable IMO).

  2. The colon (":") character separates the different directories. There is only one $CLASSPATH and it has all the directories in it. So, when you run "export CLASSPATH=...." you want to include the current value "$CLASSPATH" in order to append to it. For example:

    export CLASSPATH=.
    export CLASSPATH=$CLASSPATH:/usr/share/java/mysql-connector-java-5.1.12.jar
    

    In the first line above, you start CLASSPATH out with just a simple 'dot' which is the path to your current working directory. With that, whenever you run java it will look in the current working directory (the one you're in) for classes. In the second line above, $CLASSPATH grabs the value that you previously entered (.) and appends the path to a mysql dirver. Now, java will look for the driver AND for your classes.

  3. echo $CLASSPATH
    

    is super handy, and what it returns should read like a colon-separated list of all the directories, and .jar files, you want java looking in for the classes it needs.

  4. Tomcat does not use CLASSPATH. Read what to do about that here: https://tomcat.apache.org/tomcat-8.0-doc/class-loader-howto.html

Decompile an APK, modify it and then recompile it

dex2jar with jd-gui will give all the java source files but they are not exactly the same. They are almost equivalent .class files (not 100%). So if you want to change the code for an apk file:

  • decompile using apktool

  • apktool will generate smali(Assembly version of dex) file for every java file with same name.

  • smali is human understandable, make changes in the relevant file, recompile using same apktool(apktool b Nw.apk <Folder Containing Modified Files>)

What is a daemon thread in Java?

In Java, Daemon Threads are one of the types of the thread which does not prevent Java Virtual Machine (JVM) from exiting. The main purpose of a daemon thread is to execute background task especially in case of some routine periodic task or work. With JVM exits, daemon thread also dies.

By setting a thread.setDaemon(true), a thread becomes a daemon thread. However, you can only set this value before the thread start.

How do I convert a number to a numeric, comma-separated formatted string?

Quick & dirty for int to nnn,nnn...

declare @i int = 123456789
select replace(convert(varchar(128), cast(@i as money), 1), '.00', '')
>> 123,456,789

sqlplus error on select from external table: ORA-29913: error in executing ODCIEXTTABLEOPEN callout

When you want to create an external_table, all field's name must be written in UPPERCASE.

Done.

TypeError: Router.use() requires middleware function but got a Object

Simple solution if your are using express and doing

const router = express.Router();

make sure to

module.exports = router ;

at the end of your page

How to detect a textbox's content has changed

This Code detects whenever a textbox's content has changed by the user and modified by Javascript code.

var $myText = jQuery("#textbox");

$myText.data("value", $myText.val());

setInterval(function() {
    var data = $myText.data("value"),
    val = $myText.val();

    if (data !== val) {
        console.log("changed");
        $myText.data("value", val);
    }
}, 100);

How can I remove a specific item from an array?

Your question did not indicate if order or distinct values are a requirement.

If you don't care about order, and will not have the same value in the container more than once, use a Set. It will be way faster, and more succinct.

var aSet = new Set();

aSet.add(1);
aSet.add(2);
aSet.add(3);

aSet.delete(2);

Neither user 10102 nor current process has android.permission.READ_PHONE_STATE

I was experiencing this problem on Samsung devices (fine on others). like zyamys suggested in his/her comment, I added the manifest.permission line but in addition to rather than instead of the original line, so:

<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.Manifest.permission.READ_PHONE_STATE" />

I'm targeting API 22, so don't need to explicitly ask for permissions.

makefile:4: *** missing separator. Stop

If you are using mcedit for makefile edit. you have to see the following mark. enter image description here

Make HTML5 video poster be same size as video itself

I came up with this idea and it works perfectly. Okay so basically we want to get rid of the videos first frame from the display and then resize the poster to the videos actual size. If we then set the dimensions we have completed one of these tasks. Then only one remains. So now, the only way I know to get rid of the first frame is to actually define a poster. However we are going to give the video a faked one, one that doesn't exist. This will result in a blank display with the background transparent. I.e. our parent div's background will be visible.

Simple to use, however it might not work with all web browsers if you want to resize the dimension of the background of the div to the dimension of the video since my code is using "background-size".

HTML/HTML5:

<div class="video_poster">
    <video poster="dasdsadsakaslmklda.jpg" controls>
        <source src="videos/myvideo.mp4" type="video/mp4">
        Your browser does not support the video tag.
    </video>
<div>

CSS:

video{
    width:694px;
    height:390px;
}
.video_poster{
    width:694px;
    height:390px;
    background-size:694px 390px;
    background-image:url(images/myvideo_poster.jpg);
}

Printing with "\t" (tabs) does not result in aligned columns

As mentioned by other folks, the variable length of the string is the issue.

Rather than reinventing the wheel, Apache Commons has a nice, clean solution for this in StringUtils.

StringUtils.rightPad("String to extend",100); //100 is the length you want to pad out to.

Format JavaScript date as yyyy-mm-dd

It is easily accomplished by my date-shortcode package:

const dateShortcode = require('date-shortcode')
dateShortcode.parse('{YYYY-MM-DD}', 'Sun May 11,2014')
//=> '2014-05-11'

Random Number Between 2 Double Numbers

What if one of the values is negative? Wouldn't a better idea be:

double NextDouble(double min, double max)
{
       if (min >= max)
            throw new ArgumentOutOfRangeException();    
       return random.NextDouble() * (Math.Abs(max-min)) + min;
}

Asp.net Hyperlink control equivalent to <a href="#"></a>

I agree with SLaks, but here you go

   <asp:HyperLink id="hyperlink1" 
                  NavigateUrl="#"
                  Text=""
                  runat="server"/> 

or you can alter the href using

hyperlink1.NavigateUrl = "#"; 
hyperlink1.Text = string.empty;

unresolved external symbol __imp__fprintf and __imp____iob_func, SDL2

Microsoft has a special note on this (https://msdn.microsoft.com/en-us/library/bb531344.aspx#BK_CRT):

The printf and scanf family of functions are now defined inline.

The definitions of all of the printf and scanf functions have been moved inline into stdio.h, conio.h, and other CRT headers. This is a breaking change that leads to a linker error (LNK2019, unresolved external symbol) for any programs that declared these functions locally without including the appropriate CRT headers. If possible, you should update the code to include the CRT headers (that is, add #include ) and the inline functions, but if you do not want to modify your code to include these header files, an alternative solution is to add an additional library to your linker input, legacy_stdio_definitions.lib.

To add this library to your linker input in the IDE, open the context menu for the project node, choose Properties, then in the Project Properties dialog box, choose Linker, and edit the Linker Input to add legacy_stdio_definitions.lib to the semi-colon-separated list.

If your project links with static libraries that were compiled with a release of Visual C++ earlier than 2015, the linker might report an unresolved external symbol. These errors might reference internal stdio definitions for _iob, _iob_func, or related imports for certain stdio functions in the form of __imp_*. Microsoft recommends that you recompile all static libraries with the latest version of the Visual C++ compiler and libraries when you upgrade a project. If the library is a third-party library for which source is not available, you should either request an updated binary from the third party or encapsulate your usage of that library into a separate DLL that you compile with the older version of the Visual C++ compiler and libraries.

How to remove an unpushed outgoing commit in Visual Studio?

I fixed it in Github Desktop Application by pushing my changes.

How to automatically insert a blank row after a group of data

This won't work if the data is not sequential (1 2 3 4 but 5 7 3 1 5) as in that case you can't sort it.

Here is how I solve that issue for me:

Column A initial data that needs to contain 5 rows between each number - 5 4 6 8 9

Column B - 1 2 3 4 5 (final number represents the number of empty rows that you need to be between numbers in column A) copy-paste 1-5 in column B as long as you have numbers in column A.

Jump to D column, in D1 type 1. In D2 type this formula - =IF(B2=1,1+D1,D1) Drag it to the same length as column B.

Back to Column C - at C1 cell type this formula - =IF(B1=1,INDIRECT("a"&(D1)),""). Drag it down and we done. Now in column C we have same sequence of numbers as in column A distributed separately by 4 rows.

Java: how do I check if a Date is within a certain range?

That's the correct way. Calendars work the same way. The best I could offer you (based on your example) is this:

boolean isWithinRange(Date testDate) {
    return testDate.getTime() >= startDate.getTime() &&
             testDate.getTime() <= endDate.getTime();
}

Date.getTime() returns the number of milliseconds since 1/1/1970 00:00:00 GMT, and is a long so it's easily comparable.

multiple classes on single element html

It's a good practice if you need them. It's also a good practice is they make sense, so future coders can understand what you're doing.

But generally, no it's not a good practice to attach 10 class names to an object because most likely whatever you're using them for, you could accomplish the same thing with far fewer classes. Probably just 1 or 2.

To qualify that statement, javascript plugins and scripts may append far more classnames to do whatever it is they're going to do. Modernizr for example appends anywhere from 5 - 25 classes to your body tag, and there's a very good reason for it. jQuery UI appends lots of classnames when you use one of the widgets in that library.

Converting 'ArrayList<String> to 'String[]' in Java

Starting from Java-11, one can alternatively use the API Collection.toArray(IntFunction<T[]> generator) to achieve the same as:

List<String> list = List.of("x","y","z");
String[] arrayBeforeJDK11 = list.toArray(new String[0]);
String[] arrayAfterJDK11 = list.toArray(String[]::new); // similar to Stream.toArray

Minimal web server using netcat

Actually, the best way to close gracefully the connection is to send the Content-Length header like following. Client (like curl will close the connection after receiving the data.

DATA="Date: $(date)"; 
LENGTH=$(echo $DATA | wc -c);
echo -e "HTTP/1.1 200 OK\nContent-Length: ${LENGTH}\n\n${DATA}" | nc -l -p 8000;

How to extend available properties of User.Identity

Check out this great blog post by John Atten: ASP.NET Identity 2.0: Customizing Users and Roles

It has great step-by-step info on the whole process. Go read it : )

Here are some of the basics.

Extend the default ApplicationUser class by adding new properties (i.e.- Address, City, State, etc.):

public class ApplicationUser : IdentityUser
{
    public async Task<ClaimsIdentity> 
    GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
    {
        var userIdentity = await manager.CreateIdentityAsync(this,  DefaultAuthenticationTypes.ApplicationCookie);
        return userIdentity;
    }
    public string Address { get; set; }
    public string City { get; set; }
    public string State { get; set; }

    // Use a sensible display name for views:
    [Display(Name = "Postal Code")]
    public string PostalCode { get; set; }

    // Concatenate the address info for display in tables and such:
    public string DisplayAddress
    {
        get
        {
            string dspAddress = string.IsNullOrWhiteSpace(this.Address) ? "" : this.Address;
            string dspCity = string.IsNullOrWhiteSpace(this.City) ? "" : this.City;
            string dspState = string.IsNullOrWhiteSpace(this.State) ? "" : this.State;
            string dspPostalCode = string.IsNullOrWhiteSpace(this.PostalCode) ? "" : this.PostalCode;

            return string.Format("{0} {1} {2} {3}", dspAddress, dspCity, dspState, dspPostalCode);
        }
    }

Then you add your new properties to your RegisterViewModel.

    // Add the new address properties:
    public string Address { get; set; }
    public string City { get; set; }
    public string State { get; set; }

Then update the Register View to include the new properties.

    <div class="form-group">
        @Html.LabelFor(m => m.Address, new { @class = "col-md-2 control-label" })
        <div class="col-md-10">
            @Html.TextBoxFor(m => m.Address, new { @class = "form-control" })
        </div>
    </div>

Then update the Register() method on AccountController with the new properties.

    // Add the Address properties:
    user.Address = model.Address;
    user.City = model.City;
    user.State = model.State;
    user.PostalCode = model.PostalCode;

Remove category & tag base from WordPress url - without a plugin

updated answer:

other solution:
In wp-includes/rewrite.php file, you'll see the code:
$this->category_structure = $this->front . 'category/'; just copy whole function, put in your functions.php and hook it. just change the above line with:
$this->category_structure = $this->front . '/';

How to run only one task in ansible playbook?

There is a way, although not very elegant:

  1. ansible-playbook roles/hadoop_primary/tasks/hadoop_master.yml --step --start-at-task='start hadoop jobtracker services'
  2. You will get a prompt: Perform task: start hadoop jobtracker services (y/n/c)
  3. Answer y
  4. You will get a next prompt, press Ctrl-C

Center content in responsive bootstrap navbar

I think this is what you are looking for. You need to remove the float: left from the inner nav to center it and make it a inline-block.

.navbar .navbar-nav {
  display: inline-block;
  float: none;
  vertical-align: top;
}

.navbar .navbar-collapse {
  text-align: center;
}

http://jsfiddle.net/bdd9U/2/

Edit: if you only want this effect to happen when the nav isn't collapsed surround it in the appropriate media query.

@media (min-width: 768px) {
    .navbar .navbar-nav {
        display: inline-block;
        float: none;
        vertical-align: top;
    }

    .navbar .navbar-collapse {
        text-align: center;
    }
}

http://jsfiddle.net/bdd9U/3/

Regex doesn't work in String.matches()

You can make your pattern case insensitive by doing:

Pattern p = Pattern.compile("[a-z]+", Pattern.CASE_INSENSITIVE);

What exactly is "exit" in PowerShell?

It's a reserved keyword (like return, filter, function, break).

Reference

Also, as per Section 7.6.4 of Bruce Payette's Powershell in Action:

But what happens when you want a script to exit from within a function defined in that script? ... To make this easier, Powershell has the exit keyword.

Of course, as other have pointed out, it's not hard to do what you want by wrapping exit in a function:

PS C:\> function ex{exit}
PS C:\> new-alias ^D ex

Connecting to SQL Server Express - What is my server name?

You should be able to see it in the Services panel. Look for a servicename like Sql Server (MSSQLSERVER). The name in the parentheses is your instance name.

What does Ruby have that Python doesn't, and vice versa?

Ruby has sigils and twigils, Python doesn't.

Edit: And one very important thing that I forgot (after all, the previous was just to flame a little bit :-p):

Python has a JIT compiler (Psyco), a sightly lower level language for writing faster code (Pyrex) and the ability to add inline C++ code (Weave).

Disabling submit button until all fields have values

$('#user_input, #pass_input, #v_pass_input, #email').bind('keyup', function() {
    if(allFilled()) $('#register').removeAttr('disabled');
});

function allFilled() {
    var filled = true;
    $('body input').each(function() {
        if($(this).val() == '') filled = false;
    });
    return filled;
}

JSFiddle with your code, works :)

how to toggle attr() in jquery

For what it's worth.

$('.js-toggle-edit').on('click', function (e) {
    var bool = $('.js-editable').prop('readonly');
    $('.js-editable').prop('readonly', ! bool);
})

Keep in mind you can pass a closure to .prop(), and do a per element check. But in this case it doesn't matter, it's just a mass toggle.

Objective-C: Calling selectors with multiple arguments

Your method signature is:

- (void) myTest:(NSString *)

withAString happens to be the parameter (the name is misleading, it looks like it is part of the selector's signature).

If you call the function in this manner:

[self performSelector:@selector(myTest:) withObject:myString];

It will work.

But, as the other posters have suggested, you may want to rename the method:

- (void)myTestWithAString:(NSString*)aString;

And call:

[self performSelector:@selector(myTestWithAString:) withObject:myString];

IntelliJ IDEA 13 uses Java 1.5 despite setting to 1.7

I had the following property working for me in IntelliJ 2017

  <properties>
        <java.version>1.8</java.version>       
  </properties>

SQL query to find record with ID not in another table

Keeping in mind the points made in @John Woo's comment/link above, this is how I typically would handle it:

SELECT t1.ID, t1.Name 
FROM   Table1 t1
WHERE  NOT EXISTS (
    SELECT TOP 1 NULL
    FROM Table2 t2
    WHERE t1.ID = t2.ID
)

Do I need to pass the full path of a file in another directory to open()?

Yes, you need the full path.

log = open(os.path.join(root, f), 'r')

Is the quick fix. As the comment pointed out, os.walk decends into subdirs so you do need to use the current directory root rather than indir as the base for the path join.

How can I clear or empty a StringBuilder?

StringBuilder s = new StringBuilder();
s.append("a");
s.append("a");
// System.out.print(s); is return "aa"
s.delete(0, s.length());
System.out.print(s.length()); // is return 0

is the easy way.

Bootstrap 3 collapse accordion: collapse all works but then cannot expand all while maintaining data-parent

To keep the accordion nature intact when wanting to also use 'hide' and 'show' functions like .collapse( 'hide' ), you must initialize the collapsible panels with the parent property set in the object with toggle: false before making any calls to 'hide' or 'show'

// initialize collapsible panels
$('#accordion .collapse').collapse({
  toggle: false,
  parent: '#accordion'
});

// show panel one (will collapse others in accordion)
$( '#collapseOne' ).collapse( 'show' );

// show panel two (will collapse others in accordion)
$( '#collapseTwo' ).collapse( 'show' );

// hide panel two (will not collapse/expand others in accordion)
$( '#collapseTwo' ).collapse( 'hide' );

Python NLTK: SyntaxError: Non-ASCII character '\xc3' in file (Sentiment Analysis -NLP)

Add the following to the top of your file # coding=utf-8

If you go to the link in the error you can seen the reason why:

Defining the Encoding

Python will default to ASCII as standard encoding if no other encoding hints are given. To define a source code encoding, a magic comment must be placed into the source files either as first or second line in the file, such as: # coding=

Calling a user defined function in jQuery

_x000D_
_x000D_
function hello(){_x000D_
    console.log("hello")_x000D_
}_x000D_
$('#event-on-keyup').keyup(function(){_x000D_
    hello()_x000D_
})
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script>_x000D_
<input type="text" id="event-on-keyup">
_x000D_
_x000D_
_x000D_

CSS Font "Helvetica Neue"

You can use http://www.fontsquirrel.com/fontface/generator to encode any font for websites. It'll generate the code to include the font.

I don't really use it for fonts over 30px. They look much better as an image (because images are anti-aliased, and some browsers don't anti-alias fonts in the browser).

See: http://www.truetype-typography.com/ttalias.htm

Hope that helps...

Command not found after npm install in zsh

Another thing to try and the answer for me was to uncomment the first export in ~/.zshrc

# If you come from bash you might have to change your $PATH. export PATH=$HOME/bin:/usr/local/bin:$PATH

Remove unwanted parts from strings in a column

data['result'] = data['result'].map(lambda x: x.lstrip('+-').rstrip('aAbBcC'))

Swift - How to hide back button in navigation item?

self.navigationItem.setHidesBackButton(true, animated: false)

How do I determine if my python shell is executing in 32bit or 64bit?

platform.architecture() notes say:

Note: On Mac OS X (and perhaps other platforms), executable files may be universal files containing multiple architectures.

To get at the “64-bitness” of the current interpreter, it is more reliable to query the sys.maxsize attribute:

import sys
is_64bits = sys.maxsize > 2**32

How to send a message to a particular client with socket.io

As the az7ar answer is beautifully said but Let me make it simpler with socket.io rooms. request a server with a unique identifier to join a server. here we are using an email as a unique identifier.

Client Socket.io

socket.on('connect', function () {
  socket.emit('join', {email: [email protected]});
});

When the user joined a server, create a room for that user

Server Socket.io

io.on('connection', function (socket) {
   socket.on('join', function (data) {    
    socket.join(data.email);
  });
});

Now we are all set with joining. let emit something to from the server to room, so that user can listen.

Server Socket.io

io.to('[email protected]').emit('message', {msg: 'hello world.'});

Let finalize the topic with listening to message event to the client side

socket.on("message", function(data) {
  alert(data.msg);
});

The reference from Socket.io rooms

laravel-5 passing variable to JavaScript

Let's say you have a collection named $services that you are passing to the view.

If you need a JS array with the names, you can iterate over this as follows:

<script>
    const myServices = [];
    @foreach ($services as $service)
        myServices.push('{{ $service->name }}');
    @endforeach
</script>

Note: If the string has special characters (like ó or HTML code), you can use {!! $service->name !!}.

If you need an array of objects (with all of the attributes), you can use:

<script>
  const myServices = @json($services);
  // ...
</script>

Note: This blade directive @json is not available for old Laravel versions. You can achieve the same result using json_encode as described in other answers.


Sometimes you don't need to pass a complete collection to the view, and just an array with 1 attribute. If that's your case, you better use $services = Service::pluck('name'); in your Controller.

Dynamic creation of table with DOM

<title>Registration Form</title>
<script>
    var table;

    function check() {
        debugger;
        var name = document.myForm.name.value;
        if (name == "" || name == null) {
            document.getElementById("span1").innerHTML = "Please enter the Name";
            document.myform.name.focus();
            document.getElementById("name").style.border = "2px solid red";
            return false;
        }
        else {
            document.getElementById("span1").innerHTML = "";
            document.getElementById("name").style.border = "2px solid green";
        }

        var age = document.myForm.age.value;
        var ageFormat = /^(([1][8-9])|([2-5][0-9])|(6[0]))$/gm;

        if (age == "" || age == null) {
            document.getElementById("span2").innerHTML = "Please provide Age";
            document.myForm.age.focus();
            document.getElementById("age").style.border = "2px solid red";
            return false;
        }
        else if (!ageFormat.test(age)) {
            document.getElementById("span2").innerHTML = "Age can't be leass than 18 and greater than 60";
            document.myForm.age.focus();
            document.getElementById("age").style.border = "2px solid red";
            return false;
        }
        else {
            document.getElementById("span2").innerHTML = "";
            document.getElementById("age").style.border = "2px solid green";
        }

        var password = document.myForm.password.value;
        if (document.myForm.password.length < 6) {
            alert("Error: Password must contain at least six characters!");
            document.myForm.password.focus();
            document.getElementById("password").style.border = "2px solid red";
            return false;
        }
        re = /[0-9]/g;
        if (!re.test(password)) {
            alert("Error: password must contain at least one number (0-9)!");
            document.myForm.password.focus();
            document.getElementById("password").style.border = "2px solid red";
            return false;
        }
        re = /[a-z]/g;
        if (!re.test(password)) {
            alert("Error: password must contain at least one lowercase letter (a-z)!");
            document.myForm.password.focus();
            document.getElementById("password").style.border = "2px solid red";
            return false;
        }
        re = /[A-Z]/g;
        if (!re.test(password)) {
            alert("Error: password must contain at least one uppercase letter (A-Z)!");
            document.myForm.password.focus();
            document.getElementById("password").style.border = "2px solid red";
            return false;
        }
        re = /[$&+,:;=?@#|'<>.^*()%!-]/g;
        if (!re.test(password)) {
            alert("Error: password must contain at least one special character!");
            document.myForm.password.focus();
            document.getElementById("password").style.border = "2px solid red";
            return false;
        }
        else {
            document.getElementById("span3").innerHTML = "";
            document.getElementById("password").style.border = "2px solid green";

        }

        if (document.getElementById("data") == null)
            createTable();
        else {
            appendRow();
        }
        return true;
    }






    function createTable() {

        var myTableDiv = document.getElementById("myTable");  //indiv
        table = document.createElement("TABLE");   //TABLE??
        table.setAttribute("id", "data");
        table.border = '1';
        myTableDiv.appendChild(table);  //appendChild() insert it in the document (table --> myTableDiv)
        debugger;

        var header = table.createTHead();

        var th0 = table.tHead.appendChild(document.createElement("th"));
        th0.innerHTML = "Name";
        var th1 = table.tHead.appendChild(document.createElement("th"));
        th1.innerHTML = "Age";


        appendRow();

    }

    function appendRow() {
        var name = document.myForm.name.value;
        var age = document.myForm.age.value;


        var rowCount = table.rows.length;
        var row = table.insertRow(rowCount);

        row.insertCell(0).innerHTML = name;
        row.insertCell(1).innerHTML = age;



        clearForm();


    }


    function clearForm() {
        debugger;

        document.myForm.name.value = "";
        document.myForm.password.value = "";
        document.myForm.age.value = "";



    }
    function restrictCharacters(evt) {

        evt = (evt) ? evt : window.event;
        var charCode = (evt.which) ? evt.which : evt.keyCode;
        if (((charCode >= '65') && (charCode <= '90')) || ((charCode >= '97') && (charCode <= '122')) || (charCode == '32')) {
            return true;
        }
        else {
            return false;
        }
    }

</script>



<div>
    <form name="myForm">

        <table id="tableid">

            <tr>
                <th>Name</th>
                <td>
                    <input type="text" name="name" placeholder="Name" id="name" onkeypress="return restrictCharacters(event);" /></td>
                <td><span id="span1"></span></td>
            </tr>

            <tr>
                <th>Age</th>

                <td>
                    <input type="text" onkeypress="return event.charCode === 0 || /\d/.test(String.fromCharCode(event.charCode));" placeholder="Age"
                        name="age" id="age" /></td>
                <td><span id="span2"></span></td>
            </tr>

            <tr>
                <th>Password</th>
                <td>
                    <input type="password" name="password" id="password" placeholder="Password" /></td>
                <td><span id="span3"></span></td>
            </tr>


            <tr>
                <td></td>
                <td>
                    <input type="button" value="Submit" onclick="check();" /></td>
                <td>
                    <input type="reset" name="Reset" /></td>
            </tr>

        </table>
    </form>

    <div id="myTable">
    </div>

</div>

Is it possible to send a variable number of arguments to a JavaScript function?

Update: Since ES6, you can simply use the spread syntax when calling the function:

func(...arr);

Since ES6 also if you expect to treat your arguments as an array, you can also use the spread syntax in the parameter list, for example:

function func(...args) {
  args.forEach(arg => console.log(arg))
}

const values = ['a', 'b', 'c']
func(...values)
func(1, 2, 3)

And you can combine it with normal parameters, for example if you want to receive the first two arguments separately and the rest as an array:

function func(first, second, ...theRest) {
  //...
}

And maybe is useful to you, that you can know how many arguments a function expects:

var test = function (one, two, three) {}; 
test.length == 3;

But anyway you can pass an arbitrary number of arguments...

The spread syntax is shorter and "sweeter" than apply and if you don't need to set the this value in the function call, this is the way to go.

Here is an apply example, which was the former way to do it:

var arr = ['a','b','c'];

function func() {
  console.log(this); // 'test'
  console.log(arguments.length); // 3

  for(var i = 0; i < arguments.length; i++) {
    console.log(arguments[i]);
  }

};

func.apply('test', arr);

Nowadays I only recommend using apply only if you need to pass an arbitrary number of arguments from an array and set the this value. apply takes is the this value as the first arguments, which will be used on the function invocation, if we use null in non-strict code, the this keyword will refer to the Global object (window) inside func, in strict mode, when explicitly using 'use strict' or in ES modules, null will be used.

Also note that the arguments object is not really an Array, you can convert it by:

var argsArray = Array.prototype.slice.call(arguments);

And in ES6:

const argsArray = [...arguments] // or Array.from(arguments)

But you rarely use the arguments object directly nowadays thanks to the spread syntax.

How to pass query parameters with a routerLink

queryParams

queryParams is another input of routerLink where they can be passed like

<a [routerLink]="['../']" [queryParams]="{prop: 'xxx'}">Somewhere</a>

fragment

<a [routerLink]="['../']" [queryParams]="{prop: 'xxx'}" [fragment]="yyy">Somewhere</a>

routerLinkActiveOptions

To also get routes active class set on parent routes:

[routerLinkActiveOptions]="{ exact: false }"

To pass query parameters to this.router.navigate(...) use

let navigationExtras: NavigationExtras = {
  queryParams: { 'session_id': sessionId },
  fragment: 'anchor'
};

// Navigate to the login page with extras
this.router.navigate(['/login'], navigationExtras);

See also https://angular.io/guide/router#query-parameters-and-fragments

UPDATE with CASE and IN - Oracle

You said that budgetpost is alphanumeric. That means it is looking for comparisons against strings. You should try enclosing your parameters in single quotes (and you are missing the final THEN in the Case expression).

UPDATE tab1   
SET budgpost_gr1=   CASE  
                        WHEN (budgpost in ('1001','1012','50055'))  THEN 'BP_GR_A'   
                        WHEN (budgpost in ('5','10','98','0'))  THEN 'BP_GR_B'  
                        WHEN (budgpost in ('11','876','7976','67465')) THEN 'What?'
                        ELSE 'Missing' 
                        END 

How do I find the length of an array?

This is pretty much old and legendary question and there are already many amazing answers out there. But with time there are new functionalities being added to the languages, so we need to keep on updating things as per new features available.

I just noticed any one hasn't mentioned about C++20 yet. So thought to write answer.

C++20

In C++20, there is a new better way added to the standard library for finding the length of array i.e. std:ssize(). This function returns a signed value.

#include <iostream>

int main() {
    int arr[] = {1, 2, 3};
    std::cout << std::ssize(arr);
    return 0;
}

C++17

In C++17 there was a better way (at that time) for the same which is std::size() defined in iterator.

#include <iostream>
#include <iterator> // required for std::size

int main(){
    int arr[] = {1, 2, 3};
    std::cout << "Size is " << std::size(arr);
    return 0;
}

P.S. This method works for vector as well.

Old

This traditional approach is already mentioned in many other answers.

#include <iostream>

int main() {
    int array[] = { 1, 2, 3 };
    std::cout << sizeof(array) / sizeof(array[0]);
    return 0;
}

Just FYI, if you wonder why this approach doesn't work when array is passed to another function. The reason is,

An array is not passed by value in C++, instead the pointer to array is passed. As in some cases passing the whole arrays can be expensive operation. You can test this by passing the array to some function and make some changes to array there and then print the array in main again. You'll get updated results.

And as you would already know, the sizeof() function gives the number of bytes, so in other function it'll return the number of bytes allocated for the pointer rather than the whole array. So this approach doesn't work.

But I'm sure you can find a good way to do this, as per your requirement.

Happy Coding.

How To Set Up GUI On Amazon EC2 Ubuntu server

This can be done. Following are the steps to setup the GUI

Create new user with password login

sudo useradd -m awsgui
sudo passwd awsgui
sudo usermod -aG admin awsgui

sudo vim /etc/ssh/sshd_config # edit line "PasswordAuthentication" to yes

sudo /etc/init.d/ssh restart

Setting up ui based ubuntu machine on AWS.

In security group open port 5901. Then ssh to the server instance. Run following commands to install ui and vnc server:

sudo apt-get update
sudo apt-get install ubuntu-desktop
sudo apt-get install vnc4server

Then run following commands and enter the login password for vnc connection:

su - awsgui

vncserver

vncserver -kill :1

vim /home/awsgui/.vnc/xstartup

Then hit the Insert key, scroll around the text file with the keyboard arrows, and delete the pound (#) sign from the beginning of the two lines under the line that says "Uncomment the following two lines for normal desktop." And on the second line add "sh" so the line reads

exec sh /etc/X11/xinit/xinitrc. 

When you're done, hit Ctrl + C on the keyboard, type :wq and hit Enter.

Then start vnc server again.

vncserver

You can download xtightvncviewer to view desktop(for Ubutnu) from here https://help.ubuntu.com/community/VNC/Clients

In the vnc client, give public DNS plus ":1" (e.g. www.example.com:1). Enter the vnc login password. Make sure to use a normal connection. Don't use the key files.

Additional guide available here: http://www.serverwatch.com/server-tutorials/setting-up-vnc-on-ubuntu-in-the-amazon-ec2-Page-3.html

Mac VNC client can be downloaded from here: https://www.realvnc.com/en/connect/download/viewer/

Port opening on console

sudo iptables -A INPUT -p tcp --dport 5901 -j ACCEPT

If the grey window issue comes. Mostly because of ".vnc/xstartup" file on different user. So run the vnc server also on same user instead of "awsgui" user.

vncserver

Hyphen, underscore, or camelCase as word delimiter in URIs?

The standard best practice for REST APIs is to have a hyphen, not camelcase or underscores.

This comes from Mark Masse's "REST API Design Rulebook" from Oreilly.

In addition, note that Stack Overflow itself uses hyphens in the URL: .../hyphen-underscore-or-camelcase-as-word-delimiter-in-uris

As does WordPress: http://inventwithpython.com/blog/2012/03/18/how-much-math-do-i-need-to-know-to-program-not-that-much-actually

Excel VBA - How to Redim a 2D array?

Here is how I do this.

Dim TAV() As Variant
Dim ArrayToPreserve() as Variant

TAV = ArrayToPreserve
ReDim ArrayToPreserve(nDim1, nDim2)
For i = 0 To UBound(TAV, 1)
    For j = 0 To UBound(TAV, 2)
        ArrayToPreserve(i, j) = TAV(i, j)
    Next j
Next i

Regular expression to match a line that doesn't contain a word

With negative lookahead, regular expression can match something not contains specific pattern. This is answered and explained by Bart Kiers. Great explanation!

However, with Bart Kiers' answer, the lookahead part will test 1 to 4 characters ahead while matching any single character. We can avoid this and let the lookahead part check out the whole text, ensure there is no 'hede', and then the normal part (.*) can eat the whole text all at one time.

Here is the improved regex:

/^(?!.*?hede).*$/

Note the (*?) lazy quantifier in the negative lookahead part is optional, you can use (*) greedy quantifier instead, depending on your data: if 'hede' does present and in the beginning half of the text, the lazy quantifier can be faster; otherwise, the greedy quantifier be faster. However if 'hede' does not present, both would be equal slow.

Here is the demo code.

For more information about lookahead, please check out the great article: Mastering Lookahead and Lookbehind.

Also, please check out RegexGen.js, a JavaScript Regular Expression Generator that helps to construct complex regular expressions. With RegexGen.js, you can construct the regex in a more readable way:

var _ = regexGen;

var regex = _(
    _.startOfLine(),             
    _.anything().notContains(       // match anything that not contains:
        _.anything().lazy(), 'hede' //   zero or more chars that followed by 'hede',
                                    //   i.e., anything contains 'hede'
    ), 
    _.endOfLine()
);

Using Laravel Homestead: 'no input file specified'

I had the same issues

But forgot that the specs said the configuration file would be located at

~/.homestead/Homestead.yaml and was updating ~/Homestead/src/stubs/Homestead.yaml

So the FIX was to update the Homestead.yaml located here at

~/.homestead/Homestead.yaml

Before

sites: - map: homestead.app to: /home/vagrant/Laravel/public

After

sites: - map: homestead.app to: /home/vagrant/Code/mysitename/public

Then I ran
vagrant up --provision

Hope this works for anyone else.

What's the complete range for Chinese characters in Unicode?

May be you would find a complete list through the CJK Unicode FAQ (which does include "Chinese, Japanese, and Korean" characters)

The "East Asian Script" document does mention:

Blocks Containing Han Ideographs

Han ideographic characters are found in five main blocks of the Unicode Standard, as shown in Table 12-2

Table 12-2. Blocks Containing Han Ideographs

Block                                   Range       Comment
CJK Unified Ideographs                  4E00-9FFF   Common
CJK Unified Ideographs Extension A      3400-4DBF   Rare
CJK Unified Ideographs Extension B      20000-2A6DF Rare, historic
CJK Unified Ideographs Extension C      2A700–2B73F Rare, historic
CJK Unified Ideographs Extension D      2B740–2B81F Uncommon, some in current use
CJK Unified Ideographs Extension E      2B820–2CEAF Rare, historic
CJK Compatibility Ideographs            F900-FAFF   Duplicates, unifiable variants, corporate characters
CJK Compatibility Ideographs Supplement 2F800-2FA1F Unifiable variants

Note: the block ranges can evolve over time: latest is in CJK Unified Ideographs.

See also Wikipedia:

DateTime to javascript date

This method is working for me:

   public sCdateToJsDate(cSDate: any): Date {
        // cSDate is '2017-01-24T14:14:55.807'
        var datestr = cSDate.toString();
        var dateAr = datestr.split('-');
        var year = parseInt(dateAr[0]);
        var month = parseInt(dateAr[1])-1;
        var day = parseInt(dateAr[2].substring(0, dateAr[2].indexOf("T")));
        var timestring = dateAr[2].substring(dateAr[2].indexOf("T") + 1);
        var timeAr = timestring.split(":");
        var hour = parseInt(timeAr[0]);
        var min = parseInt(timeAr[1]);
        var sek = parseInt(timeAr[2]);
        var date = new Date(year, month, day, hour, min, sek, 0);
        return date;
    }

HTML - Arabic Support

As mentioned above, by default text editors will not use UTF-8 as the standard encoding for documents. However most editors will allow you to change that in the settings. Even for each specific document.

How to import Maven dependency in Android Studio/IntelliJ?

Android Studio 3

The answers that talk about Maven Central are dated since Android Studio uses JCenter as the default repository center now. Your project's build.gradle file should have something like this:

repositories {
    google()
    jcenter()
}

So as long as the developer has their Maven repository there (which Picasso does), then all you would have to do is add a single line to the dependencies section of your app's build.gradle file.

dependencies {
    // ...
    implementation 'com.squareup.picasso:picasso:2.5.2'
}

git add remote branch

You can check if you got your remote setup right and have the proper permissions with

git ls-remote origin

if you called your remote "origin". If you get an error you probably don't have your security set up correctly such as uploading your public key to github for example. If things are setup correctly, you will get a list of the remote references. Now

git fetch origin

will work barring any other issues like an unplugged network cable.

Once you have that done, you can get any branch you want that the above command listed with

git checkout some-branch

this will create a local branch of the same name as the remote branch and check it out.

How can I parse JSON with C#?

Here are some options without using third party libraries:

// For that you will need to add reference to System.Runtime.Serialization
var jsonReader = JsonReaderWriterFactory.CreateJsonReader(Encoding.UTF8.GetBytes(@"{ ""Name"": ""Jon Smith"", ""Address"": { ""City"": ""New York"", ""State"": ""NY"" }, ""Age"": 42 }"), new System.Xml.XmlDictionaryReaderQuotas());

// For that you will need to add reference to System.Xml and System.Xml.Linq
var root = XElement.Load(jsonReader);
Console.WriteLine(root.XPathSelectElement("//Name").Value);
Console.WriteLine(root.XPathSelectElement("//Address/State").Value);

// For that you will need to add reference to System.Web.Helpers
dynamic json = System.Web.Helpers.Json.Decode(@"{ ""Name"": ""Jon Smith"", ""Address"": { ""City"": ""New York"", ""State"": ""NY"" }, ""Age"": 42 }");
Console.WriteLine(json.Name);
Console.WriteLine(json.Address.State);

See the link for more information about System.Web.Helpers.Json.

Update: Nowadays the easiest way to get the Web.Helpers is to use the NuGet package.


If you don't care about earlier windows versions you can use the classes of the Windows.Data.Json namespace:

// minimum supported version: Win 8
JsonObject root = Windows.Data.Json.JsonValue.Parse(jsonString).GetObject();
Console.WriteLine(root["Name"].GetString());
Console.WriteLine(root["Address"].GetObject()["State"].GetString());

What is "pass-through authentication" in IIS 7?

Normally, IIS would use the process identity (the user account it is running the worker process as) to access protected resources like file system or network.

With passthrough authentication, IIS will attempt to use the actual identity of the user when accessing protected resources.

If the user is not authenticated, IIS will use the application pool identity instead. If pool identity is set to NetworkService or LocalSystem, the actual Windows account used is the computer account.

The IIS warning you see is not an error, it's just a warning. The actual check will be performed at execution time, and if it fails, it'll show up in the log.

Current time formatting with Javascript

To work with the base Date class you can look at MDN for its methods (instead of W3Schools due to this reason). There you can find a good description about every method useful to access each single date/time component and informations relative to whether a method is deprecated or not.

Otherwise you can look at Moment.js that is a good library to use for date and time processing. You can use it to manipulate date and time (such as parsing, formatting, i18n, etc.).

What is a regular expression which will match a valid domain name without a subdomain?

^[a-zA-Z0-9][-a-zA-Z0-9]+[a-zA-Z0-9].[a-z]{2,3}(.[a-z]{2,3})?(.[a-z]{2,3})?$

Examples that work:

stack.com
sta-ck.com
sta---ck.com
9sta--ck.com
sta--ck9.com
stack99.com
99stack.com
sta99ck.com

It will also work for extensions

.com.uk
.co.in
.uk.edu.in

Examples that will not work:

-stack.com

it will work even with the longest domain extension ".versicherung"

javascript get x and y coordinates on mouse click

simple solution is this:

game.js:

document.addEventListener('click', printMousePos, true);
function printMousePos(e){

      cursorX = e.pageX;
      cursorY= e.pageY;
      $( "#test" ).text( "pageX: " + cursorX +",pageY: " + cursorY );
}

How do I create a chart with multiple series using different X values for each series?

You need to use the Scatter chart type instead of Line. That will allow you to define separate X values for each series.

Swing JLabel text change on the running application

import java.awt.*;
import javax.swing.*;
import javax.swing.border.*;
import java.awt.event.*;
public class Test extends JFrame implements ActionListener
{
    private JLabel label;
    private JTextField field;
    public Test()
    {
        super("The title");
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setPreferredSize(new Dimension(400, 90));
        ((JPanel) getContentPane()).setBorder(new EmptyBorder(13, 13, 13, 13) );
        setLayout(new FlowLayout());
        JButton btn = new JButton("Change");
        btn.setActionCommand("myButton");
        btn.addActionListener(this);
        label = new JLabel("flag");
        field = new JTextField(5);
        add(field);
        add(btn);
        add(label);
        pack();
        setLocationRelativeTo(null);
        setVisible(true);
        setResizable(false);
    }
    public void actionPerformed(ActionEvent e)
    {
        if(e.getActionCommand().equals("myButton"))
        {
            label.setText(field.getText());
        }
    }
    public static void main(String[] args)
    {
        new Test();
    }
}

What does "Use of unassigned local variable" mean?

There are many paths through your code whereby your variables are not initialized, which is why the compiler complains.

Specifically, you are not validating the user input for creditPlan - if the user enters a value of anything else than "0","1","2" or "3", then none of the branches indicated will be executed (and creditPlan will not be defaulted to zero as per your user prompt).

As others have mentioned, the compiler error can be avoided by either a default initialization of all derived variables before the branches are checked, OR ensuring that at least one of the branches is executed (viz, mutual exclusivity of the branches, with a fall through else statement).

I would however like to point out other potential improvements:

  • Validate user input before you trust it for use in your code.
  • Model the parameters as a whole - there are several properties and calculations applicable to each plan.
  • Use more appropriate types for data. e.g. CreditPlan appears to have a finite domain and is better suited to an enumeration or Dictionary than a string. Financial data and percentages should always be modelled as decimal, not double to avoid rounding issues, and 'status' appears to be a boolean.
  • DRY up repetitive code. The calculation, monthlyCharge = balance * annualRate * (1/12)) is common to more than one branch. For maintenance reasons, do not duplicate this code.
  • Possibly more advanced, but note that Functions are now first class citizens of C#, so you can assign a function or lambda as a property, field or parameter!.

e.g. here is an alternative representation of your model:

    // Keep all Credit Plan parameters together in a model
    public class CreditPlan
    {
        public Func<decimal, decimal, decimal> MonthlyCharge { get; set; }
        public decimal AnnualRate { get; set; }
        public Func<bool, Decimal> LateFee { get; set; }
    }

    // DRY up repeated calculations
    static private decimal StandardMonthlyCharge(decimal balance, decimal annualRate)
    { 
       return balance * annualRate / 12;
    }

    public static Dictionary<int, CreditPlan> CreditPlans = new Dictionary<int, CreditPlan>
    {
        { 0, new CreditPlan
            {
                AnnualRate = .35M, 
                LateFee = _ => 0.0M, 
                MonthlyCharge = StandardMonthlyCharge
            }
        },
        { 1, new CreditPlan
            {
                AnnualRate = .30M, 
                LateFee = late => late ? 0 : 25.0M,
                MonthlyCharge = StandardMonthlyCharge
            }
        },
        { 2, new CreditPlan
            {
                AnnualRate = .20M, 
                LateFee = late => late ? 0 : 35.0M,
                MonthlyCharge = (balance, annualRate) => balance > 100 
                    ? balance * annualRate / 12
                    : 0
            }
        },
        { 3, new CreditPlan
            {
                AnnualRate = .15M, 
                LateFee = _ => 0.0M,
                MonthlyCharge = (balance, annualRate) => balance > 500 
                    ? (balance - 500) * annualRate / 12
                    : 0
            }
        }
    };

How to set index.html as root file in Nginx?

The answer is to place the root dir to the location directives:

root   /srv/www/ducklington.org/public_html;

ERROR 2003 (HY000): Can't connect to MySQL server on localhost (10061)

Go to Run type services.msc. Check whether MySQL services is running or not. If not, start it manually.

How to convert an OrderedDict into a regular dict in python3

>>> from collections import OrderedDict
>>> OrderedDict([('method', 'constant'), ('data', '1.225')])
OrderedDict([('method', 'constant'), ('data', '1.225')])
>>> dict(OrderedDict([('method', 'constant'), ('data', '1.225')]))
{'data': '1.225', 'method': 'constant'}
>>>

However, to store it in a database it'd be much better to convert it to a format such as JSON or Pickle. With Pickle you even preserve the order!

Android Writing Logs to text File

You should take a look at microlog4android. They have a solution ready to log to a file.

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

Using BeautifulSoup to search HTML for string

text='Python' searches for elements that have the exact text you provided:

import re
from BeautifulSoup import BeautifulSoup

html = """<p>exact text</p>
   <p>almost exact text</p>"""
soup = BeautifulSoup(html)
print soup(text='exact text')
print soup(text=re.compile('exact text'))

Output

[u'exact text']
[u'exact text', u'almost exact text']

"To see if the string 'Python' is located on the page http://python.org":

import urllib2
html = urllib2.urlopen('http://python.org').read()
print 'Python' in html # -> True

If you need to find a position of substring within a string you could do html.find('Python').

What's the difference between "&nbsp;" and " "?

As already mentioned, you will not receive a line break where there is a "no-break space".

Also be wary, that elements containing only a " " may show up incorrectly, where &nbsp; will work. In i.e. 6 at least (as far as I remember, IE7 has the same issue), if you have an empty table element, it will not apply styling, for example borders, to the element, if there is no content, or only white space. So the following will not be rendered with borders:

<td></td>
<td> <td>

Whereas the borders will show up in this example:

<td>& nbsp;</td>

Hmm -had to put in a dummy space to get it to render correctly here