Programs & Examples On #Production

Production is commonly referred to as the stage in software lifecycle where it's available to be used by the intended end user.

How do you deploy Angular apps?

For a quick and cheap way to host an angular app, I have been using the Firbase hosting. It's free on the first tier and very easy to deploy new versions using the Firebase CLI. This article here explains the necessary steps to deploy your production angular 2 app to Firebase: https://medium.com/codingthesmartway-com-blog/hosting-angular-2-applications-on-firebase-f194688c978d

In short, you run ng build --prod which creates a dist folder in the package and that's the folder that gets deployed to Firebase Hosting.

How to create .ipa file using Xcode?

Click Product > Archive from the menu, once this is complete open up the Organiser and click the latest version > Distribute > Save for Enterprise or Ad-Hoc Deployment > Choose correct signing > Save to destination

WARNING in budgets, maximum exceeded for initial

What is Angular CLI Budgets? Budgets is one of the less known features of the Angular CLI. It’s a rather small but a very neat feature!

As applications grow in functionality, they also grow in size. Budgets is a feature in the Angular CLI which allows you to set budget thresholds in your configuration to ensure parts of your application stay within boundaries which you setOfficial Documentation

Or in other words, we can describe our Angular application as a set of compiled JavaScript files called bundles which are produced by the build process. Angular budgets allows us to configure expected sizes of these bundles. More so, we can configure thresholds for conditions when we want to receive a warning or even fail build with an error if the bundle size gets too out of control!

How To Define A Budget? Angular budgets are defined in the angular.json file. Budgets are defined per project which makes sense because every app in a workspace has different needs.

Thinking pragmatically, it only makes sense to define budgets for the production builds. Prod build creates bundles with “true size” after applying all optimizations like tree-shaking and code minimization.

Oops, a build error! The maximum bundle size was exceeded. This is a great signal that tells us that something went wrong…

  1. We might have experimented in our feature and didn’t clean up properly
  2. Our tooling can go wrong and perform a bad auto-import, or we pick bad item from the suggested list of imports
  3. We might import stuff from lazy modules in inappropriate locations
  4. Our new feature is just really big and doesn’t fit into existing budgets

First Approach: Are your files gzipped?

Generally speaking, gzipped file has only about 20% the size of the original file, which can drastically decrease the initial load time of your app. To check if you have gzipped your files, just open the network tab of developer console. In the “Response Headers”, if you should see “Content-Encoding: gzip”, you are good to go.

How to gzip? If you host your Angular app in most of the cloud platforms or CDN, you should not worry about this issue as they probably have handled this for you. However, if you have your own server (such as NodeJS + expressJS) serving your Angular app, definitely check if the files are gzipped. The following is an example to gzip your static assets in a NodeJS + expressJS app. You can hardly imagine this dead simple middleware “compression” would reduce your bundle size from 2.21MB to 495.13KB.

const compression = require('compression')
const express = require('express')
const app = express()
app.use(compression())

Second Approach:: Analyze your Angular bundle

If your bundle size does get too big you may want to analyze your bundle because you may have used an inappropriate large-sized third party package or you forgot to remove some package if you are not using it anymore. Webpack has an amazing feature to give us a visual idea of the composition of a webpack bundle.

enter image description here

It’s super easy to get this graph.

  1. npm install -g webpack-bundle-analyzer
  2. In your Angular app, run ng build --stats-json (don’t use flag --prod). By enabling --stats-json you will get an additional file stats.json
  3. Finally, run webpack-bundle-analyzer ./dist/stats.json and your browser will pop up the page at localhost:8888. Have fun with it.

ref 1: How Did Angular CLI Budgets Save My Day And How They Can Save Yours

ref 2: Optimize Angular bundle size in 4 steps

Django error - matching query does not exist

your line raising the error is here:

comment = Comment.objects.get(pk=comment_id)

you try to access a non-existing comment.

from django.shortcuts import get_object_or_404

comment = get_object_or_404(Comment, pk=comment_id)

Instead of having an error on your server, your user will get a 404 meaning that he tries to access a non existing resource.

Ok up to here I suppose you are aware of this.

Some users (and I'm part of them) let tabs running for long time, if users are authorized to delete data, it may happens. A 404 error may be a better error to handle a deleted resource error than sending an email to the admin.

Other users go to addresses from their history, (same if data have been deleted since it may happens).

How to scale Docker containers in production

Update: 2019-03-11

First of all thanks for those who have upvoted this answer over the years.

Please be aware that this question was asked in August 2013, when Docker was still a very new technology. Since then: Kubernetes was launched on June 2014, Docker swarm was integrated into the Docker engine in Feb 2015, Amazon launched it's container solution, ECS, in April 2015 and Google launched GKE in August 2015. It's fair to say the production container landscape has changed substantially.


The short answer is that you'd have to write your own logic to do this.

I would expect this kind of feature to emerge from the following projects, built on top of docker, and designed to support applications in production:

Update 1

Another related project I recently discovered:

Update 2

The latest release Openstack contains support for managing Docker containers:

Update 3

System for managing Docker instances

And a presentation on how to use tools like Packer, Docker and Serf to deliver an immutable server infrastructure pattern

Update 4

A neat article on how to wire together docker containers using serf:

Update 5

Run Docker on Mesos using the Marathon framework

Mesosphere Docker Developer Tutorial

Update 6

Run Docker on Tsuru as it supports docker-cluster and segregated scheduler deploy

Update 7

Docker-based environments orchestration

maestro-ng

Update 8

decking.io

Update 9

Google kubernetes

Update 10

Redhat have refactored their openshift PAAS to integrate Docker

Update 11

A Docker NodeJS lib wrapping the Docker command line and managing it from a json file.

Update 12

Amazon's new container service enables scaling in the cluster.

Update 13

Strictly speaking Flocker does not "scale" applications, but it is designed to fufil a related function of making stateful containers (running databases services?) portable across multiple docker hosts:

https://clusterhq.com/

Update 14

A project to create portable templates that describe Docker applications:

http://panamax.io/

Update 15

The Docker project is now addressing orchestration natively (See announcement)

Update 16

Spotify Helios

See also:

Update 17

The Openstack project now has a new "container as a service" project called Magnum:

Shows a lot of promise, enables the easy setup of Docker orchestration frameworks like Kubernetes and Docker swarm.

Update 18

Rancher is a project that is maturing rapidly

http://rancher.com/

Nice UI and strong focus on hyrbrid Docker infrastructures

Update 19

The Lattice project is an offshoot of Cloud Foundry for managing container clusters.

Update 20

Docker recently bought Tutum:

https://www.docker.com/tutum

Update 21

Package manager for applications deployed on Kubernetes.

http://helm.sh/

Update 22

Vamp is an open source and self-hosted platform for managing (micro)service oriented architectures that rely on container technology.

http://vamp.io/

Update 23

A Distributed, Highly Available, Datacenter-Aware Scheduler

From the guys that gave us Vagrant and other powerful tools.

Update 24

Container hosting solution for AWS, open source and based on Kubernetes

https://supergiant.io/

Update 25

Apache Mesos based container hosted located in Germany

https://sloppy.io/features/#features

And Docker Inc. also provide a container hosting service called Docker cloud

https://cloud.docker.com/

Update 26

Jelastic is a hosted PAAS service that scales containers automatically.

Single TextView with multiple colored text

Kotlin version of @Swapnil Kotwal's answer.

Android Studio 4.0.1, Kotlin 1.3.72

val greenText = SpannableString("This is green,")
greenText.setSpan(ForegroundColorSpan(resources.getColor(R.color.someGreenColor), null), 0, greenText.length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
yourTextView.text = greenText

val yellowText = SpannableString("this is yellow, ")
yellowText.setSpan(ForegroundColorSpan(resources.getColor(R.color.someYellowColor), null), 0, yellowText.length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
yourTextView.append(yellowText)

val redText = SpannableString("and this is red.")
redText.setSpan(ForegroundColorSpan(resources.getColor(R.color.someRedColor), null), 0, redText.length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
yourTextView.append(redText)

How to get exception message in Python properly

I had the same problem. I think the best solution is to use log.exception, which will automatically print out stack trace and error message, such as:

try:
    pass
    log.info('Success')
except:
    log.exception('Failed')

How do I get the position selected in a RecyclerView?

A different method - using setTag() and getTag() methods of the View class.

  1. use setTag() in the onBindViewHolder method of your adapter

    @Override
    public void onBindViewHolder(myViewHolder viewHolder, int position) {
        viewHolder.mCardView.setTag(position);
    }
    

    where mCardView is defined in the myViewHolder class

    private class myViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
               public View mCardView;
    
               public myViewHolder(View view) {
                   super(view);
                   mCardView = (CardView) view.findViewById(R.id.card_view);
    
                   mCardView.setOnClickListener(this);
               }
           }
    
  2. use getTag() in your OnClickListener implementation

    @Override
    public void onClick(View view) {
        int position = (int) view.getTag();           
    
    //display toast with position of cardview in recyclerview list upon click
    Toast.makeText(view.getContext(),Integer.toString(position),Toast.LENGTH_SHORT).show();
    }
    

see https://stackoverflow.com/a/33027953/4658957 for more details

JavaScript code to stop form submission

Just use a simple button instead of a submit button. And call a JavaScript function to handle form submit:

<input type="button" name="submit" value="submit" onclick="submit_form();"/>

Function within a script tag:

function submit_form() {
    if (conditions) {
        document.forms['myform'].submit();
    }
    else {
        returnToPreviousPage();
    }
}

You can also try window.history.forward(-1);

CSS text-overflow in a table cell?

Specifying a max-width or fixed width doesn't work for all situations, and the table should be fluid and auto-space its cells. That's what tables are for. Works on IE9 and other browsers.

Use this: http://jsfiddle.net/maruxa1j/

_x000D_
_x000D_
table {
    width: 100%;
}
.first {
    width: 50%;
}
.ellipsis {
    position: relative;
}
.ellipsis:before {
    content: '&nbsp;';
    visibility: hidden;
}
.ellipsis span {
    position: absolute;
    left: 0;
    right: 0;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}
_x000D_
<table border="1">
    <thead>
        <tr>
            <th>Header 1</th>
            <th>Header 2</th>
            <th>Header 3</th>
            <th>Header 4</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td class="ellipsis first"><span>This Text Overflows and is too large for its cell.</span></td>
            <td class="ellipsis"><span>This Text Overflows and is too large for its cell.</span></td>
            <td class="ellipsis"><span>This Text Overflows and is too large for its cell.</span></td>
            <td class="ellipsis"><span>This Text Overflows and is too large for its cell.</span></td>
        </tr>
    </tbody>
</table>
_x000D_
_x000D_
_x000D_

IsNumeric function in c#

http://msdn.microsoft.com/en-us/library/wkze6zky.aspx

menu: Project-->Add Reference

click: assemblies, framework

Put a checkmark on Microsoft.VisualBasic.

Hit OK.

That link is for Visual Studio 2013, you can use the "Other versions" dropdown for different versions of visual studio.

In all cases you need to add a reference to the .NET assembly "Microsoft.VisualBasic".

At the top of your c# file you neeed:

using Microsoft.VisualBasic;

Then you can look at writing the code.

The code would be something like:

   private void btnOK_Click(object sender, EventArgs e)
   {
      if ( Information.IsNumeric(startingbudget) )
      {
         MessageBox.Show("This is a number.");
      }
   }

What are ODEX files in Android?

This Blog article explains the internals of ODEX files:

WHAT IS AN ODEX FILE?

In Android file system, applications come in packages with the extension .apk. These application packages, or APKs contain certain .odex files whose supposed function is to save space. These ‘odex’ files are actually collections of parts of an application that are optimized before booting. Doing so speeds up the boot process, as it preloads part of an application. On the other hand, it also makes hacking those applications difficult because a part of the coding has already been extracted to another location before execution.

How do I commit only some files?

If you have already staged files, simply unstage them:

git reset HEAD [file-name-A.ext] [file-name-B.ext]

Then add them bit by bit back in.

Where to find 64 bit version of chromedriver.exe for Selenium WebDriver?

Windows 8 64bit runs both 32bit and 64bit applications. You want chromedriver 32bit for the 32bit version of chrome you're using.

The current release of chromedriver (v2.16) has been mentioned as running much smoother since it's older versions (there were a lot of issues before). This post mentions this and some of the slight differences between chromedriver and running the normal firefox driver:

http://seleniumsimplified.com/2015/07/recent-course-source-code-changes-for-webdriver-2-46-0/

What you mentioned about "doesn't call main method" is an odd remark. You may want to elaborate.

JavaScript adding decimal numbers issue

function add(){
    var first=parseFloat($("#first").val());
    var second=parseFloat($("#second").val());
    $("#result").val(+(first+second).toFixed(2));
}

DEMO.

Passing parameter to controller action from a Html.ActionLink

You are using incorrect overload. You should use this overload

public static MvcHtmlString ActionLink(
    this HtmlHelper htmlHelper,
    string linkText,
    string actionName,
    string controllerName,
    Object routeValues,
    Object htmlAttributes
) 

And the correct code would be

<%= Html.ActionLink("Create New Part", "CreateParts", "PartList", new { parentPartId = 0 }, null)%>

Note that extra parameter at the end. For the other overloads, visit LinkExtensions.ActionLink Method. As you can see there is no string, string, string, object overload that you are trying to use.

How to remove/delete a large file from commit history in Git repository?

Use the BFG Repo-Cleaner, a simpler, faster alternative to git-filter-branch specifically designed for removing unwanted files from Git history.

Carefully follow the usage instructions, the core part is just this:

$ java -jar bfg.jar --strip-blobs-bigger-than 100M my-repo.git

Any files over 100MB in size (that aren't in your latest commit) will be removed from your Git repository's history. You can then use git gc to clean away the dead data:

$ git gc --prune=now --aggressive

The BFG is typically at least 10-50x faster than running git-filter-branch, and generally easier to use.

Full disclosure: I'm the author of the BFG Repo-Cleaner.

Python string.replace regular expression

str.replace() v2|v3 does not recognize regular expressions.

To perform a substitution using a regular expression, use re.sub() v2|v3.

For example:

import re

line = re.sub(
           r"(?i)^.*interfaceOpDataFile.*$", 
           "interfaceOpDataFile %s" % fileIn, 
           line
       )

In a loop, it would be better to compile the regular expression first:

import re

regex = re.compile(r"^.*interfaceOpDataFile.*$", re.IGNORECASE)
for line in some_file:
    line = regex.sub("interfaceOpDataFile %s" % fileIn, line)
    # do something with the updated line

DELETE_FAILED_INTERNAL_ERROR Error while Installing APK

I had same problem in my xiaomi note 4a device. I solved it by turning off MIUI optimization.

Center align "span" text inside a div

You are giving the span a 100% width resulting in it expanding to the size of the parent. This means you can’t center-align it, as there is no room to move it.

You could give the span a set width, then add the margin:0 auto again. This would center-align it.

.left 
{
   background-color: #999999;
   height: 50px;
   width: 24.5%;
}
span.panelTitleTxt 
{
   display:block;
   width:100px;
   height: 100%;
   margin: 0 auto;
}

SQL Server CTE and recursion example

The execution process is really confusing with recursive CTE, I found the best answer at https://technet.microsoft.com/en-us/library/ms186243(v=sql.105).aspx and the abstract of the CTE execution process is as below.

The semantics of the recursive execution is as follows:

  1. Split the CTE expression into anchor and recursive members.
  2. Run the anchor member(s) creating the first invocation or base result set (T0).
  3. Run the recursive member(s) with Ti as an input and Ti+1 as an output.
  4. Repeat step 3 until an empty set is returned.
  5. Return the result set. This is a UNION ALL of T0 to Tn.

create table in postgreSQL

-- Table: "user"

-- DROP TABLE "user";

CREATE TABLE "user"
(
  id bigserial NOT NULL,
  name text NOT NULL,
  email character varying(20) NOT NULL,
  password text NOT NULL,
  CONSTRAINT user_pkey PRIMARY KEY (id)
)
WITH (
  OIDS=FALSE
);
ALTER TABLE "user"
  OWNER TO postgres;

Casting variables in Java

Actually, casting doesn't always work. If the object is not an instanceof the class you're casting it to you will get a ClassCastException at runtime.

Does Internet Explorer 8 support HTML 5?

Does it support

<!DOCTYPE html>

Yes it does.

Perhaps a better question is what modern web features IE8 supports. Some of the best places to answer that are caniuse.com, html5test.com, and browserscope.org.

HTML5 means a lot of different things to different people. These days, it means HTML, CSS, and JavaScript functionality. The term is becoming a bit "Web 2.0"-like.

python multithreading wait till all threads finished

You can have class something like below from which you can add 'n' number of functions or console_scripts you want to execute in parallel passion and start the execution and wait for all jobs to complete..

from multiprocessing import Process

class ProcessParallel(object):
    """
    To Process the  functions parallely

    """    
    def __init__(self, *jobs):
        """
        """
        self.jobs = jobs
        self.processes = []

    def fork_processes(self):
        """
        Creates the process objects for given function deligates
        """
        for job in self.jobs:
            proc  = Process(target=job)
            self.processes.append(proc)

    def start_all(self):
        """
        Starts the functions process all together.
        """
        for proc in self.processes:
            proc.start()

    def join_all(self):
        """
        Waits untill all the functions executed.
        """
        for proc in self.processes:
            proc.join()


def two_sum(a=2, b=2):
    return a + b

def multiply(a=2, b=2):
    return a * b


#How to run:
if __name__ == '__main__':
    #note: two_sum, multiply can be replace with any python console scripts which
    #you wanted to run parallel..
    procs =  ProcessParallel(two_sum, multiply)
    #Add all the process in list
    procs.fork_processes()
    #starts  process execution 
    procs.start_all()
    #wait until all the process got executed
    procs.join_all()

Custom height Bootstrap's navbar

your markup was a bit messed up. Here's the styles you need and proper html

CSS:

.navbar-brand,
.navbar-nav li a {
    line-height: 150px;
    height: 150px;
    padding-top: 0;
}

HTML:

<nav class="navbar navbar-default">
    <div class="navbar-header">
        <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
            <span class="sr-only">Toggle navigation</span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
        </button>

        <a class="navbar-brand" href="#"><img src="img/logo.png" /></a>
    </div>

    <div class="collapse navbar-collapse">
        <ul class="nav navbar-nav">
            <li><a href="">Portfolio</a></li>
            <li><a href="">Blog</a></li>
            <li><a href="">Contact</a></li>
        </ul>
    </div>
</nav>

Or check out the fiddle at: http://jsfiddle.net/TP5V8/1/

Can I add extension methods to an existing static class?

Maybe you could add a static class with your custom namespace and the same class name:

using CLRConsole = System.Console;

namespace ExtensionMethodsDemo
{
    public static class Console
    {
        public static void WriteLine(string value)
        {
            CLRConsole.WriteLine(value);
        }

        public static void WriteBlueLine(string value)
        {
            System.ConsoleColor currentColor = CLRConsole.ForegroundColor;

            CLRConsole.ForegroundColor = System.ConsoleColor.Blue;
            CLRConsole.WriteLine(value);

            CLRConsole.ForegroundColor = currentColor;
        }

        public static System.ConsoleKeyInfo ReadKey(bool intercept)
        {
            return CLRConsole.ReadKey(intercept);
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                Console.WriteBlueLine("This text is blue");   
            }
            catch (System.Exception ex)
            {
                Console.WriteLine(ex.Message);
                Console.WriteLine(ex.StackTrace);
            }

            Console.WriteLine("Press any key to continue...");
            Console.ReadKey(true);
        }
    }
}

Node.js version on the command line? (not the REPL)

On an Arm7 (armhf) device running Debian Stretch, I had to issue either of the following:

$ nodejs -v
$ nodejs -h

The following did not work:

$ node -v
$ node -h
$ apm -v

Hope this helps someone else.

How do I create an HTML table with a fixed/frozen left column and a scrollable body?

If you don't want to touch your current table too much you can make a fake pinned column in front of the table.

The example shows one way of doing it without JS

_x000D_
_x000D_
table {_x000D_
  border-collapse: collapse;_x000D_
  border-spacing: 0;_x000D_
  border: 1px solid #ddd;_x000D_
  min-width: 600px;_x000D_
}_x000D_
_x000D_
.labels {_x000D_
  display:flex;_x000D_
  flex-direction: column_x000D_
}_x000D_
_x000D_
.overflow {_x000D_
  overflow-x: scroll;_x000D_
  min width: 400px;_x000D_
  flex: 1;_x000D_
}_x000D_
_x000D_
.label {_x000D_
  display: flex;_x000D_
  align-items: center;_x000D_
  white-space:nowrap;_x000D_
  padding: 10px;_x000D_
  flex: 1;_x000D_
  border-bottom: 1px solid #ddd;_x000D_
  border-right: 2px solid #ddd;_x000D_
}_x000D_
_x000D_
.label:last-of-type {_x000D_
  overflow-x: scroll;_x000D_
  border-bottom: 0;_x000D_
}_x000D_
_x000D_
td {_x000D_
  border: 1px solid #ddd;_x000D_
  padding: 10px;_x000D_
}_x000D_
_x000D_
.flex {_x000D_
  display:flex;_x000D_
  max-width: 600px;_x000D_
  padding: 0;_x000D_
  border: 5px solid #ddd;_x000D_
}
_x000D_
<div class="flex">_x000D_
  <div class="labels">_x000D_
    <span class="label">Label 1</span>_x000D_
    <span class="label">Lorem ipsum dolor sit amet.</span>_x000D_
    <span class="label">Lorem ipsum dolor.</span>_x000D_
  </div>_x000D_
  <div class="overflow">_x000D_
    <table>_x000D_
      <tr>_x000D_
        <td class="long">Lorem ipsum dolor sit amet consectetur adipisicing</td>_x000D_
        <td class="long">Lorem ipsum dolor sit amet consectetur adipisicing</td>_x000D_
      </tr>_x000D_
      <tr>_x000D_
        <td class="long">Lorem ipsum dolor sit amet consectetur adipisicing</td>_x000D_
        <td class="long">Lorem ipsum dolor sit amet consectetur adipisicing</td>_x000D_
      </tr>_x000D_
      <tr>_x000D_
        <td class="long">Lorem ipsum dolor sit amet consectetur adipisicing</td>_x000D_
        <td class="long">Lorem ipsum dolor sit amet consectetur adipisicing</td>_x000D_
      </tr>_x000D_
  </table>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

What are .iml files in Android Studio?

What are iml files in Android Studio project?

A Google search on iml file turns up:

IML is a module file created by IntelliJ IDEA, an IDE used to develop Java applications. It stores information about a development module, which may be a Java, Plugin, Android, or Maven component; saves the module paths, dependencies, and other settings.

(from this page)

why not to use gradle scripts to integrate with external modules that you add to your project.

You do "use gradle scripts to integrate with external modules", or your own modules.

However, Gradle is not IntelliJ IDEA's native project model — that is separate, held in .iml files and the metadata in .idea/ directories. In Android Studio, that stuff is largely generated out of the Gradle build scripts, which is why you are sometimes prompted to "sync project with Gradle files" when you change files like build.gradle. This is also why you don't bother putting .iml files or .idea/ in version control, as their contents will be regenerated.

If I have a team that work in different IDE's like Eclipse and AS how to make project IDE agnostic?

To a large extent, you can't.

You are welcome to have an Android project that uses the Eclipse-style directory structure (e.g., resources and manifest in the project root directory). You can teach Gradle, via build.gradle, how to find files in that structure. However, other metadata (compileSdkVersion, dependencies, etc.) will not be nearly as easily replicated.

Other alternatives include:

  • Move everybody over to another build system, like Maven, that is equally integrated (or not, depending upon your perspective) to both Eclipse and Android Studio

  • Hope that Andmore takes off soon, so that perhaps you can have an Eclipse IDE that can build Android projects from Gradle build scripts

  • Have everyone use one IDE

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);

YouTube iframe API: how do I control an iframe player that's already in the HTML?

Fiddle Links: Source code - Preview - Small version
Update: This small function will only execute code in a single direction. If you want full support (eg event listeners / getters), have a look at Listening for Youtube Event in jQuery

As a result of a deep code analysis, I've created a function: function callPlayer requests a function call on any framed YouTube video. See the YouTube Api reference to get a full list of possible function calls. Read the comments at the source code for an explanation.

On 17 may 2012, the code size was doubled in order to take care of the player's ready state. If you need a compact function which does not deal with the player's ready state, see http://jsfiddle.net/8R5y6/.

/**
 * @author       Rob W <[email protected]>
 * @website      https://stackoverflow.com/a/7513356/938089
 * @version      20190409
 * @description  Executes function on a framed YouTube video (see website link)
 *               For a full list of possible functions, see:
 *               https://developers.google.com/youtube/js_api_reference
 * @param String frame_id The id of (the div containing) the frame
 * @param String func     Desired function to call, eg. "playVideo"
 *        (Function)      Function to call when the player is ready.
 * @param Array  args     (optional) List of arguments to pass to function func*/
function callPlayer(frame_id, func, args) {
    if (window.jQuery && frame_id instanceof jQuery) frame_id = frame_id.get(0).id;
    var iframe = document.getElementById(frame_id);
    if (iframe && iframe.tagName.toUpperCase() != 'IFRAME') {
        iframe = iframe.getElementsByTagName('iframe')[0];
    }

    // When the player is not ready yet, add the event to a queue
    // Each frame_id is associated with an own queue.
    // Each queue has three possible states:
    //  undefined = uninitialised / array = queue / .ready=true = ready
    if (!callPlayer.queue) callPlayer.queue = {};
    var queue = callPlayer.queue[frame_id],
        domReady = document.readyState == 'complete';

    if (domReady && !iframe) {
        // DOM is ready and iframe does not exist. Log a message
        window.console && console.log('callPlayer: Frame not found; id=' + frame_id);
        if (queue) clearInterval(queue.poller);
    } else if (func === 'listening') {
        // Sending the "listener" message to the frame, to request status updates
        if (iframe && iframe.contentWindow) {
            func = '{"event":"listening","id":' + JSON.stringify(''+frame_id) + '}';
            iframe.contentWindow.postMessage(func, '*');
        }
    } else if ((!queue || !queue.ready) && (
               !domReady ||
               iframe && !iframe.contentWindow ||
               typeof func === 'function')) {
        if (!queue) queue = callPlayer.queue[frame_id] = [];
        queue.push([func, args]);
        if (!('poller' in queue)) {
            // keep polling until the document and frame is ready
            queue.poller = setInterval(function() {
                callPlayer(frame_id, 'listening');
            }, 250);
            // Add a global "message" event listener, to catch status updates:
            messageEvent(1, function runOnceReady(e) {
                if (!iframe) {
                    iframe = document.getElementById(frame_id);
                    if (!iframe) return;
                    if (iframe.tagName.toUpperCase() != 'IFRAME') {
                        iframe = iframe.getElementsByTagName('iframe')[0];
                        if (!iframe) return;
                    }
                }
                if (e.source === iframe.contentWindow) {
                    // Assume that the player is ready if we receive a
                    // message from the iframe
                    clearInterval(queue.poller);
                    queue.ready = true;
                    messageEvent(0, runOnceReady);
                    // .. and release the queue:
                    while (tmp = queue.shift()) {
                        callPlayer(frame_id, tmp[0], tmp[1]);
                    }
                }
            }, false);
        }
    } else if (iframe && iframe.contentWindow) {
        // When a function is supplied, just call it (like "onYouTubePlayerReady")
        if (func.call) return func();
        // Frame exists, send message
        iframe.contentWindow.postMessage(JSON.stringify({
            "event": "command",
            "func": func,
            "args": args || [],
            "id": frame_id
        }), "*");
    }
    /* IE8 does not support addEventListener... */
    function messageEvent(add, listener) {
        var w3 = add ? window.addEventListener : window.removeEventListener;
        w3 ?
            w3('message', listener, !1)
        :
            (add ? window.attachEvent : window.detachEvent)('onmessage', listener);
    }
}

Usage:

callPlayer("whateverID", function() {
    // This function runs once the player is ready ("onYouTubePlayerReady")
    callPlayer("whateverID", "playVideo");
});
// When the player is not ready yet, the function will be queued.
// When the iframe cannot be found, a message is logged in the console.
callPlayer("whateverID", "playVideo");

Possible questions (& answers):

Q: It doesn't work!
A: "Doesn't work" is not a clear description. Do you get any error messages? Please show the relevant code.

Q: playVideo does not play the video.
A: Playback requires user interaction, and the presence of allow="autoplay" on the iframe. See https://developers.google.com/web/updates/2017/09/autoplay-policy-changes and https://developer.mozilla.org/en-US/docs/Web/Media/Autoplay_guide

Q: I have embedded a YouTube video using <iframe src="http://www.youtube.com/embed/As2rZGPGKDY" />but the function doesn't execute any function!
A: You have to add ?enablejsapi=1 at the end of your URL: /embed/vid_id?enablejsapi=1.

Q: I get error message "An invalid or illegal string was specified". Why?
A: The API doesn't function properly at a local host (file://). Host your (test) page online, or use JSFiddle. Examples: See the links at the top of this answer.

Q: How did you know this?
A: I have spent some time to manually interpret the API's source. I concluded that I had to use the postMessage method. To know which arguments to pass, I created a Chrome extension which intercepts messages. The source code for the extension can be downloaded here.

Q: What browsers are supported?
A: Every browser which supports JSON and postMessage.

  • IE 8+
  • Firefox 3.6+ (actually 3.5, but document.readyState was implemented in 3.6)
  • Opera 10.50+
  • Safari 4+
  • Chrome 3+

Related answer / implementation: Fade-in a framed video using jQuery
Full API support: Listening for Youtube Event in jQuery
Official API: https://developers.google.com/youtube/iframe_api_reference

Revision history

  • 17 may 2012
    Implemented onYouTubePlayerReady: callPlayer('frame_id', function() { ... }).
    Functions are automatically queued when the player is not ready yet.
  • 24 july 2012
    Updated and successully tested in the supported browsers (look ahead).
  • 10 october 2013 When a function is passed as an argument, callPlayer forces a check of readiness. This is needed, because when callPlayer is called right after the insertion of the iframe while the document is ready, it can't know for sure that the iframe is fully ready. In Internet Explorer and Firefox, this scenario resulted in a too early invocation of postMessage, which was ignored.
  • 12 Dec 2013, recommended to add &origin=* in the URL.
  • 2 Mar 2014, retracted recommendation to remove &origin=* to the URL.
  • 9 april 2019, fix bug that resulted in infinite recursion when YouTube loads before the page was ready. Add note about autoplay.

How to uninstall Eclipse?

Right click on eclipse icon and click on open file location then delete the eclipse folder from drive(Save backup of your eclipse workspace if you want). Also delete eclipse icon. Thats it..

How to get certain commit from GitHub project

To just download a commit using the 7-digit SHA1 short form do:

Working Example:

https://github.com/python/cpython/archive/31af650.zip  

Description:

 `https://github.com/username/projectname/archive/commitshakey.zip`

If you have the long hash key 31af650ee25f65794b75d4dfefed6fe4758781c1, just get the first 7 chars 31af650. It's the default for GitHub.

How to convert number to words in java

I think this may help you...programme is very simple and works fine

import java.util.*;

public class NumberToWord

{
    public void pw(int n, String ch)
    {
        String one[] = {

        " ", " one", " two", " three", " four", " five", " six", " seven",
                " eight", " Nine", " ten", " eleven", " twelve", " thirteen",
                " fourteen", "fifteen", " sixteen", " seventeen", " eighteen",
                " nineteen" };
        String ten[] = { " ", " ", " twenty", " thirty", " forty", " fifty",
                " sixty", "seventy", " eighty", " ninety" };
        if (n > 19) {
            System.out.print(ten[n / 10] + " " + one[n % 10]);
        } else {
            System.out.print(one[n]);
        }
        if (n > 0)
            System.out.print(ch);

    }
    public static void main(String[] args)

    {
        int n = 0;
        Scanner s = new Scanner(System.in);
        System.out.print("Enter an integer number: ");
        n = s.nextInt();
        if (n <= 0)
            System.out.print("Enter numbers greater than 0");
        else
        {
            NumberToWord a = new NumberToWord();
            System.out.print("After conversion number in words is :");
            a.pw((n / 1000000000), " Hundred");
            a.pw((n / 10000000) % 100, " crore");
            a.pw(((n / 100000) % 100), " lakh");
            a.pw(((n / 1000) % 100), " thousand");
            a.pw(((n / 100) % 10), " hundred");
            a.pw((n % 100), " ");
        }
    }
}

PHP - Move a file into a different folder on the server

The rename function does this

docs rename

rename('image1.jpg', 'del/image1.jpg');

If you want to keep the existing file on the same place you should use copy

docs copy

copy('image1.jpg', 'del/image1.jpg');

If you want to move an uploaded file use the move_uploaded_file, although this is almost the same as rename this function also checks that the given file is a file that was uploaded via the POST, this prevents for example that a local file is moved

docs move_uploaded_file

$uploads_dir = '/uploads';
foreach ($_FILES["pictures"]["error"] as $key => $error) {
    if ($error == UPLOAD_ERR_OK) {
        $tmp_name = $_FILES["pictures"]["tmp_name"][$key];
        $name = $_FILES["pictures"]["name"][$key];
        move_uploaded_file($tmp_name, "$uploads_dir/$name");
    }
}

code snipet from docs

PRINT statement in T-SQL

The Print statement in TSQL is a misunderstood creature, probably because of its name. It actually sends a message to the error/message-handling mechanism that then transfers it to the calling application. PRINT is pretty dumb. You can only send 8000 characters (4000 unicode chars). You can send a literal string, a string variable (varchar or char) or a string expression. If you use RAISERROR, then you are limited to a string of just 2,044 characters. However, it is much easier to use it to send information to the calling application since it calls a formatting function similar to the old printf in the standard C library. RAISERROR can also specify an error number, a severity, and a state code in addition to the text message, and it can also be used to return user-defined messages created using the sp_addmessage system stored procedure. You can also force the messages to be logged.

Your error-handling routines won’t be any good for receiving messages, despite messages and errors being so similar. The technique varies, of course, according to the actual way you connect to the database (OLBC, OLEDB etc). In order to receive and deal with messages from the SQL Server Database Engine, when you’re using System.Data.SQLClient, you’ll need to create a SqlInfoMessageEventHandler delegate, identifying the method that handles the event, to listen for the InfoMessage event on the SqlConnection class. You’ll find that message-context information such as severity and state are passed as arguments to the callback, because from the system perspective, these messages are just like errors.

It is always a good idea to have a way of getting these messages in your application, even if you are just spooling to a file, because there is always going to be a use for them when you are trying to chase a really obscure problem. However, I can’t think I’d want the end users to ever see them unless you can reserve an informational level that displays stuff in the application.

How to check for empty array in vba macro

Here is another way to do it. I have used it in some cases and it's working.

Function IsArrayEmpty(arr As Variant) As Boolean

Dim index As Integer

index = -1
    On Error Resume Next
        index = UBound(arr)
    On Error GoTo 0

If (index = -1) Then IsArrayEmpty = True Else IsArrayEmpty = False

End Function

How can I make a HTML a href hyperlink open a new window?

<a href="#" onClick="window.open('http://www.yahoo.com', '_blank')">test</a>

Easy as that.

Or without JS

<a href="http://yahoo.com" target="_blank">test</a>

How to enable Bootstrap tooltip on disabled button?

If you're desperate (like i was) for tooltips on checkboxes, textboxes and the like, then here is my hackey workaround:

$('input:disabled, button:disabled').after(function (e) {
    d = $("<div>");
    i = $(this);
    d.css({
        height: i.outerHeight(),
        width: i.outerWidth(),
        position: "absolute",
    })
    d.css(i.offset());
    d.attr("title", i.attr("title"));
    d.tooltip();
    return d;
});

Working examples: http://jsfiddle.net/WB6bM/11/

For what its worth, I believe tooltips on disabled form elements is very important to the UX. If you're preventing somebody from doing something, you should tell them why.

What is the best way to dump entire objects to a log in C#?

You could use reflection and loop through all the object properties, then get their values and save them to the log. The formatting is really trivial (you could use \t to indent an objects properties and its values):

MyObject
    Property1 = value
    Property2 = value2
    OtherObject
       OtherProperty = value ...

How to set a cookie to expire in 1 hour in Javascript?

You can write this in a more compact way:

var now = new Date();
now.setTime(now.getTime() + 1 * 3600 * 1000);
document.cookie = "name=value; expires=" + now.toUTCString() + "; path=/";

And for someone like me, who wasted an hour trying to figure out why the cookie with expiration is not set up (but without expiration can be set up) in Chrome, here is in answer:

For some strange reason Chrome team decided to ignore cookies from local pages. So if you do this on localhost, you will not be able to see your cookie in Chrome. So either upload it on the server or use another browser.

Return a string method in C#

You don't have to have a method for that. You could create a property like this instead:

class SalesPerson
{
    string firstName, lastName;
    public string FirstName { get { return firstName; } set { firstName = value; } }
    public string LastName { get { return lastName; } set { lastName = value; } }
    public string FullName { get { return this.FirstName + " " + this.LastName; } }
}

The class could even be shortened to:

class SalesPerson
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string FullName { 
       get { return this.FirstName + " " + this.LastName; } 
    }
}

The property could then be accessed like any other property:

class Program
{
    static void Main(string[] args)
    {
        SalesPerson x = new SalesPerson("John", "Doe");
        Console.WriteLine(x.FullName); // Will print John Doe
    }
}

How can I do DNS lookups in Python, including referring to /etc/hosts?

list( map( lambda x: x[4][0], socket.getaddrinfo( \
     'www.example.com.',22,type=socket.SOCK_STREAM)))

gives you a list of the addresses for www.example.com. (ipv4 and ipv6)

What should be in my .gitignore for an Android Studio project?

Building on my normal Android .gitignore, and after reading through documentation on the Intellij IDEA website and reading posts on StackOverflow, I have constructed the following file:

# built application files
*.apk
*.ap_

# files for the dex VM
*.dex

# Java class files
*.class

# built native files (uncomment if you build your own)
# *.o
# *.so

# generated files
bin/
gen/

# Ignore gradle files
.gradle/
build/

# Local configuration file (sdk path, etc)
local.properties

# Proguard folder generated by Eclipse
proguard/

# Eclipse Metadata
.metadata/

# Mac OS X clutter
*.DS_Store

# Windows clutter
Thumbs.db

# Intellij IDEA (see https://intellij-support.jetbrains.com/entries/23393067)
.idea/workspace.xml
.idea/tasks.xml
.idea/datasources.xml
.idea/dataSources.ids

Also note that as pointed out, the built native files section is primarily useful when you are building your own native code with the Android NDK. If, on the other hand, you are using a third party library that includes these files, you may wish to remove these lines (*.o and *.so) from your .gitignore.

Decoding UTF-8 strings in Python

It's an encoding error - so if it's a unicode string, this ought to fix it:

text.encode("windows-1252").decode("utf-8")

If it's a plain string, you'll need an extra step:

text.decode("utf-8").encode("windows-1252").decode("utf-8")

Both of these will give you a unicode string.

By the way - to discover how a piece of text like this has been mangled due to encoding issues, you can use chardet:

>>> import chardet
>>> chardet.detect(u"And the Hip’s coming, too")
{'confidence': 0.5, 'encoding': 'windows-1252'}

PHP-FPM and Nginx: 502 Bad Gateway

Maybe this answer will help:

nginx error connect to php5-fpm.sock failed (13: Permission denied)

The solution was to replace www-data with nginx in /var/www/php/fpm/pool.d/www.conf

And respectively modify the socket credentials:

$ sudo chmod nginx:nginx /var/run/php/php7.2-fpm.sock

Horizontal swipe slider with jQuery and touch devices support?

Ive found another: http://swipejs.com/

seems to work nicely however I encounter an issue with it when paired with bootstrap on the OS X version of Chrome. If total cross-browser compatibility isn't an issue, then you're golden.

Throw keyword in function's signature

A no throw specification on an inlined function that only returns a member variable and could not possibly throw exceptions may be used by some compilers to do pessimizations (a made-up word for the opposite of optimizations) that can have a detrimental effect on performance. This is described in the Boost literature: Exception-specification

With some compilers a no-throw specification on non-inline functions may be beneficial if the correct optimizations are made and the use of that function impacts performance in a way that it justifies it.

To me it sounds like whether to use it or not is a call made by a very critical eye as part of a performance optimization effort, perhaps using profiling tools.

A quote from the above link for those in a hurry (contains an example of bad unintended effects of specifying throw on an inline function from a naive compiler):

Exception-specification rationale

Exception specifications [ISO 15.4] are sometimes coded to indicate what exceptions may be thrown, or because the programmer hopes they will improve performance. But consider the following member from a smart pointer:

T& operator*() const throw() { return *ptr; }

This function calls no other functions; it only manipulates fundamental data types like pointers Therefore, no runtime behavior of the exception-specification can ever be invoked. The function is completely exposed to the compiler; indeed it is declared inline Therefore, a smart compiler can easily deduce that the functions are incapable of throwing exceptions, and make the same optimizations it would have made based on the empty exception-specification. A "dumb" compiler, however, may make all kinds of pessimizations.

For example, some compilers turn off inlining if there is an exception-specification. Some compilers add try/catch blocks. Such pessimizations can be a performance disaster which makes the code unusable in practical applications.

Although initially appealing, an exception-specification tends to have consequences that require very careful thought to understand. The biggest problem with exception-specifications is that programmers use them as though they have the effect the programmer would like, instead of the effect they actually have.

A non-inline function is the one place a "throws nothing" exception-specification may have some benefit with some compilers.

Importing a CSV file into a sqlite3 database table using Python

#!/usr/bin/python
# -*- coding: utf-8 -*-

import sys, csv, sqlite3

def main():
    con = sqlite3.connect(sys.argv[1]) # database file input
    cur = con.cursor()
    cur.executescript("""
        DROP TABLE IF EXISTS t;
        CREATE TABLE t (COL1 TEXT, COL2 TEXT);
        """) # checks to see if table exists and makes a fresh table.

    with open(sys.argv[2], "rb") as f: # CSV file input
        reader = csv.reader(f, delimiter=',') # no header information with delimiter
        for row in reader:
            to_db = [unicode(row[0], "utf8"), unicode(row[1], "utf8")] # Appends data from CSV file representing and handling of text
            cur.execute("INSERT INTO neto (COL1, COL2) VALUES(?, ?);", to_db)
            con.commit()
    con.close() # closes connection to database

if __name__=='__main__':
    main()

Creating default object from empty value in PHP?

Try using:

$user = (object) null;

How do I set up a private Git repository on GitHub? Is it even possible?

Update (2019, latest)

Since Jan 2019, GitHub allows private repositories for up to three collaborators.

Previous answer:

Here is the comparison for free plans listed by tree main Git Cloud based solutions:

Enter image description here

Here is the comparison for paid plans listed by tree main Git Cloud based solutions:

Enter image description here

Conclusion:

I'm not seeing people mentioning GitLab here, but it seems like the best free private plan for me. I myself am using it with no problems.

GitHub: If you have a student account or want to pay for $7 monthly, GitHub has the biggest community and you can take advantage of it's public repositories, forks, etc.

Bitbucket: If you use other products from Atlassian like Jira or Confluence, Bitbucket works great with them.

GitLab: Everything that I care about (free private repository, number of private repositories, number of collaborators, etc.) are offered for free. This seems like the best choice for me.

Add single element to array in numpy

This command,

numpy.append(a, a[0])

does not alter a array. However, it returns a new modified array. So, if a modification is required, then the following must be used.

a = numpy.append(a, a[0])

Javascript - sort array based on another array

Use intersection of two arrays.

Ex:

var sortArray = ['a', 'b', 'c',  'd', 'e'];

var arrayToBeSort = ['z', 's', 'b',  'e', 'a'];

_.intersection(sortArray, arrayToBeSort) 

=> ['a', 'b', 'e']

if 'z and 's' are out of range of first array, append it at the end of result

Hibernate Query By Example and Projections

The real problem here is that there is a bug in hibernate where it uses select-list aliases in the where-clause:

http://opensource.atlassian.com/projects/hibernate/browse/HHH-817

Just in case someone lands here looking for answers, go look at the ticket. It took 5 years to fix but in theory it'll be in one of the next releases and then I suspect your issue will go away.

PHP - Extracting a property from an array of objects

CODE

<?php

# setup test array.
$cats = array();
$cats[] = (object) array('id' => 15);
$cats[] = (object) array('id' => 18);
$cats[] = (object) array('id' => 23);

function extract_ids($array = array())
{
    $ids = array();
    foreach ($array as $object) {
        $ids[] = $object->id;
    }
    return $ids;
}

$cat_ids = extract_ids($cats);
var_dump($cats);
var_dump($cat_ids);

?>

OUTPUT

# var_dump($cats);
array(3) {
  [0]=>
  object(stdClass)#1 (1) {
    ["id"]=>
    int(15)
  }
  [1]=>
  object(stdClass)#2 (1) {
    ["id"]=>
    int(18)
  }
  [2]=>
  object(stdClass)#3 (1) {
    ["id"]=>
    int(23)
  }
}

# var_dump($cat_ids);
array(3) {
  [0]=>
  int(15)
  [1]=>
  int(18)
  [2]=>
  int(23)
}

I know its using a loop, but it's the simplest way to do it! And using a function it still ends up on a single line.

How to determine day of week by passing specific date?

tl;dr

Using java.time

LocalDate.parse(                               // Generate `LocalDate` object from String input.
             "23/2/2010" ,
             DateTimeFormatter.ofPattern( "d/M/uuuu" ) 
         )                                    
         .getDayOfWeek()                       // Get `DayOfWeek` enum object.
         .getDisplayName(                      // Localize. Generate a String to represent this day-of-week.
             TextStyle.SHORT_STANDALONE ,      // How long or abbreviated. Some languages have an alternate spelling for "standalone" use (not so in English).
             Locale.US                         // Or Locale.CANADA_FRENCH and such. Specify a `Locale` to determine (1) human language for translation, and (2) cultural norms for abbreviation, punctuation, etc.
         ) 

Tue

See this code run live at IdeOne.com (but only Locale.US works there).

java.time

See my example code above, and see the correct Answer for java.time by Przemek.

Ordinal number

if just the day ordinal is desired, how can that be retrieved?

For ordinal number, consider passing around the DayOfWeek enum object instead such as DayOfWeek.TUESDAY. Keep in mind that a DayOfWeek is a smart object, not just a string or mere integer number. Using those enum objects makes your code more self-documenting, ensures valid values, and provides type-safety.

But if you insist, ask DayOfWeek for a number. You get 1-7 for Monday-Sunday per the ISO 8601 standard.

int ordinal = myLocalDate.getDayOfWeek().getValue() ;

Joda-Time

UPDATE: The Joda-Time project is now in maintenance mode. The team advises migrating to the java.time classes. The java.time framework is built into Java 8 (as well as back-ported to Java 6 & 7 and further adapted to Android).

Here is example code using the Joda-Time library version 2.4, as mentioned in the accepted answer by Bozho. Joda-Time is far superior to the java.util.Date/.Calendar classes bundled with Java.

LocalDate

Joda-Time offers the LocalDate class to represent a date-only without any time-of-day or time zone. Just what this Question calls for. The old java.util.Date/.Calendar classes bundled with Java lack this concept.

Parse

Parse the string into a date value.

String input = "23/2/2010";
DateTimeFormatter formatter = DateTimeFormat.forPattern( "d/M/yyyy" );
LocalDate localDate = formatter.parseLocalDate( input );

Extract

Extract from the date value the day of week number and name.

int dayOfWeek = localDate.getDayOfWeek(); // Follows ISO 8601 standard, where Monday = 1, Sunday = 7.
Locale locale = Locale.US;  // Locale specifies the human language to use in determining day-of-week name (Tuesday in English versus Mardi in French).
DateTimeFormatter formatterOutput = DateTimeFormat.forPattern( "E" ).withLocale( locale );
String output = formatterOutput.print( localDate ); // 'E' is code for abbreviation of day-of-week name. See Joda-Time doc.
String outputQuébécois = formatterOutput.withLocale( Locale.CANADA_FRENCH ).print( localDate );

Dump

Dump to console.

System.out.println( "input: " + input );
System.out.println( "localDate: " + localDate ); // Defaults to ISO 8601 formatted strings.
System.out.println( "dayOfWeek: " + dayOfWeek );
System.out.println( "output: " + output );
System.out.println( "outputQuébécois: " + outputQuébécois );

Run

When run.

input: 23/2/2010
localDate: 2010-02-23
dayOfWeek: 2
output: Tue
outputQuébécois: mar.

About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

Angular2 - Focusing a textbox on component load

Directive for autoFocus first field

_x000D_
_x000D_
import {_x000D_
  Directive,_x000D_
  ElementRef,_x000D_
  AfterViewInit_x000D_
} from "@angular/core";_x000D_
_x000D_
@Directive({_x000D_
  selector: "[appFocusFirstEmptyInput]"_x000D_
})_x000D_
export class FocusFirstEmptyInputDirective implements AfterViewInit {_x000D_
  constructor(private el: ElementRef) {}_x000D_
  ngAfterViewInit(): void {_x000D_
    const invalidControl = this.el.nativeElement.querySelector(".ng-untouched");_x000D_
    if (invalidControl) {_x000D_
      invalidControl.focus();_x000D_
    }_x000D_
  }_x000D_
}
_x000D_
_x000D_
_x000D_

Angular 6: How to set response type as text while making http call

Have you tried not setting the responseType and just type casting the response?

This is what worked for me:

/**
 * Client for consuming recordings HTTP API endpoint.
 */
@Injectable({
  providedIn: 'root'
})
export class DownloadUrlClientService {
  private _log = Log.create('DownloadUrlClientService');


  constructor(
    private _http: HttpClient,
  ) {}

  private async _getUrl(url: string): Promise<string> {
    const httpOptions = {headers: new HttpHeaders({'auth': 'false'})};
    // const httpOptions = {headers: new HttpHeaders({'auth': 'false'}), responseType: 'text'};
    const res = await (this._http.get(url, httpOptions) as Observable<string>).toPromise();
    // const res = await (this._http.get(url, httpOptions)).toPromise();
    return res;
  }
}

PHP - Getting the index of a element from a array

an array does not contain index when elements are associative. An array in php can contain mixed values like this:

$var = array("apple", "banana", "foo" => "grape", "carrot", "bar" => "donkey");   
print_r($var);

Gives you:

Array
(
    [0] => apple
    [1] => banana
    [foo] => grape
    [2] => carrot
    [bar] => donkey
)

What are you trying to achieve since you need the index value in an associative array?

Is there are way to make a child DIV's width wider than the parent DIV using CSS?

Assuming the parent has a fixed width, e.g #page { width: 1000px; } and is centered #page { margin: auto; }, you want the child to fit the width of browser viewport you could simply do:

#page {
    margin: auto;
    width: 1000px;
}

.fullwidth {
    margin-left: calc(500px - 50vw); /* 500px is half of the parent's 1000px */
    width: 100vw;
}

Limit number of characters allowed in form input text field

Make it simpler

<input type="text" maxlength="3" />

and use an alert to show that max chars have been used.

Can't use WAMP , port 80 is used by IIS 7.5

I had the same problem a month ago on Windows 10. Whenever I tried to access http://localhost/ it led me to the IIS page. I tried removing the IIS feature from windows features. Once I was sure it was gone, I tried running XAMPP, but it still did not work. I did not want to mess with the configuration files. But from this, I was quite sure it had something to do with my web browser. So, deleted the cache from the web browser I was using (Google Chrome).

To do so, I went to:

Chrome > Settings > Show Advanced Settings > Privacy > Clear browsing data > Clear Cached images and files.

Its almost the same process for any web browsers. Right after that, I was able to run XAMPP without any problem!

Hope it helps!

How Do I 'git fetch' and 'git merge' from a Remote Tracking Branch (like 'git pull')

You don't fetch a branch, you fetch an entire remote:

git fetch origin
git merge origin/an-other-branch

How to post query parameters with Axios?

In my case, the API responded with a CORS error. I instead formatted the query parameters into query string. It successfully posted data and also avoided the CORS issue.

        var data = {};

        const params = new URLSearchParams({
          contact: this.ContactPerson,
          phoneNumber: this.PhoneNumber,
          email: this.Email
        }).toString();

        const url =
          "https://test.com/api/UpdateProfile?" +
          params;

        axios
          .post(url, data, {
            headers: {
              aaid: this.ID,
              token: this.Token
            }
          })
          .then(res => {
            this.Info = JSON.parse(res.data);
          })
          .catch(err => {
            console.log(err);
          });

setting content between div tags using javascript

Try the following:

document.getElementById("successAndErrorMessages").innerHTML="someContent"; 

msdn link for detail : innerHTML Property

How to watch for a route change in AngularJS?

This is for the total beginner... like me:

HTML:

  <ul>
    <li>
      <a href="#"> Home </a>
    </li>
    <li>
      <a href="#Info"> Info </a>
    </li>
  </ul>

  <div ng-app="myApp" ng-controller="MainCtrl">
    <div ng-view>

    </div>
  </div>

Angular:

//Create App
var app = angular.module("myApp", ["ngRoute"]);

//Configure routes
app.config(function ($routeProvider) {
    $routeProvider
      .otherwise({ template: "<p>Coming soon</p>" })
      .when("/", {
        template: "<p>Home information</p>"
      })
      .when("/Info", {
        template: "<p>Basic information</p>"
        //templateUrl: "/content/views/Info.html"
      });
});

//Controller
app.controller('MainCtrl', function ($scope, $rootScope, $location) {
  $scope.location = $location.path();
  $rootScope.$on('$routeChangeStart', function () {
    console.log("routeChangeStart");
   //Place code here:....
   });
});

Hope this helps a total beginner like me. Here is the full working sample:

_x000D_
_x000D_
<html>_x000D_
<head>_x000D_
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script>_x000D_
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular-route.min.js"></script>_x000D_
</head>_x000D_
<body>_x000D_
  <ul>_x000D_
    <li>_x000D_
      <a href="#"> Home </a>_x000D_
    </li>_x000D_
    <li>_x000D_
      <a href="#Info"> Info </a>_x000D_
    </li>_x000D_
  </ul>_x000D_
_x000D_
  <div ng-app="myApp" ng-controller="MainCtrl">_x000D_
    <div ng-view>_x000D_
_x000D_
    </div>_x000D_
  </div>_x000D_
  <script>_x000D_
//Create App_x000D_
var app = angular.module("myApp", ["ngRoute"]);_x000D_
_x000D_
//Configure routes_x000D_
app.config(function ($routeProvider) {_x000D_
    $routeProvider_x000D_
      .otherwise({ template: "<p>Coming soon</p>" })_x000D_
      .when("/", {_x000D_
        template: "<p>Home information</p>"_x000D_
      })_x000D_
      .when("/Info", {_x000D_
        template: "<p>Basic information</p>"_x000D_
        //templateUrl: "/content/views/Info.html"_x000D_
      });_x000D_
});_x000D_
_x000D_
//Controller_x000D_
app.controller('MainCtrl', function ($scope, $rootScope, $location) {_x000D_
  $scope.location = $location.path();_x000D_
  $rootScope.$on('$routeChangeStart', function () {_x000D_
    console.log("routeChangeStart");_x000D_
   //Place code here:...._x000D_
   });_x000D_
});_x000D_
  </script>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

How to save a Seaborn plot into a file

Its also possible to just create a matplotlib figure object and then use plt.savefig(...):

from matplotlib import pyplot as plt
import seaborn as sns
import pandas as pd

df = sns.load_dataset('iris')
plt.figure() # Push new figure on stack
sns_plot = sns.pairplot(df, hue='species', size=2.5)
plt.savefig('output.png') # Save that figure

Asp.net - <customErrors mode="Off"/> error when trying to access working webpage

For example in my case I accidentaly changed role of some users to incorrect, and my application got error during starting (NullReferenceException). When I fixed it - the app starts fine.

Error: Cannot find module html

This is what i did for rendering html files. And it solved the errors. Install consolidate and mustache by executing the below command in your project folder.

$ sudo npm install consolidate mustache --save

And make the following changes to your app.js file

var engine = require('consolidate');

app.set('views', __dirname + '/views');
app.engine('html', engine.mustache);
app.set('view engine', 'html');

And now html pages will be rendered properly.

How do you implement a re-try-catch?

Here a reusable and more generic approach for Java 8+ that does not require external libraries:

public interface IUnreliable<T extends Exception>
{
    void tryRun ( ) throws T;
}

public static <T extends Exception> void retry (int retryCount, IUnreliable<T> runnable) throws T {
    for (int retries = 0;; retries++) {
        try {
            runnable.tryRun();
            return;
        } catch (Exception e) {
            if (retries < retryCount) {
                continue;
            } else {
                throw e;
            }
        }
    }
}

Usage:

@Test
public void demo() throws IOException {
    retry(3, () -> {
        new File("/tmp/test.txt").createNewFile();
    });
}

How to change port number for apache in WAMP

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

How to round 0.745 to 0.75 using BigDecimal.ROUND_HALF_UP?

double doubleVal = 1.745;
double doubleVal1 = 0.745;
System.out.println(new BigDecimal(doubleVal));
System.out.println(new BigDecimal(doubleVal1));

outputs:

1.74500000000000010658141036401502788066864013671875
0.74499999999999999555910790149937383830547332763671875

Which shows the real value of the two doubles and explains the result you get. As pointed out by others, don't use the double constructor (apart from the specific case where you want to see the actual value of a double).

More about double precision:

What's a .sh file?

Typically a .sh file is a shell script which you can execute in a terminal. Specifically, the script you mentioned is a bash script, which you can see if you open the file and look in the first line of the file, which is called the shebang or magic line.

Compare integer in bash, unary operator expected

Your piece of script works just great. Are you sure you are not assigning anything else before the if to "i"?

A common mistake is also not to leave a space after and before the square brackets.

jQuery UI Dialog Box - does not open after being closed

on the last line, don't use $(this).remove() use $(this).hide() instead.

EDIT: To clarify,on the close click event you're removing the #terms div from the DOM which is why its not coming back. You just need to hide it instead.

Git - How to fix "corrupted" interactive rebase?

If you get below state and rebase does not work anymore,

$ git status
rebase in progress; onto (null)
You are currently rebasing.
  (all conflicts fixed: run "git rebase --continue")

Then first run,

$ git rebase -quit

And then restore previous state from reflog,

$ git reflog
97f7c6f (HEAD, origin/master, origin/HEAD) HEAD@{0}: pull --rebase: checkout 97f7c6f292d995b2925c2ea036bb4823a856e1aa
4035795 (master) HEAD@{1}: commit (amend): Adding 2nd commit
d16be84 HEAD@{2}: commit (amend): Adding 2nd commit
8577ca8 HEAD@{3}: commit: Adding 2nd commit
3d2088d HEAD@{4}: reset: moving to head~
52eec4a HEAD@{5}: commit: Adding initial commit

Using,

$ git checkout HEAD@{1} #or
$ git checkout master #or
$ git checkout 4035795 #or

Keyboard shortcuts are not active in Visual Studio with Resharper installed

I had a very difficult time getting this working one under VS2015 one day. After the initial install everything was working, but I come in this morning and my keyboard shortcuts don't work. Going through Resharper's Environment > Keyboard & Menus didn't work; reinstalling Resharper didn't work. Even deleting every configuration from Resharper's AppData folder didn't work.

So what did work? Going to Visual Studio's Tools > Options > Environment > Keyboard and clicking Reset. After I did that, then Resharper's schemes would take.

Change form size at runtime in C#

Something like this works fine for me:

public partial class Form1 : Form
{
    Form mainFormHandler;
...
}

private void Form1_Load(object sender, EventArgs e){
    mainFormHandler = Application.OpenForms[0];
   //or instead use this one:
   //mainFormHandler = Application.OpenForms["Form1"];
}

Then you can change the size as below:

mainFormHandler.Width = 600;
mainFormHandler.Height= 400;

or

mainFormHandler.Size = new Size(600, 400);

Another useful point is that if you want to change the size of mainForm from another Form, you can simply use Property to set the size.

pip is not able to install packages correctly: Permission denied error

It looks like you're having a permissions error, based on this message in your output: error: could not create '/lib/python2.7/site-packages/lxml': Permission denied.

One thing you can try is doing a user install of the package with pip install lxml --user. For more information on how that works, check out this StackOverflow answer. (Thanks to Ishaan Taylor for the suggestion)

You can also run pip install as a superuser with sudo pip install lxml but it is not generally a good idea because it can cause issues with your system-level packages.

Get the last three chars from any string - Java

The getChars string method does not return a value, instead it dumps its result into your buffer (or destination) array. The index parameter describes the start offset in your destination array.

Try this link for a more verbose description of the getChars method.

I agree with the others on this, I think substring would be a better way to handle what you're trying to accomplish.

JavaScript: Class.method vs. Class.prototype.method

For visual learners, when defining the function without .prototype

ExampleClass = function(){};
ExampleClass.method = function(customString){
             console.log((customString !== undefined)? 
                          customString : 
                          "called from func def.");}
ExampleClass.method(); // >> output: `called from func def.`  

var someInstance = new ExampleClass();
someInstance.method('Called from instance');
    // >> error! `someInstance.method is not a function`  

With same code, if .prototype is added,

ExampleClass.prototype.method = function(customString){
             console.log((customString !== undefined)? 
                          customString : 
                          "called from func def.");}
ExampleClass.method();  
      // > error! `ExampleClass.method is not a function.`  

var someInstance = new ExampleClass();
someInstance.method('Called from instance');
                 // > output: `Called from instance`

To make it clearer,

ExampleClass = function(){};
ExampleClass.directM = function(){}  //M for method
ExampleClass.prototype.protoM = function(){}

var instanceOfExample = new ExampleClass();

ExampleClass.directM();     ? works
instanceOfExample.directM();   x Error!

ExampleClass.protoM();     x Error!
instanceOfExample.protoM();  ? works

****Note for the example above, someInstance.method() won't be executed as,
ExampleClass.method() causes error & execution cannot continue.
But for the sake of illustration & easy understanding, I've kept this sequence.****

Results generated from chrome developer console & JS Bin
Click on the jsbin link above to step through the code.
Toggle commented section with ctrl+/

Automatic Preferred Max Layout Width is not available on iOS versions prior to 8.0

Solution it's quite simple

Just enable Builds for iOS 8 and Later

enter image description here

Web API Put Request generates an Http 405 Method Not Allowed error

Add this to your web.config. You need to tell IIS what PUT PATCH DELETE and OPTIONS means. And which IHttpHandler to invoke.

<configuation>
    <system.webServer>
    <handlers>
    <remove name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" />
    <remove name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" />
    <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
    <add name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness32" responseBufferLimit="0" />
    <add name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness64" responseBufferLimit="0" />
    <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
    </handlers>
    </system.webServer>
</configuration>

Also check you don't have WebDAV enabled.

Creating a BLOB from a Base64 string in JavaScript

The atob function will decode a Base64-encoded string into a new string with a character for each byte of the binary data.

const byteCharacters = atob(b64Data);

Each character's code point (charCode) will be the value of the byte. We can create an array of byte values by applying this using the .charCodeAt method for each character in the string.

const byteNumbers = new Array(byteCharacters.length);
for (let i = 0; i < byteCharacters.length; i++) {
    byteNumbers[i] = byteCharacters.charCodeAt(i);
}

You can convert this array of byte values into a real typed byte array by passing it to the Uint8Array constructor.

const byteArray = new Uint8Array(byteNumbers);

This in turn can be converted to a BLOB by wrapping it in an array and passing it to the Blob constructor.

const blob = new Blob([byteArray], {type: contentType});

The code above works. However the performance can be improved a little by processing the byteCharacters in smaller slices, rather than all at once. In my rough testing 512 bytes seems to be a good slice size. This gives us the following function.

const b64toBlob = (b64Data, contentType='', sliceSize=512) => {
  const byteCharacters = atob(b64Data);
  const byteArrays = [];

  for (let offset = 0; offset < byteCharacters.length; offset += sliceSize) {
    const slice = byteCharacters.slice(offset, offset + sliceSize);

    const byteNumbers = new Array(slice.length);
    for (let i = 0; i < slice.length; i++) {
      byteNumbers[i] = slice.charCodeAt(i);
    }

    const byteArray = new Uint8Array(byteNumbers);
    byteArrays.push(byteArray);
  }

  const blob = new Blob(byteArrays, {type: contentType});
  return blob;
}
const blob = b64toBlob(b64Data, contentType);
const blobUrl = URL.createObjectURL(blob);

window.location = blobUrl;

Full Example:

_x000D_
_x000D_
const b64toBlob = (b64Data, contentType='', sliceSize=512) => {_x000D_
  const byteCharacters = atob(b64Data);_x000D_
  const byteArrays = [];_x000D_
_x000D_
  for (let offset = 0; offset < byteCharacters.length; offset += sliceSize) {_x000D_
    const slice = byteCharacters.slice(offset, offset + sliceSize);_x000D_
_x000D_
    const byteNumbers = new Array(slice.length);_x000D_
    for (let i = 0; i < slice.length; i++) {_x000D_
      byteNumbers[i] = slice.charCodeAt(i);_x000D_
    }_x000D_
_x000D_
    const byteArray = new Uint8Array(byteNumbers);_x000D_
    byteArrays.push(byteArray);_x000D_
  }_x000D_
_x000D_
  const blob = new Blob(byteArrays, {type: contentType});_x000D_
  return blob;_x000D_
}_x000D_
_x000D_
const contentType = 'image/png';_x000D_
const b64Data = 'iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==';_x000D_
_x000D_
const blob = b64toBlob(b64Data, contentType);_x000D_
const blobUrl = URL.createObjectURL(blob);_x000D_
_x000D_
const img = document.createElement('img');_x000D_
img.src = blobUrl;_x000D_
document.body.appendChild(img);
_x000D_
_x000D_
_x000D_

How can I get Docker Linux container information from within the container itself?

Docker sets the hostname to the container ID by default, but users can override this with --hostname. Instead, inspect /proc:

$ more /proc/self/cgroup
14:name=systemd:/docker/7be92808767a667f35c8505cbf40d14e931ef6db5b0210329cf193b15ba9d605
13:pids:/docker/7be92808767a667f35c8505cbf40d14e931ef6db5b0210329cf193b15ba9d605
12:hugetlb:/docker/7be92808767a667f35c8505cbf40d14e931ef6db5b0210329cf193b15ba9d605
11:net_prio:/docker/7be92808767a667f35c8505cbf40d14e931ef6db5b0210329cf193b15ba9d605
10:perf_event:/docker/7be92808767a667f35c8505cbf40d14e931ef6db5b0210329cf193b15ba9d605
9:net_cls:/docker/7be92808767a667f35c8505cbf40d14e931ef6db5b0210329cf193b15ba9d605
8:freezer:/docker/7be92808767a667f35c8505cbf40d14e931ef6db5b0210329cf193b15ba9d605
7:devices:/docker/7be92808767a667f35c8505cbf40d14e931ef6db5b0210329cf193b15ba9d605
6:memory:/docker/7be92808767a667f35c8505cbf40d14e931ef6db5b0210329cf193b15ba9d605
5:blkio:/docker/7be92808767a667f35c8505cbf40d14e931ef6db5b0210329cf193b15ba9d605
4:cpuacct:/docker/7be92808767a667f35c8505cbf40d14e931ef6db5b0210329cf193b15ba9d605
3:cpu:/docker/7be92808767a667f35c8505cbf40d14e931ef6db5b0210329cf193b15ba9d605
2:cpuset:/docker/7be92808767a667f35c8505cbf40d14e931ef6db5b0210329cf193b15ba9d605
1:name=openrc:/docker

Here's a handy one-liner to extract the container ID:

$ grep "memory:/" < /proc/self/cgroup | sed 's|.*/||'
7be92808767a667f35c8505cbf40d14e931ef6db5b0210329cf193b15ba9d605

How can I print out C++ map values?

If your compiler supports (at least part of) C++11 you could do something like:

for (auto& t : myMap)
    std::cout << t.first << " " 
              << t.second.first << " " 
              << t.second.second << "\n";

For C++03 I'd use std::copy with an insertion operator instead:

typedef std::pair<string, std::pair<string, string> > T;

std::ostream &operator<<(std::ostream &os, T const &t) { 
    return os << t.first << " " << t.second.first << " " << t.second.second;
}

// ...
std:copy(myMap.begin(), myMap.end(), std::ostream_iterator<T>(std::cout, "\n"));

How to prevent null values inside a Map and null fields inside a bean from getting serialized through Jackson

Answer seems to be a little old, What I did was to use this mapper to convert a MAP

      ObjectMapper mapper = new ObjectMapper().configure(SerializationConfig.Feature.WRITE_NULL_MAP_VALUES, false);

a simple Map:

          Map<String, Object> user = new HashMap<String,Object>();
            user.put( "id",  teklif.getAccount().getId() );
            user.put( "fname", teklif.getAccount().getFname());
            user.put( "lname", teklif.getAccount().getLname());
            user.put( "email", teklif.getAccount().getEmail());
            user.put( "test", null);

Use it like this for example:

      String json = mapper.writeValueAsString(user);

The simplest possible JavaScript countdown timer?

If you want a real timer you need to use the date object.

Calculate the difference.

Format your string.

window.onload=function(){
      var start=Date.now(),r=document.getElementById('r');
      (function f(){
      var diff=Date.now()-start,ns=(((3e5-diff)/1e3)>>0),m=(ns/60)>>0,s=ns-m*60;
      r.textContent="Registration closes in "+m+':'+((''+s).length>1?'':'0')+s;
      if(diff>3e5){
         start=Date.now()
      }
      setTimeout(f,1e3);
      })();
}

Example

Jsfiddle

not so precise timer

var time=5*60,r=document.getElementById('r'),tmp=time;

setInterval(function(){
    var c=tmp--,m=(c/60)>>0,s=(c-m*60)+'';
    r.textContent='Registration closes in '+m+':'+(s.length>1?'':'0')+s
    tmp!=0||(tmp=time);
},1000);

JsFiddle

Preventing HTML and Script injections in Javascript

myDiv.textContent = arbitraryHtmlString 

as @Dan pointed out, do not use innerHTML, even in nodes you don't append to the document because deffered callbacks and scripts are always executed. You can check this https://gomakethings.com/preventing-cross-site-scripting-attacks-when-using-innerhtml-in-vanilla-javascript/ for more info.

Prevent div from moving while resizing the page

1 - remove the margin from your BODY CSS.

2 - wrap all of your html in a wrapper <div id="wrapper"> ... all your body content </div>

3 - Define the CSS for the wrapper:

This will hold everything together, centered on the page.

#wrapper {
    margin-left:auto;
    margin-right:auto;
    width:960px;
}

Master Page Weirdness - "Content controls have to be top-level controls in a content page or a nested master page that references a master page."

In my case runat="server" was missing in the asp:content tag. I know it's stupid, but someone might have removed from the code in the build I got.

It worked for me. Someone may face the same thing. Hence shared.

Javascript - Open a given URL in a new tab by clicking a button

Use window.open instead of window.location to open a new window or tab (depending on browser settings).

Your fiddle does not work because there is no button element to select. Try input[type=button] or give the button an id and use #buttonId.

How to check Elasticsearch cluster health?

To check on elasticsearch cluster health you need to use

curl localhost:9200/_cat/health

More on the cat APIs here.

I usually use elasticsearch-head plugin to visualize that.

You can find it's github project here.

It's easy to install sudo $ES_HOME/bin/plugin -i mobz/elasticsearch-head and then you can open localhost:9200/_plugin/head/ in your web brower.

You should have something that looks like this :

enter image description here

What is getattr() exactly and how do I use it?

Other than all the amazing answers here, there is a way to use getattr to save copious lines of code and keeping it snug. This thought came following the dreadful representation of code that sometimes might be a necessity.

Scenario

Suppose your directory structure is as follows:

- superheroes.py
- properties.py

And, you have functions for getting information about Thor, Iron Man, Doctor Strange in superheroes.py. You very smartly write down the properties of all of them in properties.py in a compact dict and then access them.

properties.py

thor = {
    'about': 'Asgardian god of thunder',
    'weapon': 'Mjolnir',
    'powers': ['invulnerability', 'keen senses', 'vortex breath'], # and many more
}
iron_man = {
    'about': 'A wealthy American business magnate, playboy, and ingenious scientist',
    'weapon': 'Armor',
    'powers': ['intellect', 'armor suit', 'interface with wireless connections', 'money'],
}
doctor_strange = {
    'about': ' primary protector of Earth against magical and mystical threats',
    'weapon': 'Magic',
    'powers': ['magic', 'intellect', 'martial arts'],
}

Now, let's say you want to return capabilities of each of them on demand in superheroes.py. So, there are functions like

from .properties import thor, iron_man, doctor_strange


def get_thor_weapon():
    return thor['weapon']


def get_iron_man_bio():
    return iron_man['about']


def get_thor_powers():
    return thor['powers']

...and more functions returning different values based on the keys and superhero.

With the help of getattr, you could do something like:

from . import properties


def get_superhero_weapon(hero):
    superhero = getattr(properties, hero)
    return superhero['weapon']


def get_superhero_powers(hero):
    superhero = getattr(properties, hero)
    return superhero['powers']

You considerably reduced the number of lines of code, functions and repetition!

Oh and of course, if you have bad names like properties_of_thor for variables , they can be made and accessed by simply doing

def get_superhero_weapon(hero):
    superhero = 'properties_of_{}'.format(hero)
    all_properties = getattr(properties, superhero)
    return all_properties['weapon']

NOTE: For this particular problem, there can be smarter ways to deal with the situation, but the idea is to give an insight about using getattr in right places to write cleaner code.

Get the list of stored procedures created and / or modified on a particular date?

SELECT * FROM sys.objects WHERE type='p' ORDER BY modify_date DESC

SELECT name, create_date, modify_date 
FROM sys.objects
WHERE type = 'P'

SELECT name, crdate, refdate 
FROM sysobjects
WHERE type = 'P' 
ORDER BY refdate desc

How to list active connections on PostgreSQL?

SELECT * FROM pg_stat_activity WHERE datname = 'dbname' and state = 'active';

Since pg_stat_activity contains connection statistics of all databases having any state, either idle or active, database name and connection state should be included in the query to get the desired output.

Parsing a CSV file using NodeJS

fs = require('fs');
fs.readFile('FILENAME WITH PATH','utf8', function(err,content){
if(err){
    console.log('error occured ' +JSON.stringify(err));
 }
 console.log('Fileconetent are ' + JSON.stringify(content));
})

Is there a way to provide named parameters in a function call in JavaScript?

Another way would be to use attributes of a suitable object, e.g. like so:

function plus(a,b) { return a+b; };

Plus = { a: function(x) { return { b: function(y) { return plus(x,y) }}}, 
         b: function(y) { return { a: function(x) { return plus(x,y) }}}};

sum = Plus.a(3).b(5);

Of course for this made up example it is somewhat meaningless. But in cases where the function looks like

do_something(some_connection_handle, some_context_parameter, some_value)

it might be more useful. It also could be combined with "parameterfy" idea to create such an object out of an existing function in a generic way. That is for each parameter it would create a member that can evaluate to a partial evaluated version of the function.

This idea is of course related to Schönfinkeling aka Currying.

How to see PL/SQL Stored Function body in Oracle

If is a package then you can get the source for that with:

    select text from all_source where name = 'PADCAMPAIGN' 
    and type = 'PACKAGE BODY'
    order by line;

Oracle doesn't store the source for a sub-program separately, so you need to look through the package source for it.

Note: I've assumed you didn't use double-quotes when creating that package, but if you did , then use

    select text from all_source where name = 'pAdCampaign' 
    and type = 'PACKAGE BODY'
    order by line;

How do you fix a MySQL "Incorrect key file" error when you can't repair the table?

You must change the location of MySQL's temporary folder which is '/tmp' in most cases to a location with a bigger disk space. Change it in MySQL's config file.

Basically your server is running out of disk space where /tmp is located.

Call a function after previous function is complete

you can do it like this

$.when(funtion1()).then(function(){
    funtion2();
})

Keep a line of text as a single line - wrap the whole line or none at all

You can use white-space: nowrap; to define this behaviour:

// HTML:

_x000D_
_x000D_
.nowrap {_x000D_
  white-space: nowrap ;_x000D_
}
_x000D_
<p>_x000D_
      <span class="nowrap">How do I wrap this line of text</span>_x000D_
      <span class="nowrap">- asked by Peter 2 days ago</span>_x000D_
    </p>
_x000D_
_x000D_
_x000D_

// CSS:
.nowrap {
  white-space: nowrap ;
}

How do you fade in/out a background color using jquery?

Depending on your browser support, you could use a css animation. Browser support is IE10 and up for CSS animation. This is nice so you don't have to add jquery UI dependency if its only a small easter egg. If it is integral to your site (aka needed for IE9 and below) go with the jquery UI solution.

.your-animation {
    background-color: #fff !important;
    -webkit-animation: your-animation-name 1s ease 0s 1 alternate !important;
}
//You have to add the vendor prefix versions for it to work in Firefox, Safari, and Opera.
@-webkit-keyframes your-animation-name {
    from { background-color: #5EB4FE;}
    to {background-color: #fff;}
}
-moz-animation: your-animation-name 1s ease 0s 1 alternate !important;
}
@-moz-keyframes your-animation-name {
    from { background-color: #5EB4FE;}
    to {background-color: #fff;}
}
-ms-animation: your-animation-name 1s ease 0s 1 alternate !important;
}
@-ms-keyframes your-animation-name {
    from { background-color: #5EB4FE;}
    to {background-color: #fff;}
}
-o-animation: your-animation-name 1s ease 0s 1 alternate !important;
}
@-o-keyframes your-animation-name {
    from { background-color: #5EB4FE;}
    to {background-color: #fff;}
}
animation: your-animation-name 1s ease 0s 1 alternate !important;
}
@keyframes your-animation-name {
    from { background-color: #5EB4FE;}
    to {background-color: #fff;}
}

Next create a jQuery click event that adds the your-animation class to the element you wish to animate, triggering the background fading from one color to another:

$(".some-button").click(function(e){
    $(".place-to-add-class").addClass("your-animation");
});

Count the cells with same color in google spreadsheet

here is a working version :

function countbackgrounds() {
 var book = SpreadsheetApp.getActiveSpreadsheet();
 var range_input = book.getRange("B3:B4");
 var range_output = book.getRange("B6");
 var cell_colors = range_input.getBackgroundColors();
 var color = "#58FA58";
 var count = 0;

 for( var i in cell_colors ){
 Logger.log(cell_colors[i][0])
  if( cell_colors[i][0] == color ){ ++count }
  }
range_output.setValue(count);
 }  

Convert a Unix timestamp to time in JavaScript

Use:

var s = new Date(1504095567183).toLocaleDateString("en-US")
console.log(s)
// expected output "8/30/2017"  

and for time:

_x000D_
_x000D_
var s = new Date(1504095567183).toLocaleTimeString("en-US")
console.log(s)
// expected output "3:19:27 PM"
_x000D_
_x000D_
_x000D_

see Date.prototype.toLocaleDateString()

Differences between Ant and Maven

Maven is a Framework, Ant is a Toolbox

Maven is a pre-built road car, whereas Ant is a set of car parts. With Ant you have to build your own car, but at least if you need to do any off-road driving you can build the right type of car.

To put it another way, Maven is a framework whereas Ant is a toolbox. If you're content with working within the bounds of the framework then Maven will do just fine. The problem for me was that I kept bumping into the bounds of the framework and it wouldn't let me out.

XML Verbosity

tobrien is a guy who knows a lot about Maven and I think he provided a very good, honest comparison of the two products. He compared a simple Maven pom.xml with a simple Ant build file and he made mention of how Maven projects can become more complex. I think that its worth taking a look at a comparison of a couple of files that you are more likely to see in a simple real-world project. The files below represent a single module in a multi-module build.

First, the Maven file:

<project 
    xmlns="http://maven.apache.org/POM/4.0.0" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-4_0_0.xsd">

    <parent>
        <groupId>com.mycompany</groupId>
        <artifactId>app-parent</artifactId>
        <version>1.0</version>
    </parent>

    <modelVersion>4.0.0</modelVersion>
    <artifactId>persist</artifactId>
    <name>Persistence Layer</name>

    <dependencies>

        <dependency>
            <groupId>com.mycompany</groupId>
            <artifactId>common</artifactId>
            <scope>compile</scope>
            <version>${project.version}</version>
        </dependency>

        <dependency>
            <groupId>com.mycompany</groupId>
            <artifactId>domain</artifactId>
            <scope>provided</scope>
            <version>${project.version}</version>
        </dependency>

        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate</artifactId>
            <version>${hibernate.version}</version>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>commons-lang</groupId>
            <artifactId>commons-lang</artifactId>
            <version>${commons-lang.version}</version>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring</artifactId>
            <version>${spring.version}</version>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>org.dbunit</groupId>
            <artifactId>dbunit</artifactId>
            <version>2.2.3</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.testng</groupId>
            <artifactId>testng</artifactId>
            <version>${testng.version}</version>
            <scope>test</scope>
            <classifier>jdk15</classifier>
        </dependency>

        <dependency>
            <groupId>commons-dbcp</groupId>
            <artifactId>commons-dbcp</artifactId>
            <version>${commons-dbcp.version}</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>com.oracle</groupId>
            <artifactId>ojdbc</artifactId>
            <version>${oracle-jdbc.version}</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.easymock</groupId>
            <artifactId>easymock</artifactId>
            <version>${easymock.version}</version>
            <scope>test</scope>
        </dependency>

    </dependencies>

</project>

And the equivalent Ant file:

<project name="persist" >

    <import file="../build/common-build.xml" />


    <path id="compile.classpath.main">
        <pathelement location="${common.jar}" />
        <pathelement location="${domain.jar}" />
        <pathelement location="${hibernate.jar}" />
        <pathelement location="${commons-lang.jar}" />
        <pathelement location="${spring.jar}" />
    </path>


    <path id="compile.classpath.test">
        <pathelement location="${classes.dir.main}" />
        <pathelement location="${testng.jar}" />
        <pathelement location="${dbunit.jar}" />
        <pathelement location="${easymock.jar}" />
        <pathelement location="${commons-dbcp.jar}" />
        <pathelement location="${oracle-jdbc.jar}" />
        <path refid="compile.classpath.main" />
    </path>


    <path id="runtime.classpath.test">
        <pathelement location="${classes.dir.test}" />
        <path refid="compile.classpath.test" />
    </path>


</project>

tobrien used his example to show that Maven has built-in conventions but that doesn't necessarily mean that you end up writing less XML. I have found the opposite to be true. The pom.xml is 3 times longer than the build.xml and that is without straying from the conventions. In fact, my Maven example is shown without an extra 54 lines that were required to configure plugins. That pom.xml is for a simple project. The XML really starts to grow significantly when you start adding in extra requirements, which is not out of the ordinary for many projects.

But you have to tell Ant what to do

My Ant example above is not complete of course. We still have to define the targets used to clean, compile, test etc. These are defined in a common build file that is imported by all modules in the multi-module project. Which leads me to the point about how all this stuff has to be explicitly written in Ant whereas it is declarative in Maven.

Its true, it would save me time if I didn't have to explicitly write these Ant targets. But how much time? The common build file I use now is one that I wrote 5 years ago with only slight refinements since then. After my 2 year experiment with Maven, I pulled the old Ant build file out of the closet, dusted it off and put it back to work. For me, the cost of having to explicitly tell Ant what to do has added up to less than a week over a period of 5 years.

Complexity

The next major difference I'd like to mention is that of complexity and the real-world effect it has. Maven was built with the intention of reducing the workload of developers tasked with creating and managing build processes. In order to do this it has to be complex. Unfortunately that complexity tends to negate their intended goal.

When compared with Ant, the build guy on a Maven project will spend more time:

  • Reading documentation: There is much more documentation on Maven, because there is so much more you need to learn.
  • Educating team members: They find it easier to ask someone who knows rather than trying to find answers themselves.
  • Troubleshooting the build: Maven is less reliable than Ant, especially the non-core plugins. Also, Maven builds are not repeatable. If you depend on a SNAPSHOT version of a plugin, which is very likely, your build can break without you having changed anything.
  • Writing Maven plugins: Plugins are usually written with a specific task in mind, e.g. create a webstart bundle, which makes it more difficult to reuse them for other tasks or to combine them to achieve a goal. So you may have to write one of your own to workaround gaps in the existing plugin set.

In contrast:

  • Ant documentation is concise, comprehensive and all in one place.
  • Ant is simple. A new developer trying to learn Ant only needs to understand a few simple concepts (targets, tasks, dependencies, properties) in order to be able to figure out the rest of what they need to know.
  • Ant is reliable. There haven't been very many releases of Ant over the last few years because it already works.
  • Ant builds are repeatable because they are generally created without any external dependencies, such as online repositories, experimental third-party plugins etc.
  • Ant is comprehensive. Because it is a toolbox, you can combine the tools to perform almost any task you want. If you ever need to write your own custom task, it's very simple to do.

Familiarity

Another difference is that of familiarity. New developers always require time to get up to speed. Familiarity with existing products helps in that regard and Maven supporters rightly claim that this is a benefit of Maven. Of course, the flexibility of Ant means that you can create whatever conventions you like. So the convention I use is to put my source files in a directory name src/main/java. My compiled classes go into a directory named target/classes. Sounds familiar doesn't it.

I like the directory structure used by Maven. I think it makes sense. Also their build lifecycle. So I use the same conventions in my Ant builds. Not just because it makes sense but because it will be familiar to anyone who has used Maven before.

How to fix error "ERROR: Command errored out with exit status 1: python." when trying to install django-heroku using pip

You need to add the package containing the executable pg_config.

A prior answer should have details you need: pg_config executable not found

At runtime, find all classes in a Java application that extend a base class

Java dynamically loads classes, so your universe of classes would be only those that have already been loaded (and not yet unloaded). Perhaps you can do something with a custom class loader that could check the supertypes of each loaded class. I don't think there's an API to query the set of loaded classes.

target="_blank" vs. target="_new"

it's my understanding that target = whatever will look for a frame/window with that name. If not found, it will open up a new window with that name. If whatever == "_new", it will appear just as if you used _blank except.....

Using one of the reserved target names will bypass the "looking" phase. So, target = "_blank" on a dozen links will open up a dozen blank windows, but target = whatever on a dozen links will only open up one window. target = "_new" on a dozen links may give inconstant behavior. I haven't tried it on several browsers, but should only open up one window.

At least this is how I interpret the rules.

How to autosize a textarea using Prototype?

I've made something quite easy. First I put the TextArea into a DIV. Second, I've called on the ready function to this script.

<div id="divTable">
  <textarea ID="txt" Rows="1" TextMode="MultiLine" />
</div>

$(document).ready(function () {
  var heightTextArea = $('#txt').height();
  var divTable = document.getElementById('divTable');
  $('#txt').attr('rows', parseInt(parseInt(divTable .style.height) / parseInt(altoFila)));
});

Simple. It is the maximum height of the div once it is rendered, divided by the height of one TextArea of one row.

Passing a variable from one php include file to another: global vs. not

When including files in PHP, it acts like the code exists within the file they are being included from. Imagine copy and pasting the code from within each of your included files directly into your index.php. That is how PHP works with includes.

So, in your example, since you've set a variable called $name in your front.inc file, and then included both front.inc and end.inc in your index.php, you will be able to echo the variable $name anywhere after the include of front.inc within your index.php. Again, PHP processes your index.php as if the code from the two files you are including are part of the file.

When you place an echo within an included file, to a variable that is not defined within itself, you're not going to get a result because it is treated separately then any other included file.

In other words, to do the behavior you're expecting, you will need to define it as a global.

Stack array using pop() and push()

Stack Implementation in Java

  class stack
  {  private int top;
     private int[] element;
      stack()
      {element=new int[10];
      top=-1;
      }
      void push(int item)
      {top++;
      if(top==9)
          System.out.println("Overflow");
      else
              {
               top++;
      element[top]=item;

      }

      void pop()
      {if(top==-1)
          System.out.println("Underflow");
      else  
      top--;
      }
      void display()
      {
          System.out.println("\nTop="+top+"\nElement="+element[top]);
      }

      public static void main(String args[])
      {
        stack s1=new stack();
        s1.push(10);
        s1.display();
        s1.push(20);
        s1.display();
        s1.push(30);
        s1.display();
        s1.pop();
        s1.display();
      }

  }

Output

Top=0 Element=10 Top=1 Element=20 Top=2 Element=30 Top=1 Element=20

HTTP POST with Json on Body - Flutter/Dart

This works!

import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'package:http/http.dart' as http;

Future<http.Response> postRequest () async {
  var url ='https://pae.ipportalegre.pt/testes2/wsjson/api/app/ws-authenticate';

  Map data = {
    'apikey': '12345678901234567890'
  }
  //encode Map to JSON
  var body = json.encode(data);

  var response = await http.post(url,
      headers: {"Content-Type": "application/json"},
      body: body
  );
  print("${response.statusCode}");
  print("${response.body}");
  return response;
}

Bootstrap 3 Horizontal Divider (not in a dropdown)

As I found the default Bootstrap <hr/> size unsightly, here's some simple HTML and CSS to balance out the element visually:

HTML:

<hr class="half-rule"/>

CSS:

.half-rule { 
    margin-left: 0;
    text-align: left;
    width: 50%;
 }

How to search by key=>value in a multidimensional array in PHP

Here is solution:

<?php
$students['e1003']['birthplace'] = ("Mandaluyong <br>");
$students['ter1003']['birthplace'] = ("San Juan <br>");
$students['fgg1003']['birthplace'] = ("Quezon City <br>");
$students['bdf1003']['birthplace'] = ("Manila <br>");

$key = array_search('Delata Jona', array_column($students, 'name'));
echo $key;  

?>

What is the difference between a hash join and a merge join (Oracle RDBMS )?

I just want to edit this for posterity that the tags for oracle weren't added when I answered this question. My response was more applicable to MS SQL.

Merge join is the best possible as it exploits the ordering, resulting in a single pass down the tables to do the join. IF you have two tables (or covering indexes) that have their ordering the same such as a primary key and an index of a table on that key then a merge join would result if you performed that action.

Hash join is the next best, as it's usually done when one table has a small number (relatively) of items, its effectively creating a temp table with hashes for each row which is then searched continuously to create the join.

Worst case is nested loop which is order (n * m) which means there is no ordering or size to exploit and the join is simply, for each row in table x, search table y for joins to do.

How do I enable FFMPEG logging and where can I find the FFMPEG log file?

I found the below stuff in ffmpeg Docs. Hope this helps! :)

Reference: http://ffmpeg.org/ffmpeg.html#toc-Generic-options

‘-report’ Dump full command line and console output to a file named program-YYYYMMDD-HHMMSS.log in the current directory. This file can be useful for bug reports. It also implies -loglevel verbose.

Note: setting the environment variable FFREPORT to any value has the same effect.

How to get just numeric part of CSS property with jQuery?

I use a simple jQuery plugin to return the numeric value of any single CSS property.

It applies parseFloat to the value returned by jQuery's default css method.

Plugin Definition:

$.fn.cssNum = function(){
  return parseFloat($.fn.css.apply(this,arguments));
}

Usage:

var element = $('.selector-class');
var numericWidth = element.cssNum('width') * 10 + 'px';
element.css('width', numericWidth);

How to get the input from the Tkinter Text Widget?

I faced the problem of gettng entire text from Text widget and following solution worked for me :

txt.get(1.0,END)

Where 1.0 means first line, zeroth character (ie before the first!) is the starting position and END is the ending position.

Thanks to Alan Gauld in this link

Bootstrap 3 .img-responsive images are not responsive inside fieldset in FireFox

Change the img-class responsive to:

.img-responsive, x:-moz-any-link {
display: block;
max-width: 100%;
width: auto;
height: auto;

Allowed memory size of 33554432 bytes exhausted (tried to allocate 43148176 bytes) in php

Your script is using too much memory. This can often happen in PHP if you have a loop that has run out of control and you are creating objects or adding to arrays on each pass of the loop.

Check for infinite loops.

If that isn't the problem, try and help out PHP by destroying objects that you are finished with by setting them to null. eg. $OldVar = null;

Check the code where the error actually happens as well. Would you expect that line to be allocating a massive amount of memory? If not, try and figure out what has gone wrong...

Redirect stderr and stdout in Bash

do_something 2>&1 | tee -a some_file

This is going to redirect stderr to stdout and stdout to some_file and print it to stdout.

How can I make PHP display the error instead of giving me 500 Internal Server Error

Try not to go

MAMP > conf > [your PHP version] > php.ini

but

MAMP > bin > php > [your PHP version] > conf > php.ini

and change it there, it worked for me...

Entity Framework and Connection Pooling

According to Daniel Simmons:

Create a new ObjectContext instance in a Using statement for each service method so that it is disposed of before the method returns. This step is critical for scalability of your service. It makes sure that database connections are not kept open across service calls and that temporary state used by a particular operation is garbage collected when that operation is over. The Entity Framework automatically caches metadata and other information it needs in the app domain, and ADO.NET pools database connections, so re-creating the context each time is a quick operation.

This is from his comprehensive article here:

http://msdn.microsoft.com/en-us/magazine/ee335715.aspx

I believe this advice extends to HTTP requests, so would be valid for ASP.NET. A stateful, fat-client application such as a WPF application might be the only case for a "shared" context.

Javascript "Uncaught TypeError: object is not a function" associativity question

JavaScript does require semicolons, it's just that the interpreter will insert them for you on line breaks where possible*.

Unfortunately, the code

var a = new B(args)(stuff)()

does not result in a syntax error, so no ; will be inserted. (An example which can run is

var answer = new Function("x", "return x")(function(){return 42;})();

To avoid surprises like this, train yourself to always end a statement with ;.


* This is just a rule of thumb and not always true. The insertion rule is much more complicated. This blog page about semicolon insertion has more detail.

Which is faster: multiple single INSERTs or one multiple-row INSERT?

In general the less number of calls to the database the better (meaning faster, more efficient), so try to code the inserts in such a way that it minimizes database accesses. Remember, unless your using a connection pool, each databse access has to create a connection, execute the sql, and then tear down the connection. Quite a bit of overhead!

Counting the number of option tags in a select tag in jQuery

In a multi-select option box, you can use $('#input1 :selected').length; to get the number of selected options. This can be useful to disable buttons if a certain minimum number of options aren't met.

function refreshButtons () {
    if ($('#input :selected').length == 0)
    {
        $('#submit').attr ('disabled', 'disabled');
    }
    else
    {
        $('#submit').removeAttr ('disabled');
    }
}

Add back button to action bar

There are two ways to approach this.

Option 1: Update the Android Manifest If the settings Activity is always called from the same activity, you can make the relationship in the Android Manifest. Android will automagically show the 'back' button in the ActionBar

<activity
    android:name=".SettingsActivity"
    android:label="Setting Activity">
    <meta-data
        android:name="android.support.PARENT_ACTIVITY"
        android:value="com.example.example.MainActivity" />
</activity>

Option 2: Change a setting for the ActionBar If you don't know which Activity will call the Settings Activity, you can create it like this. First in your activity that extends ActionBarActivity (Make sure your @imports match the level of compatibility you are looking for).

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_settings_test);
    ActionBar actionBar = getSupportActionBar();
    actionBar.setHomeButtonEnabled(true);
    actionBar.setDisplayHomeAsUpEnabled(true);
}

Then, detect the 'back button' press and tell Android to close the currently open Activity.

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case android.R.id.home:
            // app icon in action bar clicked; goto parent activity.
            this.finish();
            return true;
        default:
            return super.onOptionsItemSelected(item);
    }
}

That should do it!

How do I list all remote branches in Git 1.7+?

But

git branch -ar

should do it.

Does Android keep the .apk files? if so where?

As opposed to what's written on the chosen answer, you don't need root and it is possible to get the APKs of the installed apps, which is how I've done it on my app (here). Example:

List<PackageInfo> packages=getPackageManager().getInstalledPackages(0);

Then, for each of the items of the list, you can access packageInfo.applicationInfo.sourceDir, which is the full path of the APK of the installed app.

Loop through all the files with a specific extension

No fancy tricks needed:

for i in *.java; do
    [ -f "$i" ] || break
    ...
done

The guard ensures that if there are no matching files, the loop will exit without trying to process a non-existent file name *.java. In bash (or shells supporting something similar), you can use the nullglob option to simply ignore a failed match and not enter the body of the loop.

shopt -s nullglob
for i in *.java; do
    ...
done

How do I get hour and minutes from NSDate?

Swift 2.0

    let dateNow = NSDate()
    let calendar = NSCalendar.currentCalendar()
    let hour = calendar.component(NSCalendarUnit.Hour, fromDate: dateNow)
    let minute = calendar.component(NSCalendarUnit.Minute, fromDate: dateNow)
    print(String(hour))
    print(String(minute))

Please do take note of the cast to String in the print statement, you can easily assign that value to variables, like this:

var hoursString = String(hour)
var minutesString = String(minute)

Then you can concatenate values like this:

var compoundString = "\(hour):\(minute)"
print(compoundString)

How to delete columns in pyspark dataframe

Consider 2 dataFrames:

>>> aDF.show()
+---+----+
| id|datA|
+---+----+
|  1|  a1|
|  2|  a2|
|  3|  a3|
+---+----+

and

>>> bDF.show()
+---+----+
| id|datB|
+---+----+
|  2|  b2|
|  3|  b3|
|  4|  b4|
+---+----+

To accomplish what you are looking for, there are 2 ways:

1. Different joining condition. Instead of saying aDF.id == bDF.id

aDF.join(bDF, aDF.id == bDF.id, "outer")

Write this:

aDF.join(bDF, "id", "outer").show()
+---+----+----+
| id|datA|datB|
+---+----+----+
|  1|  a1|null|
|  3|  a3|  b3|
|  2|  a2|  b2|
|  4|null|  b4|
+---+----+----+

This will automatically get rid of the extra the dropping process.

2. Use Aliasing: You will lose data related to B Specific Id's in this.

>>> from pyspark.sql.functions import col
>>> aDF.alias("a").join(bDF.alias("b"), aDF.id == bDF.id, "outer").drop(col("b.id")).show()

+----+----+----+
|  id|datA|datB|
+----+----+----+
|   1|  a1|null|
|   3|  a3|  b3|
|   2|  a2|  b2|
|null|null|  b4|
+----+----+----+

How to convert a String to CharSequence?

That's a good question! You may get into troubles if you invoke API that uses generics and want to assign or return that result with a different subtype of the generic type. Java 8 helps to transform:

    List<String> input = new LinkedList<>(Arrays.asList("a", "b", "c"));
    List<CharSequence> result;
    
//    result = input; // <-- Type mismatch: cannot convert from List<String> to List<CharSequence>
    result = input.stream().collect(Collectors.toList());
    
    System.out.println(result);

Best way to incorporate Volley (or other library) into Android Studio project

As of today, there is an official Android-hosted copy of Volley available on JCenter:

compile 'com.android.volley:volley:1.0.0'

This was compiled from the AOSP volley source code.

Contains case insensitive

You can try this

_x000D_
_x000D_
str = "Wow its so COOL"_x000D_
searchStr = "CoOl"_x000D_
_x000D_
console.log(str.toLowerCase().includes(searchStr.toLowerCase()))
_x000D_
_x000D_
_x000D_

Make <body> fill entire screen?

I think the largely correct way, is to set css to this:

html
{
    overflow: hidden;
}

body
{
    margin: 0;
    box-sizing: border-box;
}

html, body
{
    height: 100%;
}

How to pass a value from one jsp to another jsp page?

Using Query parameter

<a href="edit.jsp?userId=${user.id}" />  

Using Hidden variable .

<form method="post" action="update.jsp">  
...  
   <input type="hidden" name="userId" value="${user.id}">  

you can send Using Session object.

   session.setAttribute("userId", userid);

These values will now be available from any jsp as long as your session is still active.

   int userid = session.getAttribute("userId"); 

How do I type a TAB character in PowerShell?

If it helps you can embed a tab character in a double quoted string:

PS> "`t hello"

illegal use of break statement; javascript

I have a function next() which will maybe inspire you.

function queue(target) {
        var array = Array.prototype;

        var queueing = [];

        target.queue = queue;
        target.queued = queued;

        return target;

        function queued(action) {
            return function () {
                var self = this;
                var args = arguments;

                queue(function (next) {
                    action.apply(self, array.concat.apply(next, args));
                });
            };
        }

        function queue(action) {
            if (!action) {
                return;
            }

            queueing.push(action);

            if (queueing.length === 1) {
                next();
            }
        }

        function next() {
            queueing[0](function (err) {
                if (err) {
                    throw err;
                }

                queueing = queueing.slice(1);

                if (queueing.length) {
                    next();
                }
            });
        }
    }

jquery - return value using ajax result on success

// Common ajax caller
function AjaxCall(url,successfunction){
  var targetUrl=url;
  $.ajax({
    'url': targetUrl,
    'type': 'GET',
    'dataType': 'json',
    'success': successfunction,
    'error': function() {
      alert("error");
    }
  });
}

// Calling Ajax
$(document).ready(function() {
  AjaxCall("productData.txt",ajaxSuccessFunction);
});

// Function details of success function
function ajaxSuccessFunction(d){
  alert(d.Pioneer.Product[0].category);
}

it may help, create a common ajax call function and attach a function which invoke when success the ajax call, see the example

Python function global variables?

If you want to simply access a global variable you just use its name. However to change its value you need to use the global keyword.

E.g.

global someVar
someVar = 55

This would change the value of the global variable to 55. Otherwise it would just assign 55 to a local variable.

The order of function definition listings doesn't matter (assuming they don't refer to each other in some way), the order they are called does.

can't load package: package .: no buildable Go source files

You should check the $GOPATH directory. If there is an empty directory of the package name, go get doesn't download the package from the repository.

For example, If I want to get the github.com/googollee/go-socket.io package from it's github repository, and there is already an empty directory github.com/googollee/go-socket.io in the $GOPATH, go get doesn't download the package and then complains that there is no buildable Go source file in the directory. Delete any empty directory first of all.

How to add a tooltip to an svg graphic?

On svg, the right way to write the title

<svg>
  <title id="unique-id">Checkout</title>
</svg>

check here for more details https://css-tricks.com/svg-title-vs-html-title-attribute/

Reporting Services export to Excel with Multiple Worksheets

As @huttelihut pointed out, this is now possible as of SQL Server 2008 R2 - Read More Here

Prior to 2008 R2 it does't appear possible but MSDN Social has some suggested workarounds.

How to use code to open a modal in Angular 2?

I'm currently using Bootstrap 4.3 in Angular 8 and want to open modal window programmatically (without actually clicking on some button as the official demo shows).

Following method works for me: The general idea is to create a button associated to a modal window. First make sure after you click this button, it can open the modal. Then give this button tag an id using hashtag, for example #hiddenBtn. In component ts file, import ViewChild from @angular/core and write below code:

@ViewChild('hiddenBtn', {static: false}) myHiddenBtn;

After that, whenever you want to open this modal window in your component ts code, write following code to simulate click operation

this.myHiddenBtn.nativeElement.click();

Comparison of C++ unit test frameworks

CppUTest - very nice, light weight framework with mock libraries. Worthwhile taking a closer look.

Why do I get "MismatchSenderId" from GCM server side?

Please run below script in your terminal

curl -X POST \
-H "Authorization: key=  write here api_key" \
-H "Content-Type: application/json" \
-d '{ 
"registration_ids": [ 
"write here reg_id generated by gcm"
], 
"data": { 
"message": "Manual push notification from Rajkumar"
},
"priority": "high"
}' \
https://android.googleapis.com/gcm/send

it will give the message if it is succeeded or failed

Extract the first word of a string in a SQL Server query

SELECT CASE CHARINDEX(' ', @Foo, 1)
     WHEN 0 THEN @Foo -- empty or single word
     ELSE SUBSTRING(@Foo, 1, CHARINDEX(' ', @Foo, 1) - 1) -- multi-word
END

You could perhaps use this in a UDF:

CREATE FUNCTION [dbo].[FirstWord] (@value varchar(max))
RETURNS varchar(max)
AS
BEGIN
    RETURN CASE CHARINDEX(' ', @value, 1)
        WHEN 0 THEN @value
        ELSE SUBSTRING(@value, 1, CHARINDEX(' ', @value, 1) - 1) END
END
GO -- test:
SELECT dbo.FirstWord(NULL)
SELECT dbo.FirstWord('')
SELECT dbo.FirstWord('abc')
SELECT dbo.FirstWord('abc def')
SELECT dbo.FirstWord('abc def ghi')

:: (double colon) operator in Java 8

:: is called Method Reference. It is basically a reference to a single method. I.e. it refers to an existing method by name.

Short Explanation:
Below is an example of a reference to a static method:

class Hey {
     public static double square(double num){
        return Math.pow(num, 2);
    }
}

Function<Double, Double> square = Hey::square;
double ans = square.apply(23d);

square can be passed around just like object references and triggered when needed. In fact, it can be just as easily used as a reference to "normal" methods of objects as static ones. For example:

class Hey {
    public double square(double num) {
        return Math.pow(num, 2);
    }
}

Hey hey = new Hey();
Function<Double, Double> square = hey::square;
double ans = square.apply(23d);

Function above is a functional interface. To fully understand ::, it is important to understand functional interfaces as well. Plainly, a functional interface is an interface with just one abstract method.

Examples of functional interfaces include Runnable, Callable, and ActionListener.

Function above is a functional interface with just one method: apply. It takes one argument and produces a result.


The reason why ::s are awesome is that:

Method references are expressions which have the same treatment as lambda expressions (...), but instead of providing a method body, they refer an existing method by name.

E.g. instead of writing the lambda body

Function<Double, Double> square = (Double x) -> x * x;

You can simply do

Function<Double, Double> square = Hey::square;

At runtime, these two square methods behave exactly the same as each other. The bytecode may or may not be the same (though, for the above case, the same bytecode is generated; compile the above and check with javap -c).

The only major criterion to satisfy is: the method you provide should have a similar signature to the method of the functional interface you use as object reference.

The below is illegal:

Supplier<Boolean> p = Hey::square; // illegal

square expects an argument and returns a double. The get method in Supplier returns a value but does not take an argument. Thus, this results in an error.

A method reference refers to the method of a functional interface. (As mentioned, functional interfaces can have only one method each).

Some more examples: the accept method in Consumer takes an input but doesn't return anything.

Consumer<Integer> b1 = System::exit;   // void exit(int status)
Consumer<String[]> b2 = Arrays::sort;  // void sort(Object[] a)
Consumer<String> b3 = MyProgram::main; // void main(String... args)

class Hey {
    public double getRandom() {
        return Math.random();
    }
}

Callable<Double> call = hey::getRandom;
Supplier<Double> call2 = hey::getRandom;
DoubleSupplier sup = hey::getRandom;
// Supplier is functional interface that takes no argument and gives a result

Above, getRandom takes no argument and returns a double. So any functional interface that satisfies the criteria of: take no argument and return double can be used.

Another example:

Set<String> set = new HashSet<>();
set.addAll(Arrays.asList("leo","bale","hanks"));
Predicate<String> pred = set::contains;
boolean exists = pred.test("leo");

In case of parameterized types:

class Param<T> {
    T elem;
    public T get() {
        return elem;
    }

    public void set(T elem) {
        this.elem = elem;
    }

    public static <E> E returnSame(E elem) {
        return elem;
    }
}

Supplier<Param<Integer>> obj = Param<Integer>::new;
Param<Integer> param = obj.get();
Consumer<Integer> c = param::set;
Supplier<Integer> s = param::get;

Function<String, String> func = Param::<String>returnSame;

Method references can have different styles, but fundamentally they all mean the same thing and can simply be visualized as lambdas:

  1. A static method (ClassName::methName)
  2. An instance method of a particular object (instanceRef::methName)
  3. A super method of a particular object (super::methName)
  4. An instance method of an arbitrary object of a particular type (ClassName::methName)
  5. A class constructor reference (ClassName::new)
  6. An array constructor reference (TypeName[]::new)

For further reference, see http://cr.openjdk.java.net/~briangoetz/lambda/lambda-state-final.html.

Scala list concatenation, ::: vs ++

Legacy. List was originally defined to be functional-languages-looking:

1 :: 2 :: Nil // a list
list1 ::: list2  // concatenation of two lists

list match {
  case head :: tail => "non-empty"
  case Nil          => "empty"
}

Of course, Scala evolved other collections, in an ad-hoc manner. When 2.8 came out, the collections were redesigned for maximum code reuse and consistent API, so that you can use ++ to concatenate any two collections -- and even iterators. List, however, got to keep its original operators, aside from one or two which got deprecated.

What is the difference between Left, Right, Outer and Inner Joins?

At first you have to understand what does join do? We connect multiple table and get specific result from the joined tables. The simplest way to do this is cross join.

Lets say tableA has two column A and B. And tableB has three column C and D. If we apply cross join it will produce lot of meaningless row. Then we have to match using primary key to get actual data.

Left: it will return all records from left table and matched record from right table.

Right: it will return opposite to Left join. It will return all records from right table and matched records from left table.

Inner: This is like intersection. It will return only matched records from both table.

Outer: And this is like union. It will return all available record from both table.

Some times we don't need all of the data, and also we should need only common data or records. we can easily get it using these join methods. Remember left and right join also are outer join.

You can get all records just using cross join. But it could be expensive when it comes to millions of records. So make it simple by using left, right, inner or outer join.

thanks

How to get all key in JSON object (javascript)

var input = {"document":
  {"people":[
    {"name":["Harry Potter"],"age":["18"],"gender":["Male"]},
    {"name":["hermione granger"],"age":["18"],"gender":["Female"]},
  ]}
}

var keys = [];
for(var i = 0;i<input.document.people.length;i++)
{
    Object.keys(input.document.people[i]).forEach(function(key){
        if(keys.indexOf(key) == -1)
        {
            keys.push(key);
        }
    });
}
console.log(keys);

SQL Server: Get table primary key using sql query

The code I'll give you works and retrieves not only keys, but a lot of data from a table in SQL Server. Is tested in SQL Server 2k5/2k8, dunno about 2k. Enjoy!

SELECT DISTINCT
    sys.tables.object_id AS TableId,
    sys.columns.column_id AS ColumnId,
    sys.columns.name AS ColumnName,
    sys.types.name AS TypeName,
    sys.columns.precision AS NumericPrecision,
    sys.columns.scale AS NumericScale,
    sys.columns.is_nullable AS IsNullable,
    (   SELECT 
            COUNT(column_name)
        FROM 
            INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE 
        WHERE
            TABLE_NAME = sys.tables.name AND
            CONSTRAINT_NAME =
                (   SELECT
                    constraint_name
                    FROM 
                        INFORMATION_SCHEMA.TABLE_CONSTRAINTS
                    WHERE
                        TABLE_NAME = sys.tables.name AND                    
                        constraint_type = 'PRIMARY KEY' AND
                        COLUMN_NAME = sys.columns.name
                )
    ) AS IsPrimaryKey,
    sys.columns.max_length / 2 AS CharMaxLength /*BUG*/
FROM 
    sys.columns, sys.types, sys.tables 
WHERE
    sys.tables.object_id = sys.columns.object_id AND
    sys.types.system_type_id = sys.columns.system_type_id AND
    sys.types.user_type_id = sys.columns.user_type_id AND
    sys.tables.name = 'TABLE'
ORDER BY 
    IsPrimaryKey

You can use only the primary key part, but I think that the rest might become handy. Best regards, David

How to plot ROC curve in Python

AUC curve For Binary Classification using matplotlib

from sklearn import svm, datasets
from sklearn import metrics
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
from sklearn.datasets import load_breast_cancer
import matplotlib.pyplot as plt

Load Breast Cancer Dataset

breast_cancer = load_breast_cancer()

X = breast_cancer.data
y = breast_cancer.target

Split the Dataset

X_train, X_test, y_train, y_test = train_test_split(X,y,test_size=0.33, random_state=44)

Model

clf = LogisticRegression(penalty='l2', C=0.1)
clf.fit(X_train, y_train)
y_pred = clf.predict(X_test)

Accuracy

print("Accuracy", metrics.accuracy_score(y_test, y_pred))

AUC Curve

y_pred_proba = clf.predict_proba(X_test)[::,1]
fpr, tpr, _ = metrics.roc_curve(y_test,  y_pred_proba)
auc = metrics.roc_auc_score(y_test, y_pred_proba)
plt.plot(fpr,tpr,label="data 1, auc="+str(auc))
plt.legend(loc=4)
plt.show()

AUC Curve

How to outline text in HTML / CSS

from: Outline effect to text

.strokeme
{
    color: white;
    text-shadow:
    -1px -1px 0 #000,
    1px -1px 0 #000,
    -1px 1px 0 #000,
    1px 1px 0 #000;  
}

How to extract img src, title and alt from html using php?

You may use simplehtmldom. Most of the jQuery selectors are supported in simplehtmldom. An example is given below

// Create DOM from URL or file
$html = file_get_html('http://www.google.com/');

// Find all images
foreach($html->find('img') as $element)
       echo $element->src . '<br>';

// Find all links
foreach($html->find('a') as $element)
       echo $element->href . '<br>'; 

Moment.js - tomorrow, today and yesterday

You can use .add() and .subtract() method to get yesterday and tomorrow date. Then use format method to get only date .format("D/M/Y"), D stand for Day, M for Month, Y for Year. Check in Moment Docs

 let currentMilli = Date.now()
 let today = Moment(currentMilli).format("D/M/Y");
 let tomorrow = Moment(currentMilli).add(1, 'days').format("D/M/Y");
 let yesterday = Moment(currentMilli).subtract(1, 'days').format("D/M/Y");

Result will be:

Current Milli - 1576693800000
today - 19/12/2019
tomorrow - 18/12/2019
yesterday - 18/12/2019

android fragment- How to save states of views in a fragment when another fragment is pushed on top of it

if you are handling the config changes in your fragment activity specified in android manifest like this

<activity
    android:name=".courses.posts.EditPostActivity"
    android:configChanges="keyboardHidden|orientation"
    android:screenOrientation="unspecified" />

then the onSaveInstanceState of the fragment will not be invoked and the savedInstanceState object will always be null.

maxReceivedMessageSize and maxBufferSize in app.config

binding name="BindingName" 
maxReceivedMessageSize="2097152" 
maxBufferSize="2097152" 
maxBufferPoolSize="2097152" 

on client side and server side

PHPExcel - set cell type before writing a value in it

The same way as you'd set the type (number format mask) after writing a value to it:

$objPHPExcel->getActiveSheet()
    ->getStyle('A1')
    ->getNumberFormat()
    ->setFormatCode(
        PHPExcel_Style_NumberFormat::FORMAT_GENERAL
    );

or

$objPHPExcel->getActiveSheet()
    ->getStyle('A1')
    ->getNumberFormat()
    ->setFormatCode(
        PHPExcel_Style_NumberFormat::FORMAT_TEXT
    );

Though "Number" isn't a valid format mask.

You can find a list of pre-defined format masks in Classes/PHPExcel/Style/NumberFormat.php or set the value to any valid Excel number format masking string.

Server.MapPath - Physical path given, virtual path expected

var files = Directory.GetFiles(@"E:\ftproot\sales");

How do you clone a Git repository into a specific folder?

Option A:

git clone [email protected]:whatever folder-name

Ergo, for right here use:

git clone [email protected]:whatever .

Option B:

Move the .git folder, too. Note that the .git folder is hidden in most graphical file explorers, so be sure to show hidden files.

mv /where/it/is/right/now/* /where/I/want/it/
mv /where/it/is/right/now/.* /where/I/want/it/

The first line grabs all normal files, the second line grabs dot-files. It is also possibe to do it in one line by enabling dotglob (i.e. shopt -s dotglob) but that is probably a bad solution if you are asking the question this answer answers.

Better yet:

Keep your working copy somewhere else, and create a symbolic link. Like this:

ln -s /where/it/is/right/now /the/path/I/want/to/use

For your case this would be something like:

ln -sfn /opt/projectA/prod/public /httpdocs/public

Which easily could be changed to test if you wanted it, i.e.:

ln -sfn /opt/projectA/test/public /httpdocs/public

without moving files around. Added -fn in case someone is copying these lines (-f is force, -n avoid some often unwanted interactions with already and non-existing links).

If you just want it to work, use Option A, if someone else is going to look at what you have done, use Option C.

how to return a char array from a function in C

Lazy notes in comments.

#include <stdio.h>
// for malloc
#include <stdlib.h>

// you need the prototype
char *substring(int i,int j,char *ch);


int main(void /* std compliance */)
{
  int i=0,j=2;
  char s[]="String";
  char *test;
  // s points to the first char, S
  // *s "is" the first char, S
  test=substring(i,j,s); // so s only is ok
  // if test == NULL, failed, give up
  printf("%s",test);
  free(test); // you should free it
  return 0;
}


char *substring(int i,int j,char *ch)
{
  int k=0;
  // avoid calc same things several time
  int n = j-i+1; 
  char *ch1;
  // you can omit casting - and sizeof(char) := 1
  ch1=malloc(n*sizeof(char));
  // if (!ch1) error...; return NULL;

  // any kind of check missing:
  // are i, j ok? 
  // is n > 0... ch[i] is "inside" the string?...
  while(k<n)
    {   
      ch1[k]=ch[i];
      i++;k++;
    }   

  return ch1;
}

Using ls to list directories and their total sizes

This is one I like

update: I didnt like the previous one because it didn't show files in the current directory, it only listed directories.

Example output for /var on ubuntu:

sudo du -hDaxd1 /var | sort -h | tail -n10

4.0K    /var/lock
4.0K    /var/run
4.0K    /var/www
12K     /var/spool
3.7M    /var/backups
33M     /var/log
45M     /var/webmin
231M    /var/cache
1.4G    /var/lib
1.7G    /var

delete vs delete[] operators in C++

The operators delete and delete [] are used respectively to destroy the objects created with new and new[], returning to the allocated memory left available to the compiler's memory manager.

Objects created with new must necessarily be destroyed with delete, and that the arrays created with new[] should be deleted with delete[].

How do I watch a file for changes?

Check out pyinotify.

inotify replaces dnotify (from an earlier answer) in newer linuxes and allows file-level rather than directory-level monitoring.

How do I Search/Find and Replace in a standard string?

I believe this would work. It takes const char*'s as a parameter.

//params find and replace cannot be NULL
void FindAndReplace( std::string& source, const char* find, const char* replace )
{
   //ASSERT(find != NULL);
   //ASSERT(replace != NULL);
   size_t findLen = strlen(find);
   size_t replaceLen = strlen(replace);
   size_t pos = 0;

   //search for the next occurrence of find within source
   while ((pos = source.find(find, pos)) != std::string::npos)
   {
      //replace the found string with the replacement
      source.replace( pos, findLen, replace );

      //the next line keeps you from searching your replace string, 
      //so your could replace "hello" with "hello world" 
      //and not have it blow chunks.
      pos += replaceLen; 
   }
}

Using Alert in Response.Write Function in ASP.NET

You can simply write

try
 {
    //Your Logic and code
 }
 catch (Exception ex)
 {
    //Error message in  alert box
    Response.Write("<script>alert('Error :" +ex.Message+"');</script>");
 }

it will work fine

jquery, selector for class within id

I think your asking to select only <span class = "my_class">hello</span> this element, You have do like this, If I am understand your question correctly this is the answer,

$("#my_id [class='my_class']").addClass('test');

DEMO

what is the basic difference between stack and queue?

Stack is a LIFO (last in first out) data structure. The associated link to wikipedia contains detailed description and examples.

Queue is a FIFO (first in first out) data structure. The associated link to wikipedia contains detailed description and examples.

Resolve absolute path from relative path and/or file name

PowerShell is pretty common these days so I use it often as a quick way to invoke C# since that has functions for pretty much everything:

@echo off
set pathToResolve=%~dp0\..\SomeFile.txt
for /f "delims=" %%a in ('powershell -Command "[System.IO.Path]::GetFullPath( '%projectDirMc%' )"') do @set resolvedPath=%%a

echo Resolved path: %resolvedPath%

It's a bit slow, but the functionality gained is hard to beat unless without resorting to an actual scripting language.

CSS word-wrapping in div

try white-space:normal; This will override inheriting white-space:nowrap;

Display all views on oracle database

for all views (you need dba privileges for this query)

select view_name from dba_views

for all accessible views (accessible by logged user)

select view_name from all_views

for views owned by logged user

select view_name from user_views

grid controls for ASP.NET MVC?

We have just rolled our own due to limited functionality requirements on our grids. We use some JQuery here and there for some niceties like pagination and that is all we really need.

If you need something a little more fully featured you could check out ExtJs grids here.

Also MvcContrib has a grid implementation that you could check out - try here. Or more specifically here.

How to Find App Pool Recycles in Event Log

As it seems impossible to filter the XPath message data (it isn't in the XML to filter), you can also use powershell to search:

Get-WinEvent -LogName System | Where-Object {$_.Message -like "*recycle*"}

From this, I can see that the event Id for recycling seems to be 5074, so you can filter on this as well. I hope this helps someone as this information seemed to take a lot longer than expected to work out.

This along with @BlackHawkDesign comment should help you find what you need.

I had the same issue. Maybe interesting to mention is that you have to configure in which cases the app pool recycle event is logged. By default it's in a couple of cases, not all of them. You can do that in IIS > app pools > select the app pool > advanced settings > expand generate recycle event log entry – BlackHawkDesign Jan 14 '15 at 10:00

What is the purpose of class methods?

Factory methods (alternative constructors) are indeed a classic example of class methods.

Basically, class methods are suitable anytime you would like to have a method which naturally fits into the namespace of the class, but is not associated with a particular instance of the class.

As an example, in the excellent unipath module:

Current directory

  • Path.cwd()
    • Return the actual current directory; e.g., Path("/tmp/my_temp_dir"). This is a class method.
  • .chdir()
    • Make self the current directory.

As the current directory is process wide, the cwd method has no particular instance with which it should be associated. However, changing the cwd to the directory of a given Path instance should indeed be an instance method.

Hmmm... as Path.cwd() does indeed return a Path instance, I guess it could be considered to be a factory method...

Differences between TCP sockets and web sockets, one more time

WebSocket is basically an application protocol (with reference to the ISO/OSI network stack), message-oriented, which makes use of TCP as transport layer.

The idea behind the WebSocket protocol consists of reusing the established TCP connection between a Client and Server. After the HTTP handshake the Client and Server start speaking WebSocket protocol by exchanging WebSocket envelopes. HTTP handshaking is used to overcome any barrier (e.g. firewalls) between a Client and a Server offering some services (usually port 80 is accessible from anywhere, by anyone). Client and Server can switch over speaking HTTP in any moment, making use of the same TCP connection (which is never released).

Behind the scenes WebSocket rebuilds the TCP frames in consistent envelopes/messages. The full-duplex channel is used by the Server to push updates towards the Client in an asynchronous way: the channel is open and the Client can call any futures/callbacks/promises to manage any asynchronous WebSocket received message.

To put it simply, WebSocket is a high level protocol (like HTTP itself) built on TCP (reliable transport layer, on per frame basis) that makes possible to build effective real-time application with JS Clients (previously Comet and long-polling techniques were used to pull updates from the Server before WebSockets were implemented. See Stackoverflow post: Differences between websockets and long polling for turn based game server ).

Does not contain a static 'main' method suitable for an entry point

A valid entry looks like:

public static class ConsoleProgram
    {
        [STAThread]
        static void Main()
        {
            Console.WriteLine("Got here");
            Console.ReadLine();
        }
    }

I had issues as I'm writing a web application, but for the dreadly loading time, I wanted to quickly convert the same project to a console application and perform quick method tests without loading the entire solution.

My entry point was placed in /App_Code/Main.cs, and I had to do the following:

  1. Set Project -> Properties -> Application -> Output type = Console Application
  2. Create the /App_Code/Main.cs
  3. Add the code above in it (and reference the methods in my project)
  4. Right click on the Main.cs file -> Properties -> Build Action = Compile

After this, I can set the output (as mentioned in Step 1) to Class Library to start the web site, or Console Application to enter the console mode.

Why I did this instead of 2 separate projects?

Simply because I had references to Entity Framework and other specific references that created problems running 2 separate projects.

For easier solutions, I would still recommend 2 separate projects as the console output is mainly test code and you probably don't want to risk that going out in production code.

How to pass text in a textbox to JavaScript function?

This is what I have done. (Adapt from all of your answers)

<input name="textbox1" type="text" id="txt1"/>
<input name="buttonExecute" onclick="execute(document.getElementById('txt1').value)" type="button" value="Execute" />

It works. Thanks to all of you. :)

Add new attribute (element) to JSON object using JavaScript

Uses $.extend() of jquery, like this:

token = {_token:window.Laravel.csrfToken};
data = {v1:'asdass',v2:'sdfsdf'}
dat = $.extend(token,data); 

I hope you serve them.

Setting up foreign keys in phpMyAdmin?

Step 1: You have to add the line: default-storage-engine = InnoDB under the [mysqld] section of your mysql config file (my.cnf or my.ini depending on your OS) and restart the mysqld service. enter image description here

Step 2: Now when you create the table you will see the type of table is: InnoDB

enter image description here

Step 3: Create both Parent and Child table. Now open the Child table and select the column U like to have the Foreign Key: Select the Index Key from Action Label as shown below.

enter image description here

Step 4: Now open the Relation View in the same child table from bottom near the Print View as shown below.

enter image description here Step 5: Select the column U like to have the Foreign key as Select the Parent column from the drop down. dbName.TableName.ColumnName

Select appropriate Values for ON DELETE and ON UPDATE enter image description here

Bootstrap - Removing padding or margin when screen size is smaller

Another css that can make the margin problem is that you have direction:someValue in your css, so just remove it by setting it to initial.

For example:

body {
     direction:rtl;
 }
@media (max-width: 480px) {
    body {
     direction:initial;
    }
}

How to check if NSString begins with a certain character

Another approach to do it..

May it help someone...

if ([[temp substringToIndex:4] isEqualToString:@"http"]) {
  //starts with http
}

How to Bulk Insert from XLSX file extension?

you can save the xlsx file as a tab-delimited text file and do

BULK INSERT TableName
        FROM 'C:\SomeDirectory\my table.txt'
            WITH
    (
                FIELDTERMINATOR = '\t',
                ROWTERMINATOR = '\n'
    )
GO

Switching a DIV background image with jQuery

There are two different ways to change a background image CSS with jQuery.

  1. $('selector').css('backgroundImage','url(images/example.jpg)');
  2. $('selector').css({'background-image':'url(images/example.jpg)'});

Look carefully to note the differences. In the second, you can use conventional CSS and string multiple CSS properties together.

Javascript Print iframe contents only

You can use this command:

document.getElementById('iframeid').contentWindow.print();

This command basically is the same as window.print(), but as the window we would like to print is in the iframe, we first need to obtain an instance of that window as a javascript object.

So, in reference to that iframe, we first obtain the iframe by using it's id, and then it's contentWindow returns a window(DOM) object. So, we are able to directly use the window.print() function on this object.

Error: cannot open display: localhost:0.0 - trying to open Firefox from CentOS 6.2 64bit and display on Win7

In my case the issue was caused due to mismatch in .Xauthority file. Which initially showed up with "Invalid MIT-MAGIC-COOKIE-1" error and then "Error: cannot open display: :0.0" afterwards

Regenerating the .Xauthorityfile from the user under which I am running the vncserver and resetting the password with a restart of the vnc service and dbus service fixed the issue for me.

Change One Cell's Data in mysql

UPDATE only changes the values you specify:

UPDATE table SET cell='new_value' WHERE whatever='somevalue'

run a python script in terminal without the python command

You need to use a hashbang. Add it to the first line of your python script.

#! <full path of python interpreter>

Then change the file permissions, and add the executing permission.

chmod +x <filename>

And finally execute it using

./<filename>

If its in the current directory,

JS jQuery - check if value is in array

Alternate solution of the values check

//Duplicate Title Entry 
    $.each(ar , function (i, val) {
        if ( jQuery("input:first").val()== val) alert('VALUE FOUND'+Valuecheck);
  });

Flutter Circle Design

More efficient way

I suggest you to draw a circle with CustomPainter. It's very easy and way more efficient than creating a bunch of widgets/masks:

Flutter draw circle

/// Draws a circle if placed into a square widget.
class CirclePainter extends CustomPainter {
  final _paint = Paint()
    ..color = Colors.red
    ..strokeWidth = 2
    // Use [PaintingStyle.fill] if you want the circle to be filled.
    ..style = PaintingStyle.stroke;

  @override
  void paint(Canvas canvas, Size size) {
    canvas.drawOval(
      Rect.fromLTWH(0, 0, size.width, size.height),
      _paint,
    );
  }

  @override
  bool shouldRepaint(CustomPainter oldDelegate) => false;
}

Usage:

  Widget _buildCircle(BuildContext context) {
    return SizedBox(
      width: 20,
      height: 20,
      child: CustomPaint(
        painter: CirclePainter(),
      ),
    );
  }

Convert string to float?

Try this:

String numberStr = "3.5";
Float number = null;
try {
   number = Float.parseFloat(numberStr);
} catch (NumberFormatException e) {
    System.out.println("numberStr is not a number");
}

RuntimeWarning: invalid value encountered in divide

You are dividing by rr which may be 0.0. Check if rr is zero and do something reasonable other than using it in the denominator.

How to execute the start script with Nodemon

In package json:

"scripts": {
  "start": "node index",
  "dev": "nodemon index"
},

"devDependencies": {
  "nodemon": "^2.0.2"
}

And in the terminal for developing:

npm run dev

And for starting the server regular:

npm start

Run cmd commands through Java

You can try this:-

Process p = Runtime.getRuntime().exec(command);

Is multiplication and division using shift operators in C actually faster?

Shift and integer multiply instructions have similar performance on most modern CPUs - integer multiply instructions were relatively slow back in the 1980s but in general this is no longer true. Integer multiply instructions may have higher latency, so there may still be cases where a shift is preferable. Ditto for cases where you can keep more execution units busy (although this can cut both ways).

Integer division is still relatively slow though, so using a shift instead of division by a power of 2 is still a win, and most compilers will implement this as an optimisation. Note however that for this optimisation to be valid the dividend needs to be either unsigned or must be known to be positive. For a negative dividend the shift and divide are not equivalent!

#include <stdio.h>

int main(void)
{
    int i;

    for (i = 5; i >= -5; --i)
    {
        printf("%d / 2 = %d, %d >> 1 = %d\n", i, i / 2, i, i >> 1);
    }
    return 0;
}

Output:

5 / 2 = 2, 5 >> 1 = 2
4 / 2 = 2, 4 >> 1 = 2
3 / 2 = 1, 3 >> 1 = 1
2 / 2 = 1, 2 >> 1 = 1
1 / 2 = 0, 1 >> 1 = 0
0 / 2 = 0, 0 >> 1 = 0
-1 / 2 = 0, -1 >> 1 = -1
-2 / 2 = -1, -2 >> 1 = -1
-3 / 2 = -1, -3 >> 1 = -2
-4 / 2 = -2, -4 >> 1 = -2
-5 / 2 = -2, -5 >> 1 = -3

So if you want to help the compiler then make sure the variable or expression in the dividend is explicitly unsigned.

C# ASP.NET Send Email via TLS

TLS (Transport Level Security) is the slightly broader term that has replaced SSL (Secure Sockets Layer) in securing HTTP communications. So what you are being asked to do is enable SSL.

a tag as a submit button?

Try this code:

<form id="myform">
  <!-- form elements -->
  <a href="#" onclick="document.getElementById('myform').submit()">Submit</a>
</form>

But users with disabled JavaScript won't be able to submit the form, so you could add the following code:

<noscript>
  <input type="submit" value="Submit form!" />
</noscript>

What is the use of DesiredCapabilities in Selenium WebDriver?

DesiredCapabilities are options that you can use to customize and configure a browser session.

You can read more about them here!

CSV file written with Python has blank lines between each row

In Python 2, open outfile with mode 'wb' instead of 'w'. The csv.writer writes \r\n into the file directly. If you don't open the file in binary mode, it will write \r\r\n because on Windows text mode will translate each \n into \r\n.

In Python 3 the required syntax changed (see documentation links below), so open outfile with the additional parameter newline='' (empty string) instead.

Examples:

# Python 2
with open('/pythonwork/thefile_subset11.csv', 'wb') as outfile:
    writer = csv.writer(outfile)

# Python 3
with open('/pythonwork/thefile_subset11.csv', 'w', newline='') as outfile:
    writer = csv.writer(outfile)

Documentation Links