Programs & Examples On #Cruisecontrol

CruiseControl is both a continuous integration tool and an extensible framework for creating a custom continuous build process.

Create a new cmd.exe window from within another cmd.exe prompt

Simply type start in the command prompt:

start

This will open up new cmd windows.

Cannot apply indexing with [] to an expression of type 'System.Collections.Generic.IEnumerable<>

The idea of interfaces is generally to expose a sort of base line contract by which code that performs work on an object can be guaranteed of certain functionality provided by that object. In the case of IEnumerable<T>, that contract happens to be "you can access all of my elements one by one."

The kinds of methods that can be written based on this contract alone are many. See the Enumerable class for tons of examples.

But to zero in on just one concrete one: think about Sum. In order to sum up a bunch of items, what do you need? What contract would you require? The answer is quite simple: just a way to see every item, no more. Random access isn't necessary. Even a total count of all the items is not necessary.

To have added an indexer to the IEnumerable<T> interface would have been detrimental in two ways:

  1. Code that requires the contract described above (access to a sequence of elements), if it required the IEnumerable<T> interface, would be artificially restrictive as it could not deal with any type that did not implement an indexer, even though to deal with such a type should really be well within the capabilities of the code.
  2. Any type that wanted to expose a sequence of elements but was not appropriately equipped to provide random access by index (e.g., LinkedList<T>, Dictionary<TKey, TValue>) would now have to either provide some inefficient means of simulating indexing, or else abandon the IEnumerable<T> interface.

All this being said, considering that the purpose of an interface is to provide a guarantee of the minimum required functionality in a given scenario, I really think that the IList<T> interface is poorly designed. Or rather, the lack of an interface "between" IEnumerable<T> and IList<T> (random access, but no modification) is an unfortunate oversight in the BCL, in my opinion.

How do I set the default Java installation/runtime (Windows)?

I simply install all the versions of JDK I need and the latest installed becomes default, so I just reinstall the one I want to be default if necessary.

mailto link with HTML body

Anybody can try the following (mailto function only accepts plaintext but here i show how to use HTML innertext properties and how to add an anchor as mailto body params):

//Create as many html elements you need.

const titleElement = document.createElement("DIV");
titleElement.innerHTML = this.shareInformation.title; // Just some string

//Here I create an <a> so I can use href property
const titleLinkElement = document.createElement("a");
titleLinkElement.href = this.shareInformation.link; // This is a url

...

let mail = document.createElement("a");

// Using es6 template literals add the html innerText property and anchor element created to mailto body parameter
mail.href = 
  `mailto:?subject=${titleElement.innerText}&body=${titleLinkElement}%0D%0A${abstractElement.innerText}`;
mail.click();

// Notice how I use ${titleLinkElement} that is an anchor element, so mailto uses its href and renders the url I needed

JavaScript validation for empty input field

See the working example here


You are missing the required <form> element. Here is how your code should be like:

_x000D_
_x000D_
function IsEmpty() {
  if (document.forms['frm'].question.value === "") {
    alert("empty");
    return false;
  }
  return true;
}
_x000D_
<form name="frm">
  Question: <input name="question" /> <br />
  <input id="insert" onclick="return IsEmpty();" type="submit" value="Add Question" />
</form>
_x000D_
_x000D_
_x000D_

Converting char* to float or double

Code posted by you is correct and should have worked. But check exactly what you have in the char*. If the correct value is to big to be represented, functions will return a positive or negative HUGE_VAL. Check what you have in the char* against maximum values that float and double can represent on your computer.

Check this page for strtod reference and this page for atof reference.

I have tried the example you provided in both Windows and Linux and it worked fine.

Oracle comparing timestamp with date

You can truncate the date

SELECT *
FROM Table1
WHERE trunc(field1) = to_Date('2012-01-01','YYY-MM-DD')

Look at the SQL Fiddle for more examples.

CSS - display: none; not working

Another trick is to use

.class {
position: absolute;
visibility:hidden;
display:none;
}

This is not likely to mess up your flow (because it takes it out of flow) and makes sure that the user can't see it, and then if display:none works later on it will be working. Keep in mind that visibility:hidden may not remove it from screen readers.

How do I bind onchange event of a TextBox using JQuery?

if you're trying to use jQuery autocomplete plugin, then I think you don't need to bind to onChange event, it will

What does a "Cannot find symbol" or "Cannot resolve symbol" error mean?

I too was getting this error. (for which I googled and I was directed to this page)

Problem: I was calling a static method defined in the class of a project A from a class defined in another project B. I was getting the following error:

error: cannot find symbol

Solution: I resolved this by first building the project where the method is defined then the project where the method was being called from.

Anaconda vs. miniconda

Anaconda is a very large installation ~ 2 GB and is most useful for those users who are not familiar with installing modules or packages with other package managers.

Anaconda seems to be promoting itself as the official package manager of Jupyter. It's not. Anaconda bundles Jupyter, R, python, and many packages with its installation.

Anaconda is not necessary for installing Jupyter Lab or the R kernel. There is plenty of information available elsewhere for installing Jupyter Lab or Notebooks. There is also plenty of information elsewhere for installing R studio. The following shows how to install the R kernel directly from R Studio:

To install the R kernel, without Anaconda, start R Studio. In the R terminal window enter these three commands:

install.packages("devtools")
devtools::install_github("IRkernel/IRkernel")
IRkernel::installspec()

Done. Next time Jupyter is opened, the R kernel will be available.

How to query first 10 rows and next time query other 10 rows from table

for first 10 rows...

SELECT * FROM msgtable WHERE cdate='18/07/2012' LIMIT 0,10

for next 10 rows

SELECT * FROM msgtable WHERE cdate='18/07/2012' LIMIT 10,10

What is Type-safe?

Type-safe means that programmatically, the type of data for a variable, return value, or argument must fit within a certain criteria.

In practice, this means that 7 (an integer type) is different from "7" (a quoted character of string type).

PHP, Javascript and other dynamic scripting languages are usually weakly-typed, in that they will convert a (string) "7" to an (integer) 7 if you try to add "7" + 3, although sometimes you have to do this explicitly (and Javascript uses the "+" character for concatenation).

C/C++/Java will not understand that, or will concatenate the result into "73" instead. Type-safety prevents these types of bugs in code by making the type requirement explicit.

Type-safety is very useful. The solution to the above "7" + 3 would be to type cast (int) "7" + 3 (equals 10).

How to get current date time in milliseconds in android

I think leverage this functionality using Java

long time= System.currentTimeMillis();

this will return current time in milliseconds mode . this will surely work

long time= System.currentTimeMillis();
android.util.Log.i("Time Class ", " Time value in millisecinds "+time);

Here is my logcat using the above function

05-13 14:38:03.149: INFO/Time Class(301): Time value in millisecinds 1368436083157

If you got any doubt with millisecond value .Check Here

EDIT : Time Zone I used to demo the code IST(+05:30) ,So if you check milliseconds that mentioned in log to match with time in log you might get a different value based your system timezone

EDIT: This is easy approach .but if you need time zone or any other details I think this won't be enough Also See this approach using android api support

Relational Database Design Patterns?

Your question is a bit vague, but I suppose UPSERT could be considered a design pattern. For languages that don't implement MERGE, a number of alternatives to solve the problem (if a suitable rows exists, UPDATE; else INSERT) exist.

How to read the post request parameters using JavaScript

One option is to set a cookie in PHP.

For example: a cookie named invalid with the value of $invalid expiring in 1 day:

setcookie('invalid', $invalid, time() + 60 * 60 * 24);

Then read it back out in JS (using the JS Cookie plugin):

var invalid = Cookies.get('invalid');

if(invalid !== undefined) {
    Cookies.remove('invalid');
}

You can now access the value from the invalid variable in JavaScript.

What does the "static" modifier after "import" mean?

Say you have static fields and methods inside a class called MyClass inside a package called myPackage and you want to access them directly by typing myStaticField or myStaticMethod without typing each time MyClass.myStaticField or MyClass.myStaticMethod.

Note : you need to do an import myPackage.MyClass or myPackage.* for accessing the other resources

Converting string into datetime

Something that isn't mentioned here and is useful: adding a suffix to the day. I decoupled the suffix logic so you can use it for any number you like, not just dates.

import time

def num_suffix(n):
    '''
    Returns the suffix for any given int
    '''
    suf = ('th','st', 'nd', 'rd')
    n = abs(n) # wise guy
    tens = int(str(n)[-2:])
    units = n % 10
    if tens > 10 and tens < 20:
        return suf[0] # teens with 'th'
    elif units <= 3:
        return suf[units]
    else:
        return suf[0] # 'th'

def day_suffix(t):
    '''
    Returns the suffix of the given struct_time day
    '''
    return num_suffix(t.tm_mday)

# Examples
print num_suffix(123)
print num_suffix(3431)
print num_suffix(1234)
print ''
print day_suffix(time.strptime("1 Dec 00", "%d %b %y"))
print day_suffix(time.strptime("2 Nov 01", "%d %b %y"))
print day_suffix(time.strptime("3 Oct 02", "%d %b %y"))
print day_suffix(time.strptime("4 Sep 03", "%d %b %y"))
print day_suffix(time.strptime("13 Nov 90", "%d %b %y"))
print day_suffix(time.strptime("14 Oct 10", "%d %b %y"))???????

subtract two times in python

I had similar situation as you and I ended up with using external library called arrow.

Here is what it looks like:

>>> import arrow
>>> enter = arrow.get('12:30:45', 'HH:mm:ss')
>>> exit = arrow.now()
>>> duration = exit - enter
>>> duration
datetime.timedelta(736225, 14377, 757451)

What's the equivalent of Java's Thread.sleep() in JavaScript?

The simple answer is that there is no such function.

The closest thing you have is:

var millisecondsToWait = 500;
setTimeout(function() {
    // Whatever you want to do after the wait
}, millisecondsToWait);

Note that you especially don't want to busy-wait (e.g. in a spin loop), since your browser is almost certainly executing your JavaScript in a single-threaded environment.

Here are a couple of other SO questions that deal with threads in JavaScript:

And this question may also be helpful:

Iframe transparent background

Why not just load the frame off screen or hidden and then display it once it has finished loading. You could show a loading icon in its place to begin with to give the user immediate feedback that it's loading.

Change line width of lines in matplotlib pyplot legend

@ImportanceOfBeingErnest 's answer is good if you only want to change the linewidth inside the legend box. But I think it is a bit more complex since you have to copy the handles before changing legend linewidth. Besides, it can not change the legend label fontsize. The following two methods can not only change the linewidth but also the legend label text font size in a more concise way.

Method 1

import numpy as np
import matplotlib.pyplot as plt

# make some data
x = np.linspace(0, 2*np.pi)

y1 = np.sin(x)
y2 = np.cos(x)

# plot sin(x) and cos(x)
fig = plt.figure()
ax  = fig.add_subplot(111)
ax.plot(x, y1, c='b', label='y1')
ax.plot(x, y2, c='r', label='y2')

leg = plt.legend()
# get the individual lines inside legend and set line width
for line in leg.get_lines():
    line.set_linewidth(4)
# get label texts inside legend and set font size
for text in leg.get_texts():
    text.set_fontsize('x-large')

plt.savefig('leg_example')
plt.show()

Method 2

import numpy as np
import matplotlib.pyplot as plt

# make some data
x = np.linspace(0, 2*np.pi)

y1 = np.sin(x)
y2 = np.cos(x)

# plot sin(x) and cos(x)
fig = plt.figure()
ax  = fig.add_subplot(111)
ax.plot(x, y1, c='b', label='y1')
ax.plot(x, y2, c='r', label='y2')

leg = plt.legend()
# get the lines and texts inside legend box
leg_lines = leg.get_lines()
leg_texts = leg.get_texts()
# bulk-set the properties of all lines and texts
plt.setp(leg_lines, linewidth=4)
plt.setp(leg_texts, fontsize='x-large')
plt.savefig('leg_example')
plt.show()

The above two methods produce the same output image:

output image

"Prevent saving changes that require the table to be re-created" negative effects

The table is only dropped and re-created in cases where that's the only way SQL Server's Management Studio has been programmed to know how to do it.

There are certainly cases where it will do that when it doesn't need to, but there will also be cases where edits you make in Management Studio will not drop and re-create because it doesn't have to.

The problem is that enumerating all of the cases and determining which side of the line they fall on will be quite tedious.

This is why I like to use ALTER TABLE in a query window, instead of visual designers that hide what they're doing (and quite frankly have bugs) - I know exactly what is going to happen, and I can prepare for cases where the only possibility is to drop and re-create the table (which is some number less than how often SSMS will do that to you).

How to upload multiple files using PHP, jQuery and AJAX

Using this source code you can upload multiple file like google one by one through ajax. Also you can see the uploading progress

HTML

 <input type="file" id="multiupload" name="uploadFiledd[]" multiple >
 <button type="button" id="upcvr" class="btn btn-primary">Start Upload</button>
 <div id="uploadsts"></div>

Javascript

    <script>

    function uploadajax(ttl,cl){

    var fileList = $('#multiupload').prop("files");
    $('#prog'+cl).removeClass('loading-prep').addClass('upload-image');

    var form_data =  "";

    form_data = new FormData();
    form_data.append("upload_image", fileList[cl]);


    var request = $.ajax({
              url: "upload.php",
              cache: false,
              contentType: false,
              processData: false,
              async: true,
              data: form_data,
              type: 'POST', 
              xhr: function() {  
                  var xhr = $.ajaxSettings.xhr();
                  if(xhr.upload){ 
                  xhr.upload.addEventListener('progress', function(event){
                      var percent = 0;
                      if (event.lengthComputable) {
                          percent = Math.ceil(event.loaded / event.total * 100);
                      }
                      $('#prog'+cl).text(percent+'%') 
                   }, false);
                 }
                 return xhr;
              },
              success: function (res, status) {
                  if (status == 'success') {
                      percent = 0;
                      $('#prog' + cl).text('');
                      $('#prog' + cl).text('--Success: ');
                      if (cl < ttl) {
                          uploadajax(ttl, cl + 1);
                      } else {
                          alert('Done');
                      }
                  }
              },
              fail: function (res) {
                  alert('Failed');
              }    
          })
    }

    $('#upcvr').click(function(){
        var fileList = $('#multiupload').prop("files");
        $('#uploadsts').html('');
        var i;
        for ( i = 0; i < fileList.length; i++) {
            $('#uploadsts').append('<p class="upload-page">'+fileList[i].name+'<span class="loading-prep" id="prog'+i+'"></span></p>');
            if(i == fileList.length-1){
                uploadajax(fileList.length-1,0);
            }
         }
    });
    </script>

PHP

upload.php
    move_uploaded_file($_FILES["upload_image"]["tmp_name"],$_FILES["upload_image"]["name"]);

Why isn't my Pandas 'apply' function referencing multiple columns working?

Let's say we want to apply a function add5 to columns 'a' and 'b' of DataFrame df

def add5(x):
    return x+5

df[['a', 'b']].apply(add5)

Passing string to a function in C - with or without pointers?

An array is a pointer. It points to the start of a sequence of "objects".

If we do this: ìnt arr[10];, then arr is a pointer to a memory location, from which ten integers follow. They are uninitialised, but the memory is allocated. It is exactly the same as doing int *arr = new int[10];.

Why does AngularJS include an empty option in select?

Though both @pkozlowski.opensource's and @Mark's answers are correct, I'd like to share my slightly modified version where I always select the first item in the list, regardless of its value:

<select ng-options="option.value as option.name for option in typeOptions" ng-init="form.type=typeOptions[0].value">
</select>

Add a new line to a text file in MS-DOS

  • I always use copy con to write text, It so easy to write a long text
  • Example:

    C:\COPY CON [drive:][path][File name]

    .... Content

    F6

    1 file(s) is copied

Calculate days between two Dates in Java 8

Here you go:

public class DemoDate {
    public static void main(String[] args) {
        LocalDate today = LocalDate.now();
        System.out.println("Current date: " + today);

        //add 1 month to the current date
        LocalDate date2 = today.plus(1, ChronoUnit.MONTHS);
        System.out.println("Next month: " + date2);

        // Put latest date 1st and old date 2nd in 'between' method to get -ve date difference
        long daysNegative = ChronoUnit.DAYS.between(date2, today);
        System.out.println("Days : "+daysNegative);

        // Put old date 1st and new date 2nd in 'between' method to get +ve date difference
        long datePositive = ChronoUnit.DAYS.between(today, date2);
        System.out.println("Days : "+datePositive);
    }
}

How to Return partial view of another controller by controller?

Normally the views belong with a specific matching controller that supports its data requirements, or the view belongs in the Views/Shared folder if shared between controllers (hence the name).

"Answer" (but not recommended - see below):

You can refer to views/partial views from another controller, by specifying the full path (including extension) like:

return PartialView("~/views/ABC/XXX.cshtml", zyxmodel);

or a relative path (no extension), based on the answer by @Max Toro

return PartialView("../ABC/XXX", zyxmodel);

BUT THIS IS NOT A GOOD IDEA ANYWAY

*Note: These are the only two syntax that work. not ABC\\XXX or ABC/XXX or any other variation as those are all relative paths and do not find a match.

Better Alternatives:

You can use Html.Renderpartial in your view instead, but it requires the extension as well:

Html.RenderPartial("~/Views/ControllerName/ViewName.cshtml", modeldata);

Use @Html.Partial for inline Razor syntax:

@Html.Partial("~/Views/ControllerName/ViewName.cshtml", modeldata)

You can use the ../controller/view syntax with no extension (again credit to @Max Toro):

@Html.Partial("../ControllerName/ViewName", modeldata)

Note: Apparently RenderPartial is slightly faster than Partial, but that is not important.

If you want to actually call the other controller, use:

@Html.Action("action", "controller", parameters)

Recommended solution: @Html.Action

My personal preference is to use @Html.Action as it allows each controller to manage its own views, rather than cross-referencing views from other controllers (which leads to a large spaghetti-like mess).

You would normally pass just the required key values (like any other view) e.g. for your example:

@Html.Action("XXX", "ABC", new {id = model.xyzId })

This will execute the ABC.XXX action and render the result in-place. This allows the views and controllers to remain separately self-contained (i.e. reusable).

Update Sep 2014:

I have just hit a situation where I could not use @Html.Action, but needed to create a view path based on a action and controller names. To that end I added this simple View extension method to UrlHelper so you can say return PartialView(Url.View("actionName", "controllerName"), modelData):

public static class UrlHelperExtension
{
    /// <summary>
    /// Return a view path based on an action name and controller name
    /// </summary>
    /// <param name="url">Context for extension method</param>
    /// <param name="action">Action name</param>
    /// <param name="controller">Controller name</param>
    /// <returns>A string in the form "~/views/{controller}/{action}.cshtml</returns>
    public static string View(this UrlHelper url, string action, string controller)
    {
        return string.Format("~/Views/{1}/{0}.cshtml", action, controller);
    }
}

What is the reason for having '//' in Python?

In Python 3, they made the / operator do a floating-point division, and added the // operator to do integer division (i.e., quotient without remainder); whereas in Python 2, the / operator was simply integer division, unless one of the operands was already a floating point number.

In Python 2.X:

>>> 10/3
3
>>> # To get a floating point number from integer division:
>>> 10.0/3
3.3333333333333335
>>> float(10)/3
3.3333333333333335

In Python 3:

>>> 10/3
3.3333333333333335
>>> 10//3
3

For further reference, see PEP238.

How to make a deep copy of Java ArrayList

Cloning the objects before adding them. For example, instead of newList.addAll(oldList);

for(Person p : oldList) {
    newList.add(p.clone());
}

Assuming clone is correctly overriden inPerson.

What does this format means T00:00:00.000Z?

As one person may have already suggested,

I passed the ISO 8601 date string directly to moment like so...

`moment.utc('2019-11-03T05:00:00.000Z').format('MM/DD/YYYY')`

or

`moment('2019-11-03T05:00:00.000Z').utc().format('MM/DD/YYYY')`

either of these solutions will give you the same result.

`console.log(moment('2019-11-03T05:00:00.000Z').utc().format('MM/DD/YYYY')) // 11/3/2019`

Plot smooth line with PyPlot

For this example spline works well, but if the function is not smooth inherently and you want to have smoothed version you can also try:

from scipy.ndimage.filters import gaussian_filter1d

ysmoothed = gaussian_filter1d(y, sigma=2)
plt.plot(x, ysmoothed)
plt.show()

if you increase sigma you can get a more smoothed function.

Proceed with caution with this one. It modifies the original values and may not be what you want.

docker-compose up for only certain containers

Oh, just with this:

$ docker-compose up client server database

How to convert R Markdown to PDF?

Only two steps:

  1. Install the latest release "pandoc" from here:

    https://github.com/jgm/pandoc/releases

  2. Call the function pandoc in the library(knitr)

    library(knitr)
    pandoc('input.md', format = 'latex')
    

Thus, you can convert your "input.md" into "input.pdf".

What's the difference between UTF-8 and UTF-8 without BOM?

This question already has a million-and-one answers and many of them are quite good, but I wanted to try and clarify when a BOM should or should not be used.

As mentioned, any use of the UTF BOM (Byte Order Mark) in determining whether a string is UTF-8 or not is educated guesswork. If there is proper metadata available (like charset="utf-8"), then you already know what you're supposed to be using, but otherwise you'll need to test and make some assumptions. This involves checking whether the file a string comes from begins with the hexadecimal byte code, EF BB BF.

If a byte code corresponding to the UTF-8 BOM is found, the probability is high enough to assume it's UTF-8 and you can go from there. When forced to make this guess, however, additional error checking while reading would still be a good idea in case something comes up garbled. You should only assume a BOM is not UTF-8 (i.e. latin-1 or ANSI) if the input definitely shouldn't be UTF-8 based on its source. If there is no BOM, however, you can simply determine whether it's supposed to be UTF-8 by validating against the encoding.

Why is a BOM not recommended?

  1. Non-Unicode-aware or poorly compliant software may assume it's latin-1 or ANSI and won't strip the BOM from the string, which can obviously cause issues.
  2. It's not really needed (just check if the contents are compliant and always use UTF-8 as the fallback when no compliant encoding can be found)

When should you encode with a BOM?

If you're unable to record the metadata in any other way (through a charset tag or file system meta), and the programs being used like BOMs, you should encode with a BOM. This is especially true on Windows where anything without a BOM is generally assumed to be using a legacy code page. The BOM tells programs like Office that, yes, the text in this file is Unicode; here's the encoding used.

When it comes down to it, the only files I ever really have problems with are CSV. Depending on the program, it either must, or must not have a BOM. For example, if you're using Excel 2007+ on Windows, it must be encoded with a BOM if you want to open it smoothly and not have to resort to importing the data.

set environment variable in python script

bash:

LD_LIBRARY_PATH=my_path
sqsub -np $1 /path/to/executable

Similar, in Python:

import os
import subprocess
import sys

os.environ['LD_LIBRARY_PATH'] = "my_path" # visible in this process + all children
subprocess.check_call(['sqsub', '-np', sys.argv[1], '/path/to/executable'],
                      env=dict(os.environ, SQSUB_VAR="visible in this subprocess"))

How to read specific lines from a file (by line number)?

Reading files is incredible fast. Reading a 100MB file takes less than 0.1 seconds (see my article Reading and Writing Files with Python). Hence you should read it completely and then work with the single lines.

What most answer here do is not wrong, but bad style. Opening files should always be done with with as it makes sure that the file is closed again.

So you should do it like this:

with open("path/to/file.txt") as f:
    lines = f.readlines()
print(lines[26])  # or whatever you want to do with this line
print(lines[30])  # or whatever you want to do with this line

Huge files

If you happen to have a huge file and memory consumption is a concern, you can process it line by line:

with open("path/to/file.txt") as f:
    for i, line in enumerate(f):
        pass  # process line i

How to create helper file full of functions in react native?

I am sure this can help. Create fileA anywhere in the directory and export all the functions.

export const func1=()=>{
    // do stuff
}
export const func2=()=>{
    // do stuff 
}
export const func3=()=>{
    // do stuff 
}
export const func4=()=>{
    // do stuff 
}
export const func5=()=>{
    // do stuff 
}

Here, in your React component class, you can simply write one import statement.

import React from 'react';
import {func1,func2,func3} from 'path_to_fileA';

class HtmlComponents extends React.Component {
    constructor(props){
        super(props);
        this.rippleClickFunction=this.rippleClickFunction.bind(this);
    }
    rippleClickFunction(){
        //do stuff. 
        // foo==bar
        func1(data);
        func2(data)
    }
   render() {
      return (
         <article>
             <h1>React Components</h1>
             <RippleButton onClick={this.rippleClickFunction}/>
         </article>
      );
   }
}

export default HtmlComponents;

How to generate .json file with PHP?

First, you need to decode it :

$jsonString = file_get_contents('jsonFile.json');
$data = json_decode($jsonString, true);

Then change the data :

$data[0]['activity_name'] = "TENNIS";
// or if you want to change all entries with activity_code "1"
foreach ($data as $key => $entry) {
    if ($entry['activity_code'] == '1') {
        $data[$key]['activity_name'] = "TENNIS";
    }
}

Then re-encode it and save it back in the file:

$newJsonString = json_encode($data);
file_put_contents('jsonFile.json', $newJsonString);

copy

What are the -Xms and -Xmx parameters when starting JVM?

The question itself has already been addressed above. Just adding part of the default values.

As per http://docs.oracle.com/cd/E13150_01/jrockit_jvm/jrockit/jrdocs/refman/optionX.html

The default value of Xmx will depend on platform and amount of memory available in the system.

jquery function setInterval

You can use it like this:

$(document).ready(function(){

    setTimeout("swapImages()",1000);

    function swapImages(){

        var active = $('.active'); 
        var next = ($('.active').next().length > 0) ? $('.active').next() : $('#siteNewsHead img:first');

        active.removeClass('active');
        next.addClass('active');
        setTimeout("swapImages()",1000);
}

});

Pass Hidden parameters using response.sendRedirect()

Using session, I successfully passed a parameter (name) from servlet #1 to servlet #2, using response.sendRedirect in servlet #1. Servlet #1 code:

protected void doPost(HttpServletRequest request, HttpServletResponse response) {
    String name = request.getParameter("name");
    String password = request.getParameter("password");
    ...
    request.getSession().setAttribute("name", name);
    response.sendRedirect("/todo.do");

In Servlet #2, you don't need to get name back. It's already connected to the session. You could do String name = (String) request.getSession().getAttribute("name"); ---but you don't need this.

If Servlet #2 calls a JSP, you can show name this way on the JSP webpage:

<h1>Welcome ${name}</h1>

javascript convert int to float

JavaScript only has a Number type that stores floating point values.

There is no int.

Edit:

If you want to format the number as a string with two digits after the decimal point use:

(4).toFixed(2)

Enter key press behaves like a Tab in Javascript

The simplest vanilla JS snippet I came up with:

document.addEventListener('keydown', function (event) {
  if (event.keyCode === 13 && event.target.nodeName === 'INPUT') {
    var form = event.target.form;
    var index = Array.prototype.indexOf.call(form, event.target);
    form.elements[index + 1].focus();
    event.preventDefault();
  }
});

Works in IE 9+ and modern browsers.

Text in Border CSS HTML

Text in Border with transparent text background

_x000D_
_x000D_
.box{
    background-image: url("https://i.stack.imgur.com/N39wV.jpg");
    width: 350px;
    padding: 10px;
}

/*begin first box*/
.first{
    width: 300px;
    height: 100px;
    margin: 10px;
    border-width: 0 2px 0 2px;
    border-color: #333;
    border-style: solid;
    position: relative;
}

.first span {
    position: absolute;
    display: flex;
    right: 0;
    left: 0;
    align-items: center;
}
.first .foo{
    top: -8px;
}
.first .bar{
    bottom: -8.5px;
}
.first span:before{
    margin-right: 15px;
}
.first span:after {
    margin-left: 15px;
}
.first span:before , .first span:after {
    content: ' ';
    height: 2px;
    background: #333;
    display: block;
    width: 50%;
}


/*begin second box*/
.second{
    width: 300px;
    height: 100px;
    margin: 10px;
    border-width: 2px 0 2px 0;
    border-color: #333;
    border-style: solid;
    position: relative;
}

.second span {
    position: absolute;
    top: 0;
    bottom: 0;
    display: flex;
    flex-direction: column;
    align-items: center;
}
.second .foo{
    left: -15px;
}
.second .bar{
    right: -15.5px;
}
.second span:before{
    margin-bottom: 15px;
}
.second span:after {
    margin-top: 15px;
}
.second span:before , .second span:after {
    content: ' ';
    width: 2px;
    background: #333;
    display: block;
    height: 50%;
}
_x000D_
<div class="box">
    <div class="first">
        <span class="foo">FOO</span>
        <span class="bar">BAR</span>
    </div>

   <br>

    <div class="second">
        <span class="foo">FOO</span>
        <span class="bar">BAR</span>
    </div>
</div>
_x000D_
_x000D_
_x000D_

How to get detailed list of connections to database in sql server 2005?

There is also who is active?:

Who is Active? is a comprehensive server activity stored procedure based on the SQL Server 2005 and 2008 dynamic management views (DMVs). Think of it as sp_who2 on a hefty dose of anabolic steroids

Using jQuery To Get Size of Viewport

To get size of viewport on load and on resize (based on SimaWB response):

function getViewport() {
    var viewportWidth = $(window).width();
    var viewportHeight = $(window).height();
    $('#viewport').html('Viewport: '+viewportWidth+' x '+viewportHeight+' px');
}

getViewport();

$(window).resize(function() {
    getViewport()
});

How to recover deleted rows from SQL server table?

What is gone is gone. The only protection I know of is regular backup.

How can I pause setInterval() functions?

i wrote a simple ES6 class that may come handy. inspired by https://stackoverflow.com/a/58580918/4907364 answer

export class IntervalTimer {
    private callbackStartTime;
    private remaining= 0;
    private paused= false;
    public timerId = null;
    private readonly _callback;
    private readonly _delay;

    constructor(callback, delay) {
        this._callback = callback;
        this._delay = delay;
    }

    pause() {
        if (!this.paused) {
            this.clear();
            this.remaining = new Date().getTime() - this.callbackStartTime;
            this.paused = true;
        }
    }

    resume() {
        if (this.paused) {
            if (this.remaining) {
                setTimeout(() => {
                    this.run();
                    this.paused = false;
                    this.start();
                }, this.remaining);
            } else {
                this.paused = false;
                this.start();
            }
        }
    }

    clear() {
        clearInterval(this.timerId);
    }

    start() {
        this.clear();
        this.timerId = setInterval(() => {
            this.run();
        }, this._delay);
    }

    private run() {
        this.callbackStartTime = new Date().getTime();
        this._callback();
    }
}

usage is pretty straightforward,

const interval = new IntervalTimer(console.log(aaa), 3000);
interval.start();
interval.pause();
interval.resume();
interval.clear();

Comments in Markdown

Vim Instant-Markdown users need to use

<!---
First comment line...
//
_NO_BLANK_LINES_ARE_ALLOWED_
//
_and_try_to_avoid_double_minuses_like_this_: --
//
last comment line.
-->

Closing Application with Exit button

this.close_Button = (Button)this.findViewById(R.id.close);
   this.close_Button.setOnClickListener(new OnClickListener() {
     @Override
     public void onClick(View v) {
        finish();
     }
  });

finish() - Call this when your activity is done and should be closed. The ActivityResult is propagated back to whoever launched you via onActivityResult().

Show/hide widgets in Flutter programmatically

Invisible: The widget takes physical space on the screen but not visible to user.

Gone: The widget doesn't take any physical space and is completely gone.


Invisible example

Visibility(
  child: Text("Invisible"),
  maintainSize: true, 
  maintainAnimation: true,
  maintainState: true,
  visible: false, 
),

Gone example

Visibility(
  child: Text("Gone"),
  visible: false,
),

Alternatively, you can use if condition for both invisible and gone.

Column(
  children: <Widget>[
    if (show) Text("This can be visible/not depending on condition"),
    Text("This is always visible"),
  ],
) 

Regex pattern for checking if a string starts with a certain substring?

For the extension method fans:

public static bool RegexStartsWith(this string str, params string[] patterns)
{
    return patterns.Any(pattern => 
       Regex.Match(str, "^("+pattern+")").Success);
}

Usage

var answer = str.RegexStartsWith("mailto","ftp","joe");
//or
var answer2 = str.RegexStartsWith("mailto|ftp|joe");
//or
bool startsWithWhiteSpace = "  does this start with space or tab?".RegexStartsWith(@"\s");

Get driving directions using Google Maps API v2

You can also try the following project that aims to help use that api. It's here:https://github.com/MathiasSeguy-Android2EE/GDirectionsApiUtils

How it works, definitly simply:

public class MainActivity extends ActionBarActivity implements DCACallBack{
/**
 * Get the Google Direction between mDevice location and the touched location using the     Walk
 * @param point
 */
private void getDirections(LatLng point) {
     GDirectionsApiUtils.getDirection(this, mDeviceLatlong, point,     GDirectionsApiUtils.MODE_WALKING);
}

/*
 * The callback
 * When the direction is built from the google server and parsed, this method is called and give you the expected direction
 */
@Override
public void onDirectionLoaded(List<GDirection> directions) {        
    // Display the direction or use the DirectionsApiUtils
    for(GDirection direction:directions) {
        Log.e("MainActivity", "onDirectionLoaded : Draw GDirections Called with path " + directions);
        GDirectionsApiUtils.drawGDirection(direction, mMap);
    }
}

How to send data to COM PORT using JAVA?

An alternative to javax.comm is the rxtx library which supports more platforms than javax.comm.

SaveFileDialog setting default path and file type?

Environment.GetSystemVariable("%SystemDrive%"); will provide the drive OS installed, and you can set filters to savedialog Obtain file path of C# save dialog box

Center an item with position: relative

Much simpler:

position: relative; 
left: 50%;
transform: translateX(-50%);

You are now centered in your parent element. You can do that vertically too.

Cannot use string offset as an array in php

I just want to explain my solving for the same problem.

my code before(given same error):

$arr2= ""; // this is the problem and solve by replace this $arr2 = array();
for($i=2;$i<count($arrdata);$i++){
    $rowx = explode(" ",$arrdata[$i]);
    $arr1= ""; // and this is too
    for($x=0;$x<count($rowx);$x++){
        if($rowx[$x]!=""){
            $arr1[] = $rowx[$x];
        }
    }
    $arr2[] = $arr1;
}
for($i=0;$i<count($arr2);$i++){
    $td .="<tr>";
    for($j=0;$j<count($hcol)-1;$j++){
        $td .= "<td style='border-right:0px solid #000'>".$arr2[$i][$j]."</td>"; //and it's($arr2[$i][$j]) give an error: Cannot use string offset as an array
    }
    $td .="</tr>";
}

my code after and solved it:

$arr2= array(); //change this from $arr2="";
for($i=2;$i<count($arrdata);$i++){
    $rowx = explode(" ",$arrdata[$i]);
    $arr1=array(); //and this
    for($x=0;$x<count($rowx);$x++){
        if($rowx[$x]!=""){
            $arr1[] = $rowx[$x];
        }
    }
    $arr2[] = $arr1;
}
for($i=0;$i<count($arr2);$i++){
    $td .="<tr>";
    for($j=0;$j<count($hcol)-1;$j++){
        $td .= "<td style='border-right:0px solid #000'>".$arr2[$i][$j]."</td>";
    }
    $td .="</tr>";
}

Thank's. Hope it's helped, and sorry if my english mess like boy's room :D

is inaccessible due to its protection level

The reason being you can not access protected member data through the instance of the class.

Reason why it is not allowed is explained in this blog

Angular2 @Input to a property with get/set

Updated accepted answer to angular 7.0.1 on stackblitz here: https://stackblitz.com/edit/angular-inputsetter?embed=1&file=src/app/app.component.ts

directives are no more in Component decorator options. So I have provided sub directive to app module.

thank you @thierry-templier!

Eclipse: Java was started but returned error code=13

I also faced the error code when i upgraded my java version to 1.8. The problem was with my eclipse.

My jdk which was installed on my system is of 32 - bit and my eclipse was of 64 - bit.

So solve this problem i downloaded the 32 - bit eclipse.

IMO this Architecture miss match problem

Plese match your architecture type of JDK and eclipse.

Injecting content into specific sections from a partial view ASP.NET MVC 3 with Razor View Engine

This is quite a popular question, so I'll post my solution up.

I had the same problem and although it isn't ideal, I think it actually works quite well and doesn't make the partial dependant on the view.

My scenario was that an action was accessible by itself but also could be embedded into a a view - a google map.

In my _layout I have:

@RenderSection("body_scripts", false)

In my index view I have:

@Html.Partial("Clients")
@section body_scripts
{
    @Html.Partial("Clients_Scripts")
}

In my clients view I have (all the map and assoc. html):

@section body_scripts
{
    @Html.Partial("Clients_Scripts")
}

My Clients_Scripts view contains the javascript to be rendered onto the page.

This way my script is isolated and can be rendered into the page where required, with the body_scripts tag only being rendered on the first occurrence that the razor view engine finds it.

That lets me have everything separated - it's a solution that works quite well for me, others may have issues with it, but it does patch the "by design" hole.

Making text bold using attributed string in swift

edit/update: Xcode 8.3.2 • Swift 3.1

If you know HTML and CSS you can use it to easily control the font style, color and size of your attributed string as follow:

extension String {
    var html2AttStr: NSAttributedString? {
        return try? NSAttributedString(data: Data(utf8), options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType, NSCharacterEncodingDocumentAttribute: String.Encoding.utf8.rawValue], documentAttributes: nil)
    }
}

"<style type=\"text/css\">#red{color:#F00}#green{color:#0F0}#blue{color: #00F; font-weight: Bold; font-size: 32}</style><span id=\"red\" >Red,</span><span id=\"green\" > Green </span><span id=\"blue\">and Blue</span>".html2AttStr

How to check if smtp is working from commandline (Linux)

Not sure if this help or not but this is a command line tool which let you simply send test mails from a SMTP server priodically. http://code.google.com/p/woodpecker-tester/

Delete terminal history in Linux

If you use bash, then the terminal history is saved in a file called .bash_history. Delete it, and history will be gone.

However, for MySQL the better approach is not to enter the password in the command line. If you just specify the -p option, without a value, then you will be prompted for the password and it won't be logged.

Another option, if you don't want to enter your password every time, is to store it in a my.cnf file. Create a file named ~/.my.cnf with something like:

[client]
user = <username>
password = <password>

Make sure to change the file permissions so that only you can read the file.

Of course, this way your password is still saved in a plaintext file in your home directory, just like it was previously saved in .bash_history.

How can I check if my Element ID has focus?

If you want to use jquery $("..").is(":focus").

You can take a look at this stack

How to parse unix timestamp to time.Time

You can directly use time.Unix function of time which converts the unix time stamp to UTC

package main

import (
  "fmt"
  "time"
)


func main() {
    unixTimeUTC:=time.Unix(1405544146, 0) //gives unix time stamp in utc 

    unitTimeInRFC3339 :=unixTimeUTC.Format(time.RFC3339) // converts utc time to RFC3339 format

    fmt.Println("unix time stamp in UTC :--->",unixTimeUTC)
    fmt.Println("unix time stamp in unitTimeInRFC3339 format :->",unitTimeInRFC3339)
}

Output

unix time stamp in UTC :---> 2014-07-16 20:55:46 +0000 UTC
unix time stamp in unitTimeInRFC3339 format :----> 2014-07-16T20:55:46Z

Check in Go Playground: https://play.golang.org/p/5FtRdnkxAd

JavaScript code to stop form submission

Simply do it....

<form>
<!-- Your Input Elements -->
</form>

and here goes your JQuery

$(document).on('submit', 'form', function(e){
    e.preventDefault();
    //your code goes here
    //100% works
    return;
});

Twitter Bootstrap and ASP.NET GridView

You need to set useaccessibleheader attribute of the gridview to true and also then also specify a TableSection to be a header after calling the DataBind() method on you GridView object. So if your grid view is mygv

mygv.UseAccessibleHeader = True
mygv.HeaderRow.TableSection = TableRowSection.TableHeader

This should result in a proper formatted grid with thead and tbody tags

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

unset($a->new_property);

This works for array elements, variables, and object attributes.

Example:

$a = new stdClass();

$a->new_property = 'foo';
var_export($a);  // -> stdClass::__set_state(array('new_property' => 'foo'))

unset($a->new_property);
var_export($a);  // -> stdClass::__set_state(array())

How to remove title bar from the android activity?

You can try:

<activity android:name=".YourActivityName"
          android:theme="@style/Theme.Design.NoActionBar">

that works for me

Changing default startup directory for command prompt in Windows 7

Keep the opening of the command prompt clean. Avoid editing the registry key and adding an Autorun, it may come back to bite you.
Create a simple batch file and save it in the C:\Windows or C:\Windows\System32 folder. I call mine !.bat (exclamation mark). It has the following commands:

@echo off c: cd \ cls whoami

It goes to the folder where I need to work, clears the screen and tells me what security context I'm in.

Best way to run scheduled tasks

Use Windows Scheduler to run a web page.

To prevent malicous user or search engine spiders to run it, when you setup the scheduled task, simply call the web page with a querystring, ie : mypage.aspx?from=scheduledtask

Then in the page load, simply use a condition : if (Request.Querystring["from"] == "scheduledtask") { //executetask }

This way no search engine spider or malicious user will be able to execute your scheduled task.

How to get the Android Emulator's IP address?

If you do truly want the IP assigned to your emulator:

adb shell
ifconfig eth0

Which will give you something like:

eth0: ip 10.0.2.15 mask 255.255.255.0 flags [up broadcast running multicast]

Dark color scheme for Eclipse

As I replied to "Is there a simple, consistent way to change the color scheme of Eclipse editors?":

I've been looking for this too and after a bit of research found a workable solution. This is based on the FDT editor for Eclipse, but I'm sure you could apply the same logic to other editors.

My blog post: Howto create a color-scheme for FDT

Hope this helps!

Angular, content type is not being sent with $http

Just to show an example of how to dynamically add the "Content-type" header to every POST request. In may case I'm passing POST params as query string, that is done using the transformRequest. In this case its value is application/x-www-form-urlencoded.

// set Content-Type for POST requests
angular.module('myApp').run(basicAuth);
function basicAuth($http) {
    $http.defaults.headers.post = {'Content-Type': 'application/x-www-form-urlencoded'};
}

Then from the interceptor in the request method before return the config object

// if header['Content-type'] is a POST then add data
'request': function (config) {
  if (
    angular.isDefined(config.headers['Content-Type']) 
    && !angular.isDefined(config.data)
  ) {
    config.data = '';
  }
  return config;
}

How to list imported modules?

print [key for key in locals().keys()
       if isinstance(locals()[key], type(sys)) and not key.startswith('__')]

How to use TLS 1.2 in Java 6

Public Oracle Java 6 releases do not support TLSv1.2. Paid-for releases of Java 6 (post-EOL) might. (UPDATE - TLSv1.1 is available for Java 1.6 from update 111 onwards; source)

Contact Oracle sales.

Other alternatives are:

  • Use an alternative JCE implementation such as Bouncy Castle. See this answer for details on how to do it. It changes the default SSLSocketFactory implementation, so that your application will use BC transparently. (Other answers show how to use the BC SSLSocketFactory implementation explicitly, but that approach will entail modifying application or library code that that is opening sockets.)

  • Use an IBM Java 6 ... if available for your platform. According to "IBM SDK, Java Technology Edition fixes to mitigate against the POODLE security vulnerability (CVE-2014-3566)":

    "TLSv1.1 and TLSv1.2 are available only for Java 6 service refresh 10, Java 6.0.1 service refresh 1 (J9 VM2.6), and later releases."


However, I'd advise upgrading to a Java 11 (now). Java 6 was EOL'd in Feb 2013, and continuing to use it is potentially risky. Free Oracle Java 8 is EOL for many use-cases. (Tell or remind the boss / the client. They need to know.)

Strange "java.lang.NoClassDefFoundError" in Eclipse

If you are using Eclipse try Project>clean and then try to restart the server

How to apply font anti-alias effects in CSS?

Works the best. If you want to use it sitewide, without having to add this syntax to every class or ID, add the following CSS to your css body:

body { 
    -webkit-font-smoothing: antialiased;
    text-shadow: 1px 1px 1px rgba(0,0,0,0.004);
    background: url('./images/background.png');
    text-align: left;
    margin: auto;

}

In TensorFlow, what is the difference between Session.run() and Tensor.eval()?

If you have a Tensor t, calling t.eval() is equivalent to calling tf.get_default_session().run(t).

You can make a session the default as follows:

t = tf.constant(42.0)
sess = tf.Session()
with sess.as_default():   # or `with sess:` to close on exit
    assert sess is tf.get_default_session()
    assert t.eval() == sess.run(t)

The most important difference is that you can use sess.run() to fetch the values of many tensors in the same step:

t = tf.constant(42.0)
u = tf.constant(37.0)
tu = tf.mul(t, u)
ut = tf.mul(u, t)
with sess.as_default():
   tu.eval()  # runs one step
   ut.eval()  # runs one step
   sess.run([tu, ut])  # evaluates both tensors in a single step

Note that each call to eval and run will execute the whole graph from scratch. To cache the result of a computation, assign it to a tf.Variable.

Is it possible only to declare a variable without assigning any value in Python?

Why not just do this:

var = None

Python is dynamic, so you don't need to declare things; they exist automatically in the first scope where they're assigned. So, all you need is a regular old assignment statement as above.

This is nice, because you'll never end up with an uninitialized variable. But be careful -- this doesn't mean that you won't end up with incorrectly initialized variables. If you init something to None, make sure that's what you really want, and assign something more meaningful if you can.

Dockerfile copy keep subdirectory structure

Alternatively you can use a "." instead of *, as this will take all the files in the working directory, include the folders and subfolders:

FROM ubuntu
COPY . /
RUN ls -la /

HTML Table width in percentage, table rows separated equally

you can try this, I would do it with CSS, but i think you want it with tables without CSS.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
   <body leftmargin=0 rightmargin=0>
      <table cellpadding="0" cellspacing="0" width="100%" border="1" height="350px"> 
         <tr>
            <td width="25%">&nbsp;</td>
            <td width="25%">&nbsp;</td>
            <td width="25%">&nbsp;</td>
            <td width="25%">&nbsp;</td>
         </tr>
      </table> 
   </body>
</html>

iPhone App Minus App Store?

If you patch /Developer/Platforms/iPhoneOS.platform/Info.plist and then try to debug a application running on the device using a real development provisionen profile from Apple it will probably not work. Symptoms are weird error messages from com.apple.debugserver and that you can use any bundle identifier without getting a error when building in Xcode. The solution is to restore Info.plist.

How can I fill a column with random numbers in SQL? I get the same value in every row

Instead of rand(), use newid(), which is recalculated for each row in the result. The usual way is to use the modulo of the checksum. Note that checksum(newid()) can produce -2,147,483,648 and cause integer overflow on abs(), so we need to use modulo on the checksum return value before converting it to absolute value.

UPDATE CattleProds
SET    SheepTherapy = abs(checksum(NewId()) % 10000)
WHERE  SheepTherapy IS NULL

This generates a random number between 0 and 9999.

Switch to selected tab by name in Jquery-UI Tabs

I could not get the previous answer to work. I did the following to get the index of the tab by name:

var index = $('#tabs a[href="#simple-tab-2"]').parent().index();
$('#tabs').tabs('select', index);

GoTo Next Iteration in For Loop in java

If you want to skip current iteration, use continue;.

for(int i = 0; i < 5; i++){
    if (i == 2){
        continue;
    }
 }

Need to break out of the whole loop? Use break;

for(int i = 0; i < 5; i++){
    if (i == 2){
        break;
    }
}

If you need to break out of more than one loop use break someLabel;

outerLoop:                                           // Label the loop
for(int j = 0; j < 5; j++){
     for(int i = 0; i < 5; i++){
        if (i==2){
          break outerLoop;
        }
     }
  }

*Note that in this case you are not marking a point in code to jump to, you are labeling the loop! So after the break the code will continue right after the loop!

When you need to skip one iteration in nested loops use continue someLabel;, but you can also combine them all.

outerLoop:
for(int j = 0; j < 10; j++){
     innerLoop:
     for(int i = 0; i < 10; i++){
        if (i + j == 2){
          continue innerLoop;
        }
        if (i + j == 4){
          continue outerLoop;
        }
        if (i + j == 6){
          break innerLoop;
        }
        if (i + j == 8){
          break outerLoop;
        }
     }
  }

How do I clear the std::queue efficiently?

Yes - a bit of a misfeature of the queue class, IMHO. This is what I do:

#include <queue>
using namespace std;;

int main() {
    queue <int> q1;
    // stuff
    q1 = queue<int>();  
}

Open a local HTML file using window.open in Chrome

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

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

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

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

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

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

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

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

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

Visual Studio 2015 is very slow

This may help someone visiting this question.

I had an issue where it was slow only in very large files. When opening braces such as { or after completing a type, such as decimal it would hang.

This was resolved by disabling the "Show a completion list after every character is typed" setting in Options => Text Editor => C# => Intellisense

ORDER BY date and time BEFORE GROUP BY name in mysql

This worked for me:

SELECT *
FROM your_table
WHERE id IN (
    SELECT MAX(id)
    FROM your_table
    GROUP BY name
);

How to get different colored lines for different plots in a single figure?

TL;DR No, it can't be done automatically. Yes, it is possible.

import matplotlib.pyplot as plt
my_colors = plt.rcParams['axes.prop_cycle']() # <<< note that we CALL the prop_cycle
fig, axes = plt.subplots(2,3)
for ax in axes.flatten(): ax.plot((0,1), (0,1), **next(my_colors))

enter image description here Each plot (axes) in a figure (figure) has its own cycle of colors — if you don't force a different color for each plot, all the plots share the same order of colors but, if we stretch a bit what "automatically" means, it can be done.


The OP wrote

[...] I have to identify each plot with a different color which should be automatically generated by [Matplotlib].

But... Matplotlib automatically generates different colors for each different curve

In [10]: import numpy as np
    ...: import matplotlib.pyplot as plt

In [11]: plt.plot((0,1), (0,1), (1,2), (1,0));
Out[11]:

enter image description here

So why the OP request? If we continue to read, we have

Can you please give me a method to put different colors for different plots in the same figure?

and it make sense, because each plot (each axes in Matplotlib's parlance) has its own color_cycle (or rather, in 2018, its prop_cycle) and each plot (axes) reuses the same colors in the same order.

In [12]: fig, axes = plt.subplots(2,3)

In [13]: for ax in axes.flatten():
    ...:     ax.plot((0,1), (0,1))

enter image description here

If this is the meaning of the original question, one possibility is to explicitly name a different color for each plot.

If the plots (as it often happens) are generated in a loop we must have an additional loop variable to override the color automatically chosen by Matplotlib.

In [14]: fig, axes = plt.subplots(2,3)

In [15]: for ax, short_color_name in zip(axes.flatten(), 'brgkyc'):
    ...:     ax.plot((0,1), (0,1), short_color_name)

enter image description here

Another possibility is to instantiate a cycler object

from cycler import cycler
my_cycler = cycler('color', ['k', 'r']) * cycler('linewidth', [1., 1.5, 2.])
actual_cycler = my_cycler()

fig, axes = plt.subplots(2,3)
for ax in axes.flat:
    ax.plot((0,1), (0,1), **next(actual_cycler))

enter image description here

Note that type(my_cycler) is cycler.Cycler but type(actual_cycler) is itertools.cycle.

Flex-box: Align last row to grid

Using flexbox and a few media queries, I made this little work-around: http://codepen.io/una/pen/yNEGjv (its a bit hacky but works):

.container {
  display: flex;
  flex-flow: row wrap;
  justify-content: flex-start;
  max-width: 1200px;
  margin: 0 auto;
}

.item {
  background-color: gray;
  height: 300px;
  flex: 0 30%;
  margin: 10px;

  @media (max-width: 700px) {
     flex: 0 45%;
  }

  @media (max-width: 420px) {
    flex: 0 100%;
  }

  &:nth-child(3n-1) {
    margin-left: 10px;
    margin-right: 10px;
  }
}

Adding calculated column(s) to a dataframe in pandas

You could have is_hammer in terms of row["Open"] etc. as follows

def is_hammer(rOpen,rLow,rClose,rHigh):
    return lower_wick_at_least_twice_real_body(rOpen,rLow,rClose) \
       and closed_in_top_half_of_range(rHigh,rLow,rClose)

Then you can use map:

df["isHammer"] = map(is_hammer, df["Open"], df["Low"], df["Close"], df["High"])

Structure padding and packing

Padding aligns structure members to "natural" address boundaries - say, int members would have offsets, which are mod(4) == 0 on 32-bit platform. Padding is on by default. It inserts the following "gaps" into your first structure:

struct mystruct_A {
    char a;
    char gap_0[3]; /* inserted by compiler: for alignment of b */
    int b;
    char c;
    char gap_1[3]; /* -"-: for alignment of the whole struct in an array */
} x;

Packing, on the other hand prevents compiler from doing padding - this has to be explicitly requested - under GCC it's __attribute__((__packed__)), so the following:

struct __attribute__((__packed__)) mystruct_A {
    char a;
    int b;
    char c;
};

would produce structure of size 6 on a 32-bit architecture.

A note though - unaligned memory access is slower on architectures that allow it (like x86 and amd64), and is explicitly prohibited on strict alignment architectures like SPARC.

Find the most frequent number in a NumPy array

I like the solution by JoshAdel.

But there is just one catch.

The np.bincount() solution only works on numbers.

If you have strings, collections.Counter solution will work for you.

How do I put an image into my picturebox using ImageLocation?

Setting the image using picture.ImageLocation() works fine, but you are using a relative path. Check your path against the location of the .exe after it is built.

For example, if your .exe is located at:

<project folder>/bin/Debug/app.exe

The image would have to be at:

<project folder>/bin/Image/1.jpg


Of course, you could just set the image at design-time (the Image property on the PictureBox property sheet).

If you must set it at run-time, one way to make sure you know the location of the image is to add the image file to your project. For example, add a new folder to your project, name it Image. Right-click the folder, choose "Add existing item" and browse to your image (be sure the file filter is set to show image files). After adding the image, in the property sheet set the Copy to Output Directory to Copy if newer.

At this point the image file will be copied when you build the application and you can use

picture.ImageLocation = @"Image\1.jpg"; 

Java associative-array

Actually Java does support associative arrays they are called dictionaries!

How to encode text to base64 in python

To compatibility with both py2 and py3

import six
import base64

def b64encode(source):
    if six.PY3:
        source = source.encode('utf-8')
    content = base64.b64encode(source).decode('utf-8')

Set adb vendor keys

look at this url Android adb devices unauthorized else briefly do the following:

  1. look for adbkey with not extension in the platform-tools/.android and delete this file
  2. look at C:\Users\*username*\.android) and delete adbkey
  3. C:\Windows\System32\config\systemprofile\.android and delete adbkey

You may find it in one of the directories above. Or just search adbkey in the Parent folders above then locate and delete.

How to continue the code on the next line in VBA

In VBA (and VB.NET) the line terminator (carriage return) is used to signal the end of a statement. To break long statements into several lines, you need to

Use the line-continuation character, which is an underscore (_), at the point at which you want the line to break. The underscore must be immediately preceded by a space and immediately followed by a line terminator (carriage return).

(From How to: Break and Combine Statements in Code)

In other words: Whenever the interpreter encounters the sequence <space>_<line terminator>, it is ignored and parsing continues on the next line. Note, that even when ignored, the line continuation still acts as a token separator, so it cannot be used in the middle of a variable name, for example. You also cannot continue a comment by using a line-continuation character.

To break the statement in your question into several lines you could do the following:

U_matrix(i, j, n + 1) = _
     k * b_xyt(xi, yi, tn) / (4 * hx * hy) * U_matrix(i + 1, j + 1, n) + _
     (k * (a_xyt(xi, yi, tn) / hx ^ 2 + d_xyt(xi, yi, tn) / (2 * hx)))

(Leading whitespaces are ignored.)

Accessing Object Memory Address

With ctypes, you can achieve the same thing with

>>> import ctypes
>>> a = (1,2,3)
>>> ctypes.addressof(a)
3077760748L

Documentation:

addressof(C instance) -> integer
Return the address of the C instance internal buffer

Note that in CPython, currently id(a) == ctypes.addressof(a), but ctypes.addressof should return the real address for each Python implementation, if

  • ctypes is supported
  • memory pointers are a valid notion.

Edit: added information about interpreter-independence of ctypes

How to display the string html contents into webbrowser control?

Instead of navigating to blank, you can do

webBrowser1.DocumentText="0";
webBrowser1.Document.OpenNew(true);
webBrowser1.Document.Write(theHTML);
webBrowser1.Refresh();

No need to wait for events or anything else. You can check the MSDN for OpenNew, while I have tested the initial DocumentText assignment in one of my projects and it works.

How to deserialize a JObject to .NET object

According to this post, it's much better now:

// pick out one album
JObject jalbum = albums[0] as JObject;

// Copy to a static Album instance
Album album = jalbum.ToObject<Album>();

Documentation: Convert JSON to a Type

How to detect simple geometric shapes using OpenCV

You can also use template matching to detect shapes inside an image.

Shrink to fit content in flexbox, or flex-basis: content workaround?

I want columns One and Two to shrink/grow to fit rather than being fixed.

Have you tried: flex-basis: auto

or this:

flex: 1 1 auto, which is short for:

  • flex-grow: 1 (grow proportionally)
  • flex-shrink: 1 (shrink proportionally)
  • flex-basis: auto (initial size based on content size)

or this:

main > section:first-child {
    flex: 1 1 auto;
    overflow-y: auto;
}

main > section:nth-child(2) {
    flex: 1 1 auto;
    overflow-y: auto;
}

main > section:last-child {
    flex: 20 1 auto;
    display: flex;
    flex-direction: column;  
}

revised demo

Related:

Reset select value to default

One nice clean way is to add a data-default attribute to the select

<select id="my_select" data-default="b">
...
</select>

An then the code is really simple:

$("#reset").on("click", function () {
    var $select = $('#my_select');
    $select.val($select.data('default'));
});

Live example: http://jsfiddle.net/T8sCf/7/

Is there a replacement for unistd.h for Windows (Visual C)?

No, IIRC there is no getopt() on Windows.

Boost, however, has the program_options library... which works okay. It will seem like overkill at first, but it isn't terrible, especially considering it can handle setting program options in configuration files and environment variables in addition to command line options.

How to split a single column values to multiple column values?

Here is how I did this on a SQLite database:

SELECT SUBSTR(name, 1,INSTR(name, " ")-1) as Firstname,
SUBSTR(name, INSTR(name," ")+1, LENGTH(name)) as Lastname
FROM YourTable;

Hope it helps.

Best way to access a control on another form in Windows Forms?

The first is not working of course. The controls on a form are private, visible only for that form by design.

To make it all public is also not the best way.

If I would like to expose something to the outer world (which also can mean an another form), I make a public property for it.

public Boolean nameOfControlVisible
{
    get { return this.nameOfControl.Visible; }
    set { this.nameOfControl.Visible = value; }
}

You can use this public property to hide or show the control or to ask the control current visibility property:

otherForm.nameOfControlVisible = true;

You can also expose full controls, but I think it is too much, you should make visible only the properties you really want to use from outside the current form.

public ControlType nameOfControlP
{
    get { return this.nameOfControl; }
    set { this.nameOfControl = value; }
}

MVC 4 Razor adding input type date

If you want to use @Html.EditorFor() you have to use jQuery ui and update your Asp.net Mvc to 5.2.6.0 with NuGet Package Manager.

@Html.EditorFor(m => m.EntryDate, new { htmlAttributes = new { @class = "datepicker" } })

@section Scripts {

@Scripts.Render("~/bundles/jqueryval")

<script>

    $(document).ready(function(){

      $('.datepicker').datepicker();

     });

</script>

}

What's the best way to center your HTML email content in the browser window (or email client preview pane)?

CSS in emails is a pain. You'll probably need tables unfortunately, because CSS is not greatly supported in all email clients.

That said, use an HTML Transitional DOCTYPE, not XHTML, and use <center>.

Put Excel-VBA code in module or sheet?

I would suggest separating your code based on the functionality and purpose specific to each sheet or module. In this manner, you would only put code relative to a sheet's UI inside the sheet's module and only put code related to modules in respective modules. Also, use separate modules to encapsulate code that is shared or reused among several different sheets.

For example, let's say you multiple sheets that are responsible for displaying data from a database in a special way. What kinds of functionality do we have in this situation? We have functionality related to each specific sheet, tasks related to getting data from the database, and tasks related to populating a sheet with data. In this case, I might start with a module for the data access, a module for populating a sheet with data, and within each sheet I'd have code for accessing code in those modules.

It might be laid out like this.

Module: DataAccess:

Function GetData(strTableName As String, strCondition1 As String) As Recordset
    'Code Related to getting data from the database'
End Function

Module: PopulateSheet:

Sub PopulateASheet(wsSheet As Worksheet, rs As Recordset)
    'Code to populate a worksheet '
End Function

Sheet: Sheet1 Code:

Sub GetDataAndPopulate()
    'Sample Code'
     Dim rs As New Recordset
     Dim ws As Worksheet
     Dim strParam As String
     Set ws = ActiveSheet
     strParam = ws.Range("A1").Value

     Set rs = GetData("Orders",strParam)

     PopulateASheet ws, rs
End Sub

Sub Button1_Click()
    Call GetDataAndPopulate
End Sub

Does VBA have Dictionary Structure?

You can access a non-Native HashTable through System.Collections.HashTable.

HashTable

Represents a collection of key/value pairs that are organized based on the hash code of the key.

Not sure you would ever want to use this over Scripting.Dictionary but adding here for the sake of completeness. You can review the methods in case there are some of interest e.g. Clone, CopyTo

Example:

Option Explicit

Public Sub UsingHashTable()

    Dim h As Object
    Set h = CreateObject("System.Collections.HashTable")
   
    h.Add "A", 1
    ' h.Add "A", 1  ''<< Will throw duplicate key error
    h.Add "B", 2
    h("B") = 2
      
    Dim keys As mscorlib.IEnumerable 'Need to cast in order to enumerate  'https://stackoverflow.com/a/56705428/6241235
    
    Set keys = h.keys
    
    Dim k As Variant
    
    For Each k In keys
        Debug.Print k, h(k)                      'outputs the key and its associated value
    Next
    
End Sub

This answer by @MathieuGuindon gives plenty of detail about HashTable and also why it is necessary to use mscorlib.IEnumerable (early bound reference to mscorlib) in order to enumerate the key:value pairs.


C++ Convert string (or char*) to wstring (or wchar_t*)

std::string -> wchar_t[] with safe mbstowcs_s function:

auto ws = std::make_unique<wchar_t[]>(s.size() + 1);
mbstowcs_s(nullptr, ws.get(), s.size() + 1, s.c_str(), s.size());

This is from my sample code

How to get html to print return value of javascript function?

There are some options to do that.

One would be:

document.write(produceMessage())

Other would be appending some element in your document this way:

var span = document.createElement("span");
span.appendChild(document.createTextNode(produceMessage()));
document.body.appendChild(span);

Or just:

document.body.appendChild(document.createTextNode(produceMessage()));

If you're using jQuery, you can do this:

$(document.body).append(produceMessage());

Parsing domain from a URL

I've found that @philfreo's solution (referenced from php.net) is pretty well to get fine result but in some cases it shows php's "notice" and "Strict Standards" message. Here a fixed version of this code.

function getHost($url) { 
   $parseUrl = parse_url(trim($url)); 
   if(isset($parseUrl['host']))
   {
       $host = $parseUrl['host'];
   }
   else
   {
        $path = explode('/', $parseUrl['path']);
        $host = $path[0];
   }
   return trim($host); 
} 

echo getHost("http://example.com/anything.html");           // example.com
echo getHost("http://www.example.net/directory/post.php");  // www.example.net
echo getHost("https://example.co.uk");                      // example.co.uk
echo getHost("www.example.net");                            // example.net
echo getHost("subdomain.example.net/anything");             // subdomain.example.net
echo getHost("example.net");                                // example.net

Databinding an enum property to a ComboBox in WPF

Try using

<ComboBox ItemsSource="{Binding Source={StaticResource ExampleEnumValues}}"
    SelectedValue="{Binding Path=ExampleProperty}" />

how to end ng serve or firebase serve

it is enough to modify something in your text editor and reload localhost. all your connection will be lost nd you have opsibility to ng serve the new project in the console.

Maximum Java heap size of a 32-bit JVM on a 64-bit OS

The limitation also comes from the fact that for a 32 bit VM, the heap itself has to start at address zero if you want all those 4GB.

Think about it, if you want to reference something via:

0000....0001

i.e.: a reference that has this particular bits representation, it means you are trying to access the very first memory from the heap. For that to be possible, the heap has to start at address zero. But that never happens, it starts at some offset from zero:

    | ....               .... {heap_start .... heap_end} ... |
 --> (this can't be referenced) <--

Because heap never starts from address zero in an OS, there are quite a few bits that are never used from a 32 bits reference, and as such the heap that can be referenced is lower.

Make Font Awesome icons in a circle?

You can also do this. I wanted to add a circle around my icomoon icons. Here is the code.

span {
font-size: 54px;
border-radius: 50%;
border: 10px solid rgb(205, 209, 215);
padding: 30px;
}

ORA-01008: not all variables bound. They are bound

I know this is an old question, but it hasn't been correctly addressed, so I'm answering it for others who may run into this problem.

By default Oracle's ODP.net binds variables by position, and treats each position as a new variable.

Treating each copy as a different variable and setting it's value multiple times is a workaround and a pain, as furman87 mentioned, and could lead to bugs, if you are trying to rewrite the query and move things around.

The correct way is to set the BindByName property of OracleCommand to true as below:

var cmd = new OracleCommand(cmdtxt, conn);
cmd.BindByName = true;

You could also create a new class to encapsulate OracleCommand setting the BindByName to true on instantiation, so you don't have to set the value each time. This is discussed in this post

Using Composer's Autoload

The composer documentation states that:

After adding the autoload field, you have to re-run install to re-generate the vendor/autoload.php file.

Assuming your "src" dir resides at the same level as "vendor" dir:

  • src
    • AppName
  • vendor
  • composer.json

the following config is absolutely correct:

{
    "autoload": {
        "psr-0": {"AppName": "src/"}
    }
}

but you must re-update/install dependencies to make it work for you, i.e. run:

php composer.phar update

This command will get the latest versions of the dependencies and update the file "vendor/composer/autoload_namespaces.php" to match your configuration.

Also as noted by @Dom, you can use composer dump-autoload to update the autoloader without having to go through an update.

Mercurial stuck "waiting for lock"

I had the same problem on Win 7. The solution was to remove following files:

  1. .hg/store/phaseroots
  2. .hg/wlock

As for .hg/store/lock - there was no such file.

Quantile-Quantile Plot using SciPy

How big is your sample? Here is another option to test your data against any distribution using OpenTURNS library. In the example below, I generate a sample x of 1.000.000 numbers from a Uniform distribution and test it against a Normal distribution. You can replace x by your data if you reshape it as x= [[x1], [x2], .., [xn]]

import openturns as ot

x = ot.Uniform().getSample(1000000)
g = ot.VisualTest.DrawQQplot(x, ot.Normal())
g

In my Jupyter Notebook, I see: enter image description here

If you are writing a script, you can do it more properly

from openturns.viewer import View`
import matplotlib.pyplot as plt
View(g)
plt.show()

how to define variable in jquery

var name = 'john';
document.write(name);

it will write the variable you have declared upper

Argparse optional positional arguments?

parser.add_argument also has a switch required. You can use required=False. Here is a sample snippet with Python 2.7:

parser = argparse.ArgumentParser(description='get dir')
parser.add_argument('--dir', type=str, help='dir', default=os.getcwd(), required=False)
args = parser.parse_args()

How do you debug MySQL stored procedures?

The first and stable debugger for MySQL is in dbForge Studio for MySQL

Why won't eclipse switch the compiler to Java 8?

This is a old topic but I just wanted to point out that I have searched enough to find that Indigo version can't be updated to S.E 1.8 here the link which is given on eclipse website to update the Execution Environment but if you try it will throw error for Indigo.

Image//wiki.eclipse.org/File:ExecutionEnvironmentDescriptionInstallation.png this is the link where the Information about execution environment is given.

https://wiki.eclipse.org/JDT/Eclipse_Java_8_Support_For_Kepler This shows the step by step to update Execution environment.

I have tried to update Execution environment and I got the same error.

Call external javascript functions from java code

try {
        ScriptEngineManager manager = new ScriptEngineManager();
        ScriptEngine engine = manager.getEngineByName("JavaScript");
        System.out.println("okay1");
        FileInputStream fileInputStream = new FileInputStream("C:/Users/Kushan/eclipse-workspace/sureson.lk/src/main/webapp/js/back_end_response.js");
        System.out.println("okay2");
        if (fileInputStream != null){
         BufferedReader reader = new BufferedReader(new InputStreamReader(fileInputStream));
         engine.eval(reader);
         System.out.println("okay3");
        // Invocable javascriptEngine = null;
         System.out.println("okay4");
        Invocable invocableEngine = (Invocable)engine;
         System.out.println("okay5");
         int x=0;
         System.out.println("invocableEngine is : "+invocableEngine);
         Object object = invocableEngine.invokeFunction("backend_message",x);

         System.out.println("okay6");
        }
        }catch(Exception e) {
            System.out.println("erroe when calling js function"+ e);
        }

How can I run a PHP script inside a HTML file?

<?php 
     echo '<p>Hello World</p>' 
?>

As simple as placing something along those lines within your HTML assuming your server is set-up to execute PHP in files with the HTML extension.

How can I style even and odd elements?

Below is the example of even and odd css color apply

<html>
<head>
<style> 
p:nth-child(even) {
    background: red;
}
p:nth-child(odd) {
    background: green;
}
</style>
</head>
<body>

<p>The first Odd.</p>
<p>The second Even.</p>
<p>The third Odd.</p>
<p>The fourth Even.</p>


</body>
</html>

Scraping data from website using vba

you can use winhttprequest object instead of internet explorer as it's good to load data excluding pictures n advertisement instead of downloading full webpage including advertisement n pictures those make internet explorer object heavy compare to winhttpRequest object.

Share data between AngularJS controllers

Just do it simple (tested with v1.3.15):

<article ng-controller="ctrl1 as c1">
    <label>Change name here:</label>
    <input ng-model="c1.sData.name" />
    <h1>Control 1: {{c1.sData.name}}, {{c1.sData.age}}</h1>
</article>
<article ng-controller="ctrl2 as c2">
    <label>Change age here:</label>
    <input ng-model="c2.sData.age" />
    <h1>Control 2: {{c2.sData.name}}, {{c2.sData.age}}</h1>
</article>

<script>
    var app = angular.module("MyApp", []);

    var dummy = {name: "Joe", age: 25};

    app.controller("ctrl1", function () {
        this.sData = dummy;
    });

    app.controller("ctrl2", function () {
        this.sData = dummy;
    });
</script>

Can you pass parameters to an AngularJS controller on creation?

If ng-init is not for passing objects into $scope, you can always write your own directive. So here is what I got:

http://jsfiddle.net/goliney/89bLj/

Javasript:

var app = angular.module('myApp', []);
app.directive('initData', function($parse) {
    return function(scope, element, attrs) {
        //modify scope
        var model = $parse(attrs.initData);
        model(scope);
    };
});

function Ctrl1($scope) {
    //should be defined
    $scope.inputdata = {foo:"east", bar:"west"};
}

Html:

<div ng-controller="Ctrl1">
    <div init-data="inputdata.foo=123; inputdata.bar=321"></div>
</div>

But my approach can only modify objects, which are already defined at controller.

TINYTEXT, TEXT, MEDIUMTEXT, and LONGTEXT maximum storage sizes

From the documentation (MySQL 8) :

      Type | Maximum length
-----------+-------------------------------------
  TINYTEXT |           255 (2 8−1) bytes
      TEXT |        65,535 (216−1) bytes = 64 KiB
MEDIUMTEXT |    16,777,215 (224−1) bytes = 16 MiB
  LONGTEXT | 4,294,967,295 (232−1) bytes =  4 GiB

Note that the number of characters that can be stored in your column will depend on the character encoding.

Declare and Initialize String Array in VBA

Public Function _
CreateTextArrayFromSourceTexts(ParamArray SourceTexts() As Variant) As String()

    ReDim TargetTextArray(0 To UBound(SourceTexts)) As String
    
    For SourceTextsCellNumber = 0 To UBound(SourceTexts)
        TargetTextArray(SourceTextsCellNumber) = SourceTexts(SourceTextsCellNumber)
    Next SourceTextsCellNumber

    CreateTextArrayFromSourceTexts = TargetTextArray
End Function

Example:

Dim TT() As String
TT = CreateTextArrayFromSourceTexts("hi", "bye", "hi", "bcd", "bYe")

Result:

TT(0)="hi"
TT(1)="bye"
TT(2)="hi"
TT(3)="bcd"
TT(4)="bYe"

Enjoy!

Edit: I removed the duplicatedtexts deleting feature and made the code smaller and easier to use.

Saving a Numpy array as an image

matplotlib svn has a new function to save images as just an image -- no axes etc. it's a very simple function to backport too, if you don't want to install svn (copied straight from image.py in matplotlib svn, removed the docstring for brevity):

def imsave(fname, arr, vmin=None, vmax=None, cmap=None, format=None, origin=None):
    from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
    from matplotlib.figure import Figure

    fig = Figure(figsize=arr.shape[::-1], dpi=1, frameon=False)
    canvas = FigureCanvas(fig)
    fig.figimage(arr, cmap=cmap, vmin=vmin, vmax=vmax, origin=origin)
    fig.savefig(fname, dpi=1, format=format)

No tests found for given includes Error, when running Parameterized Unit test in Android Studio

When I use junit5, it's working. But every time I execute gradle --clean, I get Class not found error. Then I add this to build.gradle to resolve my problem and I can still use junit4:

test {
}

Get the second highest value in a MySQL table

FOR SECOND LAST:

SELECT name, salary
    FROM employee 
    ORDER BY salary DESC
    LIMIT 1 , 1

FOR THIRD LAST:

SELECT name, salary
    FROM employee 
    ORDER BY salary DESC
    LIMIT 2 , 1

Typescript es6 import module "File is not a module error"

In addition to Tim's answer, this issue occurred for me when I was splitting up a refactoring a file, splitting it up into their own files.

VSCode, for some reason, indented parts of my [class] code, which caused this issue. This was hard to notice at first, but after I realised the code was indented, I formatted the code and the issue disappeared.

for example, everything after the first line of the Class definition was auto-indented during the paste.

export class MyClass extends Something<string> {
    public blah: string = null;

    constructor() { ... }
  }

Difference between _self, _top, and _parent in the anchor tag target attribute

While these answers are good, IMHO I don't think they fully address the question.

The target attribute in an anchor tag tells the browser the target of the destination of the anchor. They were initially created in order to manipulate and direct anchors to the frame system of document. This was well before CSS came to the aid of HTML developers.

While target="_self" is default by browser and the most common target is target="_blank" which opens the anchor in a new window(which has been redirected to tabs by browser settings usually). The "_parent", "_top" and framename tags are left a mystery to those that aren't familiar with the days of iframe site building as the trend.

target="_self" This opens an anchor in the same frame. What is confusing is that because we generally don't write in frames anymore (and the frame and frameset tags are obsolete in HTML5) people assume this a same window function. Instead if this anchor was nested in frames it would open in a sandbox mode of sorts, meaning only in that frame.

target="_parent" Will open the in the next level up of a frame if they were nested to inside one another

target="_top" This breaks outside of all the frames it is nested in and opens the link as top document in the browser window.

target="framename This was originally deprecated but brought back in HTML5. This will target the exact frame in question. While the name was the proper method that method has been replaced with using the id identifying tag.

<!--Example:-->

<html>
<head>
</head>
<body>
<iframe src="url1" name="A"><p> This my first iframe</p></iframe>
<iframe src="url2" name="B"><p> This my second iframe</p></iframe>
<iframe src="url3" name="C"><p> This my third iframe</p></iframe>

<a href="url4" target="B"></a>
</body>
</html>

Asynchronous Function Call in PHP

This old question has a new answer. There are a few "async" solutions for PHP this days (which are equivalent to Python's multiprocess in the sense that they spawn new independent PHP processes rather than manage it at the framework level)

The two solutions I have seen are

Give them a try!

Convert blob to base64

There is a pure JavaSript way that is not depended on any stacks:

const blobToBase64 = blob => {
  const reader = new FileReader();
  reader.readAsDataURL(blob);
  return new Promise(resolve => {
    reader.onloadend = () => {
      resolve(reader.result);
    };
  });
};

For using this helper function you should set a callback, example:

blobToBase64(blobData).then(res => {
  // do what you wanna do
  console.log(res); // res is base64 now
});

I write this helper function for my problem on React Native project, I wanted to download an image and then store it as a cached image:

fetch(imageAddressAsStringValue)
  .then(res => res.blob())
  .then(blobToBase64)
  .then(finalResult => { 
    storeOnMyLocalDatabase(finalResult);
  });

Getting the folder name from a path

Try this:

string filename = @"C:/folder1/folder2/file.txt";
string FolderName = new DirectoryInfo(System.IO.Path.GetDirectoryName(filename)).Name;

count of entries in data frame in R

I think of this as a two-step process:

  1. subset the original data frame according to the filter supplied (Believe==FALSE); then

  2. get the row count of this subset

For the first step, the subset function is a good way to do this (just an alternative to ordinary index or bracket notation).

For the second step, i would use dim or nrow

One advantage of using subset: you don't have to parse the result it returns to get the result you need--just call nrow on it directly.

so in your case:

v = nrow(subset(Santa, Believe==FALSE))     # 'subset' returns a data.frame

or wrapped in an anonymous function:

>> fnx = function(fac, lev){nrow(subset(Santa, fac==lev))}

>> fnx(Believe, TRUE)
      3

Aside from nrow, dim will also do the job. This function returns the dimensions of a data frame (rows, cols) so you just need to supply the appropriate index to access the number of rows:

v = dim(subset(Santa, Believe==FALSE))[1] 

An answer to the OP posted before this one shows the use of a contingency table. I don't like that approach for the general problem as recited in the OP. Here's the reason. Granted, the general problem of how many rows in this data frame have value x in column C? can be answered using a contingency table as well as using a "filtering" scheme (as in my answer here). If you want row counts for all values for a given factor variable (column) then a contingency table (via calling table and passing in the column(s) of interest) is the most sensible solution; however, the OP asks for the count of a particular value in a factor variable, not counts across all values. Aside from the performance hit (might be big, might be trivial, just depends on the size of the data frame and the processing pipeline context in which this function resides). And of course once the result from the call to table is returned, you still have to parse from that result just the count that you want.

So that's why, to me, this is a filtering rather than a cross-tab problem.

How to do what head, tail, more, less, sed do in Powershell?

"-TotalCount" in this instance responds exactly like "-head". You have to use -TotalCount or -head to run the command like that. But -TotalCount is misleading - it does not work in ACTUALLY giving you ANY counts...

gc -TotalCount 25 C:\scripts\logs\robocopy_report.txt

The above script, tested in PS 5.1 is the SAME response as below...

gc -head 25 C:\scripts\logs\robocopy_report.txt

So then just use '-head 25" already!

Is there a Boolean data type in Microsoft SQL Server like there is in MySQL?

You can use Bit DataType in SQL Server to store boolean data.

Asp.Net MVC with Drop Down List, and SelectListItem Assistance

You have a view model to which your view is strongly typed => use strongly typed helpers:

<%= Html.DropDownListFor(
    x => x.SelectedAccountId, 
    new SelectList(Model.Accounts, "Value", "Text")
) %>

Also notice that I use a SelectList for the second argument.

And in your controller action you were returning the view model passed as argument and not the one you constructed inside the action which had the Accounts property correctly setup so this could be problematic. I've cleaned it a bit:

public ActionResult AccountTransaction()
{
    var accounts = Services.AccountServices.GetAccounts(false);
    var viewModel = new AccountTransactionView
    {
        Accounts = accounts.Select(a => new SelectListItem
        {
            Text = a.Description,
            Value = a.AccountId.ToString()
        })
    };
    return View(viewModel);
}

Conditionally ignoring tests in JUnit 4

In JUnit 4, another option for you may be to create an annotation to denote that the test needs to meet your custom criteria, then extend the default runner with your own and using reflection, base your decision on the custom criteria. It may look something like this:

public class CustomRunner extends BlockJUnit4ClassRunner {
    public CTRunner(Class<?> klass) throws initializationError {
        super(klass);
    }

    @Override
    protected boolean isIgnored(FrameworkMethod child) {
        if(shouldIgnore()) {
            return true;
        }
        return super.isIgnored(child);
    }

    private boolean shouldIgnore(class) {
        /* some custom criteria */
    }
}

Get the cell value of a GridView row

I was looking for an integer value in named column, so I did the below:

int index = dgv_myDataGridView.CurrentCell.RowIndex;

int id = Convert.ToInt32(dgv_myDataGridView["ID", index].Value)

The good thing about this is that the column can be in any position in the grid view and you will still get the value.

Cheers

What are static factory methods?

I thought i will add some light to this post on what i know. We used this technique extensively in our recent android project. Instead of creating objects using new operator you can also use static method to instantiate a class. Code listing:

//instantiating a class using constructor
Vinoth vin = new Vinoth(); 

//instantiating the class using static method
Class Vinoth{
  private Vinoth(){
  }
  // factory method to instantiate the class
  public static Vinoth getInstance(){
    if(someCondition)
        return new Vinoth();
  }
}

Static methods support conditional object creation: Each time you invoke a constructor an object will get created but you might not want that. suppose you want to check some condition only then you want to create a new object.You would not be creating a new instance of Vinoth each time, unless your condition is satisfied.

Another example taken from Effective Java.

public static Boolean valueOf(boolean b) {
        return (b ? TRUE : FALSE);
}

This method translates a boolean primitive value into a Boolean object reference. The Boolean.valueOf(boolean) method illustrates us, it never creates an object. The ability of static factory methods to return the same object from repeated invocations allows classes to maintain strict control over what instances exist at any time.

Static factory methods is that, unlike constructors, they can return an object of any subtype of their return type. One application of this flexibility is that an API can return objects without making their classes public. Hiding implementation classes in this fashion leads to a very compact API.

Calendar.getInstance() is a great example for the above, It creates depending on the locale a BuddhistCalendar, JapaneseImperialCalendar or by default one Georgian.

Another example which i could think is Singleton pattern, where you make your constructors private create an own getInstance method where you make sure, that there is always just one instance available.

public class Singleton{
    //initailzed during class loading
    private static final Singleton INSTANCE = new Singleton();

    //to prevent creating another instance of Singleton
    private Singleton(){}

    public static Singleton getSingleton(){
        return INSTANCE;
    }
}

How do you test running time of VBA code?

Unless your functions are very slow, you're going to need a very high-resolution timer. The most accurate one I know is QueryPerformanceCounter. Google it for more info. Try pushing the following into a class, call it CTimer say, then you can make an instance somewhere global and just call .StartCounter and .TimeElapsed

Option Explicit

Private Type LARGE_INTEGER
    lowpart As Long
    highpart As Long
End Type

Private Declare Function QueryPerformanceCounter Lib "kernel32" (lpPerformanceCount As LARGE_INTEGER) As Long
Private Declare Function QueryPerformanceFrequency Lib "kernel32" (lpFrequency As LARGE_INTEGER) As Long

Private m_CounterStart As LARGE_INTEGER
Private m_CounterEnd As LARGE_INTEGER
Private m_crFrequency As Double

Private Const TWO_32 = 4294967296# ' = 256# * 256# * 256# * 256#

Private Function LI2Double(LI As LARGE_INTEGER) As Double
Dim Low As Double
    Low = LI.lowpart
    If Low < 0 Then
        Low = Low + TWO_32
    End If
    LI2Double = LI.highpart * TWO_32 + Low
End Function

Private Sub Class_Initialize()
Dim PerfFrequency As LARGE_INTEGER
    QueryPerformanceFrequency PerfFrequency
    m_crFrequency = LI2Double(PerfFrequency)
End Sub

Public Sub StartCounter()
    QueryPerformanceCounter m_CounterStart
End Sub

Property Get TimeElapsed() As Double
Dim crStart As Double
Dim crStop As Double
    QueryPerformanceCounter m_CounterEnd
    crStart = LI2Double(m_CounterStart)
    crStop = LI2Double(m_CounterEnd)
    TimeElapsed = 1000# * (crStop - crStart) / m_crFrequency
End Property

How to use performSelector:withObject:afterDelay: with primitive types in Cocoa?

I know this is an old question but if you are building iOS SDK 4+ then you can use blocks to do this with very little effort and make it more readable:

double delayInSeconds = 2.0;
int primitiveValue = 500;
dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC));
dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
    [self doSomethingWithPrimitive:primitiveValue];     
});

The network adapter could not establish the connection - Oracle 11g

I had the similar issue. its resolved for me with a simple command.

lsnrctl start

The Network Adapter exception is caused because:

  1. The database host name or port number is wrong (OR)
  2. The database TNSListener has not been started. The TNSListener may be started with the lsnrctl utility.

Try to start the listener using the command prompt:

  1. Click Start, type cmd in the search field, and when cmd shows up in the list of options, right click it and select ‘Run as Administrator’.
  2. At the Command Prompt window, type lsnrctl start without the quotes and press Enter.
  3. Type Exit and press Enter.

Hope it helps.

What range of values can integer types store in C++

You should look at the specialisations of the numeric_limits<> template for a given type. Its in the header.

Open Jquery modal dialog on click event

Try this

    $(function() {

$('#clickMe').click(function(event) {
    var mytext = $('#myText').val();


    $('<div id="dialog">'+mytext+'</div>').appendTo('body');        
    event.preventDefault();

        $("#dialog").dialog({                   
            width: 600,
            modal: true,
            close: function(event, ui) {
                $("#dialog").remove();
                }
            });
    }); //close click
});

And in HTML

<h3 id="clickMe">Open dialog</h3>
<textarea cols="0" rows="0" id="myText" style="display:none">Some hidden text display none</textarea>

Specifying content of an iframe instead of the src attribute to a page

iframe now supports srcdoc which can be used to specify the HTML content of the page to show in the inline frame.

How to detect the device orientation using CSS media queries?

@media all and (orientation:portrait) {
/* Style adjustments for portrait mode goes here */
}

@media all and (orientation:landscape) {
  /* Style adjustments for landscape mode goes here */
}

but it still looks like you have to experiment

How to get difference between two rows for a column field?

SQL Server 2012 and up support LAG / LEAD functions to access the previous or subsequent row. SQL Server 2005 does not support this (in SQL2005 you need a join or something else).

A SQL 2012 example on this data

/* Prepare */
select * into #tmp
from
(
    select 2  as rowint,      23 as Value
    union select 3,       45
    union select 17,      10
    union select 9,       0
) x


/* The SQL 2012 query */
select rowInt, Value, LEAD(value) over (order by rowInt) - Value  
from #tmp

LEAD(value) will return the value of the next row in respect to the given order in "over" clause.

Letsencrypt add domain to existing certificate

This is how i registered my domain:

sudo letsencrypt --apache -d mydomain.com

Then it was possible to use the same command with additional domains and follow the instructions:

sudo letsencrypt --apache -d mydomain.com,x.mydomain.com,y.mydomain.com

ASP.NET MVC View Engine Comparison

My current choice is Razor. It is very clean and easy to read and keeps the view pages very easy to maintain. There is also intellisense support which is really great. ALos, when used with web helpers it is really powerful too.

To provide a simple sample:

@Model namespace.model
<!Doctype html>
<html>
<head>
<title>Test Razor</title>
</head>
<body>
<ul class="mainList">
@foreach(var x in ViewData.model)
{
<li>@x.PropertyName</li>
}
</ul>
</body>

And there you have it. That is very clean and easy to read. Granted, that's a simple example but even on complex pages and forms it is still very easy to read and understand.

As for the cons? Well so far (I'm new to this) when using some of the helpers for forms there is a lack of support for adding a CSS class reference which is a little annoying.

Thanks Nathj07

Styling a disabled input with css only

Let's just say you have 3 buttons:

<input type="button" disabled="disabled" value="hello world">
<input type="button" disabled value="hello world">
<input type="button" value="hello world">

To style the disabled button you can use the following css:

input[type="button"]:disabled{
    color:#000;
}

This will only affect the button which is disabled.

To stop the color changing when hovering you can use this too:

input[type="button"]:disabled:hover{
    color:#000;
}

You can also avoid this by using a css-reset.

What is JSON and why would I use it?

the common short answer is: if you are using AJAX to make data requests, you can easily send and return objects as JSON strings. Available extensions for Javascript support toJSON() calls on all javascript types for sending data to the server in an AJAX request. AJAX responses can return objects as JSON strings which can be converted into Javascript objects by a simple eval call, e.g. if the AJAX function someAjaxFunctionCallReturningJson returned

"{ \"FirstName\" : \"Fred\", \"LastName\" : \"Flintstone\" }"

you could write in Javascript

var obj = eval("(" + someAjaxFunctionCallReturningJson().value + ")");
alert(obj.FirstName);
alert(obj.LastName);

JSON can also be used for web service payloads et al, but it is really convenient for AJAX results.

  • Update (ten years later): Don't do this, use JSON.parse

How to fix Error: listen EADDRINUSE while using nodejs?

This happened to me because I had my server running in another Terminal window. Closing the connection solved the problem.

JBoss vs Tomcat again

First the facts, neither is better. As you already mentioned, Tomcat provides a servlet container that supports the Servlet specification (Tomcat 7 supports Servlet 3.0). JBoss AS, a 'complete' application server supports Java EE 6 (including Servlet 3.0) in its current version.

Tomcat is fairly lightweight and in case you need certain Java EE features beyond the Servlet API, you can easily enhance Tomcat by providing the required libraries as part of your application. For example, if you need JPA features you can include Hibernate or OpenEJB and JPA works nearly out of the box.

How to decide whether to use Tomcat or a full stack Java EE application server:

When starting your project you should have an idea what it requires. If you're in a large enterprise environment JBoss (or any other Java EE server) might be the right choice as it provides built-in support for e.g:

  1. JMS messaging for asynchronous integration
  2. Web Services engine (JAX-WS and/or JAX-RS)
  3. Management capabilities like JMX and a scripted administration interface
  4. Advanced security, e.g. out-of-the-box integration with 3rd party directories
  5. EAR file instead of "only" WAR file support
  6. all the other "great" Java EE features I can't remember :-)

In my opinion Tomcat is a very good fit if it comes to web centric, user facing applications. If backend integration comes into play, a Java EE application server should be (at least) considered. Last but not least, migrating a WAR developed for Tomcat to JBoss should be a 1 day excercise.

Second, you should also take the usage inside your environment into account. In case your organization already runs say 1,000 JBoss instances, you might always go with that regardless of your concrete requirements (consider aspects like cost for operations or upskilling). Of course, this applies vice versa.

my 2 cent

How to check the value given is a positive or negative integer?

I use in this case and it works :)

var pos = 0; 
var sign = 0;
var zero = 0;
var neg = 0;
for( var i in arr ) {
    sign = arr[i] > 0 ? 1 : arr[i] == 0 ? 0 : -1;
    if (sign === 0) {
        zero++; 
    } else if (sign === 1 ) {
        pos++;
    } else {
        neg++;
    }
}

Convert string with comma to integer

How about this?

 "1,112".delete(',').to_i

Java decimal formatting using String.format?

You want java.text.DecimalFormat

Adding Image to xCode by dragging it from File

You can't add image from desktop to UIimageView, you only can add image (dragging) into project folders and then select the name image into UIimageView properties (inspector).

Tutorial on how to do that: http://conecode.com/news/2011/06/ios-tutorial-creating-an-image-view-uiimageview/

Why is "using namespace std;" considered bad practice?

Experienced programmers use whatever solves their problems and avoid whatever creates new problems, and they avoid header-file-level using-directives for this exact reason.

Experienced programmers also try to avoid full qualification of names inside their source files. A minor reason for this is that it's not elegant to write more code when less code is sufficient unless there are good reasons. A major reason for this is turning off argument-dependent lookup (ADL).

What are these good reasons? Sometimes programmers explicitly want to turn off ADL, other times they want to disambiguate.

So the following are OK:

  1. Function-level using-directives and using-declarations inside functions' implementations
  2. Source-file-level using-declarations inside source files
  3. (Sometimes) source-file-level using-directives

How do I enable index downloads in Eclipse for Maven dependency search?

Tick 'Full Index Enabled' and then 'Rebuild Index' of the central repository in 'Global Repositories' under Window > Show View > Other > Maven > Maven Repositories, and it should work.

The rebuilding may take a long time depending on the speed of your internet connection, but eventually it works.

How to use a global array in C#?

Your class shoud look something like this:

class Something {     int[] array; //global array, replace type of course     void function1() {        array = new int[10]; //let say you declare it here that will be 10 integers in size     }     void function2() {        array[0] = 12; //assing value at index 0 to 12.     } } 

That way you array will be accessible in both functions. However, you must be careful with global stuff, as you can quickly overwrite something.

How to I say Is Not Null in VBA

you can do like follows. Remember, IsNull is a function which returns TRUE if the parameter passed to it is null, and false otherwise.

Not IsNull(Fields!W_O_Count.Value)

Set default value of an integer column SQLite

It happens that I'm just starting to learn coding and I needed something similar as you have just asked in SQLite (I´m using [SQLiteStudio] (3.1.1)).

It happens that you must define the column's 'Constraint' as 'Not Null' then entering your desired definition using 'Default' 'Constraint' or it will not work (I don't know if this is an SQLite or the program requirment).

Here is the code I used:

CREATE TABLE <MY_TABLE> (
<MY_TABLE_KEY>       INTEGER    UNIQUE
                                PRIMARY KEY,
<MY_TABLE_SERIAL>    TEXT       DEFAULT (<MY_VALUE>) 
                                NOT NULL
<THE_REST_COLUMNS>
);

WCF Exception: Could not find a base address that matches scheme http for the endpoint

In my case this fixed the issue

  1. Go to Project Properties by clicking F4 on the project name
  2. Set SSLEnabled = true

Project Properties Image

Get multiple elements by Id

If you can change the markup, you might want to use class instead.

<!-- html -->
<a class="test" name="Name 1"></a>
<a class="test" name="Name 2"></a>
<a class="test" name="Name 3"></a>

// javascript
var elements = document.getElementsByClassName("test");
var names = '';
for(var i=0; i<elements.length; i++) {
    names += elements[i].name;
}
document.write(names);

jsfiddle demo

How to listen to route changes in react router v4?

v5.1 introduces the useful hook useLocation

https://reacttraining.com/blog/react-router-v5-1/#uselocation

import { Switch, useLocation } from 'react-router-dom'

function usePageViews() {
  let location = useLocation()

  useEffect(
    () => {
      ga.send(['pageview', location.pathname])
    },
    [location]
  )
}

function App() {
  usePageViews()
  return <Switch>{/* your routes here */}</Switch>
}

How to read file with space separated values in pandas

If you can't get text parsing to work using the accepted answer (e.g if your text file contains non uniform rows) then it's worth trying with Python's csv library - here's an example using a user defined Dialect:

 import csv

 csv.register_dialect('skip_space', skipinitialspace=True)
 with open(my_file, 'r') as f:
      reader=csv.reader(f , delimiter=' ', dialect='skip_space')
      for item in reader:
          print(item)

Is there a way to make HTML5 video fullscreen?

Safari supports it through webkitEnterFullscreen.

Chrome should support it since it's WebKit also, but errors out.

Chris Blizzard of Firefox said they're coming out with their own version of fullscreen which will allow any element to go to fullscreen. e.g. Canvas

Philip Jagenstedt of Opera says they'll support it in a later release.

Yes, the HTML5 video spec says not to support fullscreen, but since users want it, and every browser is going to support it, the spec will change.

what does the __file__ variable mean/do?

When a module is loaded from a file in Python, __file__ is set to its path. You can then use that with other functions to find the directory that the file is located in.

Taking your examples one at a time:

A = os.path.join(os.path.dirname(__file__), '..')
# A is the parent directory of the directory where program resides.

B = os.path.dirname(os.path.realpath(__file__))
# B is the canonicalised (?) directory where the program resides.

C = os.path.abspath(os.path.dirname(__file__))
# C is the absolute path of the directory where the program resides.

You can see the various values returned from these here:

import os
print(__file__)
print(os.path.join(os.path.dirname(__file__), '..'))
print(os.path.dirname(os.path.realpath(__file__)))
print(os.path.abspath(os.path.dirname(__file__)))

and make sure you run it from different locations (such as ./text.py, ~/python/text.py and so forth) to see what difference that makes.


I just want to address some confusion first. __file__ is not a wildcard it is an attribute. Double underscore attributes and methods are considered to be "special" by convention and serve a special purpose.

http://docs.python.org/reference/datamodel.html shows many of the special methods and attributes, if not all of them.

In this case __file__ is an attribute of a module (a module object). In Python a .py file is a module. So import amodule will have an attribute of __file__ which means different things under difference circumstances.

Taken from the docs:

__file__ is the pathname of the file from which the module was loaded, if it was loaded from a file. The __file__ attribute is not present for C modules that are statically linked into the interpreter; for extension modules loaded dynamically from a shared library, it is the pathname of the shared library file.

In your case the module is accessing it's own __file__ attribute in the global namespace.

To see this in action try:

# file: test.py

print globals()
print __file__

And run:

python test.py

{'__builtins__': <module '__builtin__' (built-in)>, '__name__': '__main__', '__file__':
 'test_print__file__.py', '__doc__': None, '__package__': None}
test_print__file__.py

Detecting iOS orientation change instantly

Add a notifier in the viewWillAppear function

-(void)viewWillAppear:(BOOL)animated{
  [super viewWillAppear:animated];
  [[NSNotificationCenter defaultCenter] addObserver:self  selector:@selector(orientationChanged:)    name:UIDeviceOrientationDidChangeNotification  object:nil];
}

The orientation change notifies this function

- (void)orientationChanged:(NSNotification *)notification{
   [self adjustViewsForOrientation:[[UIApplication sharedApplication] statusBarOrientation]];
}

which in-turn calls this function where the moviePlayerController frame is orientation is handled

- (void) adjustViewsForOrientation:(UIInterfaceOrientation) orientation {

    switch (orientation)
    {
        case UIInterfaceOrientationPortrait:
        case UIInterfaceOrientationPortraitUpsideDown:
        { 
        //load the portrait view    
        }

            break;
        case UIInterfaceOrientationLandscapeLeft:
        case UIInterfaceOrientationLandscapeRight:
        {
        //load the landscape view 
        }
            break;
        case UIInterfaceOrientationUnknown:break;
    }
}

in viewDidDisappear remove the notification

-(void)viewDidDisappear:(BOOL)animated{
   [super viewDidDisappear:animated];
   [[NSNotificationCenter defaultCenter]removeObserver:self name:UIDeviceOrientationDidChangeNotification object:nil];
}

I guess this is the fastest u can have changed the view as per orientation

Best practice multi language website

I am not going to attempt to refine the answers already given. Instead I will tell you about the way my own OOP PHP framework handles translations.

Internally, my framework use codes like en, fr, es, cn and so on. An array holds the languages supported by the website: array('en','fr','es','cn') The language code is passed via $_GET (lang=fr) and if not passed or not valid, it is set to the first language in the array. So at any time during program execution and from the very beginning, the current language is known.

It is useful to understand the kind of content that needs to be translated in a typical application:

1) error messages from classes (or procedural code) 2) non-error messages from classes (or procedural code) 3) page content (usually store in a database) 4) site-wide strings (like website name) 5) script-specific strings

The first type is simple to understand. Basically, we are talking about messages like "could not connect to the database ...". These messages only need to be loaded when an error occurs. My manager class receives a call from the other classes and using the information passed as parameters simply goes to relevant the class folder and retrieves the error file.

The second type of error message is more like the messages you get when the validation of a form went wrong. ("You cannot leave ... blank" or "please choose a password with more than 5 characters"). The strings need to be loaded before the class runs.I know what is

For the actual page content, I use one table per language, each table prefixed by the code for the language. So en_content is the table with English language content, es_content is for spain, cn_content for China and fr_content is the French stuff.

The fourth kind of string is relevant throughout your website. This is loaded via a configuration file named using the code for the language, that is en_lang.php, es_lang.php and so on. In the global language file you will need to load the translated languages such as array('English','Chinese', 'Spanish','French') in the English global file and array('Anglais','Chinois', 'Espagnol', 'Francais') in the French file. So when you populate a dropdown for language selection, it is in the correct language ;)

Finally you have the script-specific strings. So if you write a cooking application, it might be "Your oven was not hot enough".

In my application cycle, the global language file is loaded first. In there you will find not just global strings (like "Jack's Website") but also settings for some of the classes. Basically anything that is language or culture-dependent. Some of the strings in there include masks for dates (MMDDYYYY or DDMMYYYY), or ISO Language Codes. In the main language file, I include strings for individual classes becaue there are so few of them.

The second and last language file that is read from disk is the script language file. lang_en_home_welcome.php is the language file for the home/welcome script. A script is defined by a mode (home) and an action (welcome). Each script has its own folder with config and lang files.

The script pulls the content from the database naming the content table as explained above.

If something goes wrong, the manager knows where to get the language-dependent error file. That file is only loaded in case of an error.

So the conclusion is obvious. Think about the translation issues before you start developing an application or framework. You also need a development workflow that incorporates translations. With my framework, I develop the whole site in English and then translate all the relevant files.

Just a quick final word on the way the translation strings are implemented. My framework has a single global, the $manager, which runs services available to any other service. So for example the form service gets hold of the html service and uses it to write the html. One of the services on my system is the translator service. $translator->set($service,$code,$string) sets a string for the current language. The language file is a list of such statements. $translator->get($service,$code) retrieves a translation string. The $code can be numeric like 1 or a string like 'no_connection'. There can be no clash between services because each has its own namespace in the translator's data area.

I post this here in the hope it will save somebody the task of reinventing the wheel like I had to do a few long years ago.

How to get the Development/Staging/production Hosting Environment in ConfigureServices

This can be accomplished without any extra properties or method parameters, like so:

public void ConfigureServices(IServiceCollection services)
{
    IServiceProvider serviceProvider = services.BuildServiceProvider();
    IHostingEnvironment env = serviceProvider.GetService<IHostingEnvironment>();

    if (env.IsProduction()) DoSomethingDifferentHere();
}

Creating a JSON response using Django and Python

Django code views.py:

def view(request):
    if request.method == 'POST':
        print request.body
        data = request.body
        return HttpResponse(json.dumps(data))

HTML code view.html:

<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $("#mySelect").change(function(){
        selected = $("#mySelect option:selected").text()
        $.ajax({
            type: 'POST',
            dataType: 'json',
            contentType: 'application/json; charset=utf-8',
            url: '/view/',
            data: {
                    'fruit': selected
                  },
            success: function(result) {
                        document.write(result)
                    }
    });
  });
});
</script>
</head>
<body>

<form>
    {{data}}
    <br>
Select your favorite fruit:
<select id="mySelect">
  <option value="apple" selected >Select fruit</option>
  <option value="apple">Apple</option>
  <option value="orange">Orange</option>
  <option value="pineapple">Pineapple</option>
  <option value="banana">Banana</option>
</select>
</form>
</body>
</html>

how to declare global variable in SQL Server..?

It is not possible to declare global variables in SQL Server. Sql server has a concept of global variables, but they are system defined and can not be extended.

obviously you can do all kinds of tricks with the SQL you are sending - SqlCOmmand has such a variable replacement mechanism for example - BEFORE you send it to SqlServer, but that is about it.

Set field value with reflection

The method below sets a field on your object even if the field is in a superclass

/**
 * Sets a field value on a given object
 *
 * @param targetObject the object to set the field value on
 * @param fieldName    exact name of the field
 * @param fieldValue   value to set on the field
 * @return true if the value was successfully set, false otherwise
 */
public static boolean setField(Object targetObject, String fieldName, Object fieldValue) {
    Field field;
    try {
        field = targetObject.getClass().getDeclaredField(fieldName);
    } catch (NoSuchFieldException e) {
        field = null;
    }
    Class superClass = targetObject.getClass().getSuperclass();
    while (field == null && superClass != null) {
        try {
            field = superClass.getDeclaredField(fieldName);
        } catch (NoSuchFieldException e) {
            superClass = superClass.getSuperclass();
        }
    }
    if (field == null) {
        return false;
    }
    field.setAccessible(true);
    try {
        field.set(targetObject, fieldValue);
        return true;
    } catch (IllegalAccessException e) {
        return false;
    }
}

How to get all elements which name starts with some string?

You can use getElementsByName("input") to get a collection of all the inputs on the page. Then loop through the collection, checking the name on the way. Something like this:

<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>JS Bin</title>

</head>
<body>

  <input name="q1_a" type="text" value="1A"/>
  <input name="q1_b" type="text" value="1B"/>
  <input name="q1_c" type="text" value="1C"/>
  <input name="q2_d" type="text" value="2D"/>

  <script type="text/javascript">
  var inputs = document.getElementsByTagName("input");
  for (x = 0 ; x < inputs.length ; x++){
    myname = inputs[x].getAttribute("name");
    if(myname.indexOf("q1_")==0){
      alert(myname);
      // do more stuff here
       }
    }
    </script>
</body>
</html>

Demo

What is the difference between WCF and WPF?

  • WPF is your FrontEnd (presentation: .htm, .xaml & .css, ..)
  • WCF is your BackEnd app (services that involve server connections to acquire data for you to deliver to the FrontEnd to present). You can write WCF for RESTful model.
  • WebAPI is for building services of RESTful model for 4.+ frameworks.

Angular4 - No value accessor for form control

You should use formControlName="surveyType" on an input and not on a div

What is a vertical tab?

It was used during the typewriter era to move down a page to the next vertical stop, typically spaced 6 lines apart (much the same way horizontal tabs move along a line by 8 characters).

In modern day settings, the vt is of very little, if any, significance.

Converting java date to Sql timestamp

You can cut off the milliseconds using a Calendar:

java.util.Date utilDate = new java.util.Date();
Calendar cal = Calendar.getInstance();
cal.setTime(utilDate);
cal.set(Calendar.MILLISECOND, 0);
System.out.println(new java.sql.Timestamp(utilDate.getTime()));
System.out.println(new java.sql.Timestamp(cal.getTimeInMillis()));

Output:

2014-04-04 10:10:17.78
2014-04-04 10:10:17.0

How to convert list data into json in java

Try like below with Gson Library.

Earlier Conversion List format were:

[Product [Id=1, City=Bengalore, Category=TV, Brand=Samsung, Name=Samsung LED, Type=LED, Size=32 inches, Price=33500.5, Stock=17.0], Product [Id=2, City=Bengalore, Category=TV, Brand=Samsung, Name=Samsung LED, Type=LED, Size=42 inches, Price=41850.0, Stock=9.0]]

and here the conversion source begins.

//** Note I have created the method toString() in Product class.

//Creating and initializing a java.util.List of Product objects
List<Product> productList = (List<Product>)productRepository.findAll();

//Creating a blank List of Gson library JsonObject
List<JsonObject> entities = new ArrayList<JsonObject>();

//Simply printing productList size
System.out.println("Size of productList is : " + productList.size());

//Creating a Iterator for productList
Iterator<Product> iterator = productList.iterator();

//Run while loop till Product Object exists.
while(iterator.hasNext()){

    //Creating a fresh Gson Object
    Gson gs = new Gson();

    //Converting our Product Object to JsonElement 
    //Object by passing the Product Object String value (iterator.next())
    JsonElement element = gs.fromJson (gs.toJson(iterator.next()), JsonElement.class);

    //Creating JsonObject from JsonElement
    JsonObject jsonObject = element.getAsJsonObject();

    //Collecting the JsonObject to List
    entities.add(jsonObject);

}

//Do what you want to do with Array of JsonObject
System.out.println(entities);

Converted Json Result is :

[{"Id":1,"City":"Bengalore","Category":"TV","Brand":"Samsung","Name":"Samsung LED","Type":"LED","Size":"32 inches","Price":33500.5,"Stock":17.0}, {"Id":2,"City":"Bengalore","Category":"TV","Brand":"Samsung","Name":"Samsung LED","Type":"LED","Size":"42 inches","Price":41850.0,"Stock":9.0}]

Hope this would help many guys!

Cannot change version of project facet Dynamic Web Module to 3.0?

I had the same issue, editing web.xml as well as changing file in .settings folder alone didn't help. My solution was to directly point maven compiler plugin to use the desired java version by editing pom.xml:

  <build>
    ...
    <plugins>
      <plugin>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.1</version>
        <configuration>
          <source>1.7</source>
          <target>1.7</target>
        </configuration>
      </plugin>
    </plugins>    
  </build> 

Now run Maven->Update project and after that you can change servlets version in properties->project facets->Dynamic Web module version or, as written earlier, by manually editing org.eclipse.wst.common.project.facet.core.xml in .settings folder of your project.

#include errors detected in vscode

1.Install Mingw-w64

2.Then Edit environment variables for your account "C:\mingw-w64\x86_64-8.1.0-win32-seh-rt_v6-rev0\mingw64\bin"

3.Reload

  • For MAC

    1.Open search ,command + shift +P, and run this code “c/c++ edit configurations (ui)”

    2.open file c_cpp_properties.json and update the includePath from "${workspaceFolder}/**" to "${workspaceFolder}/inc"