Programs & Examples On #Dsdt

Setting graph figure size

Write it as a one-liner:

figure('position', [0, 0, 200, 500])  % create new figure with specified size  

enter image description here

Batch file. Delete all files and folders in a directory

I just put this together from what morty346 posted:

set folder="C:\test"
IF EXIST "%folder%" (
    cd /d %folder%
    for /F "delims=" %%i in ('dir /b') do (rmdir "%%i" /s/q || del "%%i" /s/q)
)

It adds a quick check that the folder defined in the variable exists first, changes directory to the folder, and deletes the contents.

Error in finding last used cell in Excel with VBA

Sub lastRow()

    Dim i As Long
        i = Cells(Rows.Count, 1).End(xlUp).Row
            MsgBox i

End Sub

sub LastRow()

'Paste & for better understanding of the working use F8 Key to run the code .

dim WS as worksheet
dim i as long

set ws = thisworkbook("SheetName")

ws.activate

ws.range("a1").select

ws.range("a1048576").select

activecell.end(xlup).select

i= activecell.row

msgbox "My Last Row Is " & i

End sub

How do I test for an empty JavaScript object?

Pure Vanilla Javascript, and full backward compatibility

_x000D_
_x000D_
function isObjectDefined (Obj) {_x000D_
  if (Obj === null || typeof Obj !== 'object' ||_x000D_
    Object.prototype.toString.call(Obj) === '[object Array]') {_x000D_
    return false_x000D_
  } else {_x000D_
    for (var prop in Obj) {_x000D_
      if (Obj.hasOwnProperty(prop)) {_x000D_
        return true_x000D_
      }_x000D_
    }_x000D_
    return JSON.stringify(Obj) !== JSON.stringify({})_x000D_
  }_x000D_
}_x000D_
_x000D_
console.log(isObjectDefined()) // false_x000D_
console.log(isObjectDefined('')) // false_x000D_
console.log(isObjectDefined(1)) // false_x000D_
console.log(isObjectDefined('string')) // false_x000D_
console.log(isObjectDefined(NaN)) // false_x000D_
console.log(isObjectDefined(null)) // false_x000D_
console.log(isObjectDefined({})) // false_x000D_
console.log(isObjectDefined([])) // false_x000D_
console.log(isObjectDefined({a: ''})) // true
_x000D_
_x000D_
_x000D_

How do I calculate tables size in Oracle

select segment_name as tablename, sum(bytes/ (1024 * 1024 * 1024)) as tablesize_in_GB
From dba_segments /* if looking at tables not owned by you else use user_segments */
where segment_name = 'TABLE_WHOSE_SIZE_I_WANT_TO_KNOW'
and   OWNER = 'WHO OWNS THAT TABLE' /* if user_segments is used delete this line */ 
group by segment_name ;

Force DOM redraw/refresh on Chrome/Mac

This is my solution that worked for disappearing content...

<script type = 'text/javascript'>
    var trash_div;

    setInterval(function()
    {
        if (document.body)
        {
            if (!trash_div)
                trash_div = document.createElement('div');

            document.body.appendChild(trash_div);
            document.body.removeChild(trash_div);
        }
    }, 1000 / 25); //25 fps...
</script>

Method to find string inside of the text file. Then getting the following lines up to a certain limit

Here is a java 8 method to find a string in a text file:

for (String toFindUrl : urlsToTest) {
        streamService(toFindUrl);
    }

private void streamService(String item) {
        try (Stream<String> stream = Files.lines(Paths.get(fileName))) {
           stream.filter(lines -> lines.contains(item))
                       .forEach(System.out::println);

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

How to use jQuery with TypeScript

Here is my TypeScript & jQuery config steps.

It makes jQuery's types support to work better than the most articles in the internet . ( I believe. )

first:

npm install jquery --save
npm install @types/jquery --save-dev




second( very very very important ! ! ! ):

import jquery = require("jquery");



// this helps TypeScript to understand jQuery best !!!  otherwise It will confused .
const $: JQueryStatic = jquery;




then , You Can Enjoy It :

$(document).ready(function () {
    $('btn').click(function () {
       alert('I am clicked !')
    }
}




It's silky smooth !!!

mkdir -p functionality in Python

I've had success with the following personally, but my function should probably be called something like 'ensure this directory exists':

def mkdirRecursive(dirpath):
    import os
    if os.path.isdir(dirpath): return

    h,t = os.path.split(dirpath) # head/tail
    if not os.path.isdir(h):
        mkdirRecursive(h)

    os.mkdir(join(h,t))
# end mkdirRecursive

Java Desktop application: SWT vs. Swing

Interesting question. I don't know SWT too well to brag about it (unlike Swing and AWT) but here's the comparison done on SWT/Swing/AWT.

http://www.developer.com/java/other/article.php/10936_2179061_2/Swing-and-SWT-A-Tale-of-Two-Java-GUI-Libraries.htm

And here's the site where you can get tutorial on basically anything on SWT (http://www.java2s.com/Tutorial/Java/0280__SWT/Catalog0280__SWT.htm)

Hope you make a right decision (if there are right decisions in coding)... :-)

How do I debug a stand-alone VBScript script?

For posterity, here's Microsoft's article KB308364 on the subject. This no longer exists on their website, it is from an archive.

How to debug Windows Script Host, VBScript, and JScript files

SUMMARY

The purpose of this article is to explain how to debug Windows Script Host (WSH) scripts, which can be written in any ActiveX script language (as long as the proper language engine is installed), but which, by default, are written in VBScript and JScript. There are certain flags in the registry and, depending on the debugger used, certain required procedures to enable debugging.

MORE INFORMATION

To debug WSH scripts in Microsoft Visual InterDev, the Microsoft Script Debugger, or any other debugger, use the following command-line syntax to start the script:

wscript.exe //d <path to WSH file>
           This code informs the user when a runtime error has occurred and gives the user a choice to debug the application. Also, the //x flag

can be used, as follows, to throw an immediate exception, which starts the debugger immediately after the script starts running:

wscript.exe //d //x <path to WSH file>
           After a debug condition exists, the following registry key determines which debugger will be used:

HKEY_CLASSES_ROOT\CLSID\{834128A2-51F4-11D0-8F20-00805F2CD064}\LocalServer32

The script debugger should be Msscrdbg.exe, and the Visual InterDev debugger should be Mdm.exe.

If Visual InterDev is the default debugger, make sure that just-in-time (JIT) functionality is enabled. To do this, follow these steps:

  1. Start Visual InterDev.

  2. On the Tools menu, click Options.

  3. Click Debugger, and then ensure that the Just-In-Time options are selected for both the General and Script categories.

Additionally, if you are trying to debug a .wsf file, make sure that the following registry key is set to 1:

HKEY_CURRENT_USER\Software\Microsoft\Windows Script\Settings\JITDebug

PROPERTIES

Article ID: 308364 - Last Review: June 19, 2014 - Revision: 3.0

Keywords: kbdswmanage2003swept kbinfo KB308364

Go test string contains substring

To compare, there are more options:

import (
    "fmt"
    "regexp"
    "strings"
)

const (
    str    = "something"
    substr = "some"
)

// 1. Contains
res := strings.Contains(str, substr)
fmt.Println(res) // true

// 2. Index: check the index of the first instance of substr in str, or -1 if substr is not present
i := strings.Index(str, substr)
fmt.Println(i) // 0

// 3. Split by substr and check len of the slice, or length is 1 if substr is not present
ss := strings.Split(str, substr)
fmt.Println(len(ss)) // 2

// 4. Check number of non-overlapping instances of substr in str
c := strings.Count(str, substr)
fmt.Println(c) // 1

// 5. RegExp
matched, _ := regexp.MatchString(substr, str)
fmt.Println(matched) // true

// 6. Compiled RegExp
re = regexp.MustCompile(substr)
res = re.MatchString(str)
fmt.Println(res) // true

Benchmarks: Contains internally calls Index, so the speed is almost the same (btw Go 1.11.5 showed a bit bigger difference than on Go 1.14.3).

BenchmarkStringsContains-4              100000000               10.5 ns/op             0 B/op          0 allocs/op
BenchmarkStringsIndex-4                 117090943               10.1 ns/op             0 B/op          0 allocs/op
BenchmarkStringsSplit-4                  6958126               152 ns/op              32 B/op          1 allocs/op
BenchmarkStringsCount-4                 42397729                29.1 ns/op             0 B/op          0 allocs/op
BenchmarkStringsRegExp-4                  461696              2467 ns/op            1326 B/op         16 allocs/op
BenchmarkStringsRegExpCompiled-4         7109509               168 ns/op               0 B/op          0 allocs/op

How can I force users to access my page over HTTPS instead of HTTP?

You shouldn't for security reasons. Especially if cookies are in play here. It leaves you wide open to cookie-based replay attacks.

Either way, you should use Apache control rules to tune it.

Then you can test for HTTPS being enabled and redirect as-needed where needed.

You should redirect to the pay page only using a FORM POST (no get), and accesses to the page without a POST should be directed back to the other pages. (This will catch the people just hot-jumping.)

http://joseph.randomnetworks.com/archives/2004/07/22/redirect-to-ssl-using-apaches-htaccess/

Is a good place to start, apologies for not providing more. But you really should shove everything through SSL.

It's over-protective, but at least you have less worries.

MS-DOS Batch file pause with enter key

Depending on which OS you're using, if you are flexible, then CHOICE can be used to wait on almost any key EXCEPT enter

If you are really referring to what Microsoft insists on calling "Command Prompt" which is simply an MS-DOS emulator, then perhaps TIMEOUT may suit your purpose (timeout /t -1 waits on any key, not just ENTER) and of course CHOICE is available again in recent WIN editions.

And a warning on SET /P - whereas set /p DUMMY=Hit ENTER to continue... will work,

set "dummy="
set /p DUMMY=Hit ENTER to continue...
if defined dummy (echo not just ENTER was pressed) else (echo just ENTER was pressed)

will detect whether just ENTER or something else, ending in ENTER was keyed in.

Oracle 11g SQL to get unique values in one column of a multi-column query

This will be more efficient, plus you have control over the ordering it uses to pick a value:

SELECT DISTINCT
       FIRST_VALUE(person)
          OVER(PARTITION BY language
               ORDER BY person)
      ,language
FROM   tableA;

If you really don't care which person is picked for each language, you can omit the ORDER BY clause:

SELECT DISTINCT
       FIRST_VALUE(person)
          OVER(PARTITION BY language)
      ,language
FROM   tableA;

jQuery $.cookie is not a function

add this cookie plugin for jquery.

<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery-cookie/1.4.1/jquery.cookie.min.js"></script>

High Quality Image Scaling Library

Tested libraries like Imagemagick and GD are available for .NET

You could also read up on things like bicubic interpolation and write your own.

Python: Finding differences between elements of a list

I suspect this is what the numpy diff command does anyway, but just for completeness you can simply difference the sub-vectors:

from numpy import array as a
a(x[1:])-a(x[:-1])

In addition, I wanted to add these solutions to generalizations of the question:

Solution with periodic boundaries

Sometimes with numerical integration you will want to difference a list with periodic boundary conditions (so the first element calculates the difference to the last. In this case the numpy.roll function is helpful:

v-np.roll(v,1)

Solutions with zero prepended

Another numpy solution (just for completeness) is to use

numpy.ediff1d(v)

This works as numpy.diff, but only on a vector (it flattens the input array). It offers the ability to prepend or append numbers to the resulting vector. This is useful when handling accumulated fields that is often the case fluxes in meteorological variables (e.g. rain, latent heat etc), as you want a resulting list of the same length as the input variable, with the first entry untouched.

Then you would write

np.ediff1d(v,to_begin=v[0])

Of course, you can also do this with the np.diff command, in this case though you need to prepend zero to the series with the prepend keyword:

np.diff(v,prepend=0.0) 

All the above solutions return a vector that is the same length as the input.

Convert double to float in Java

Just cast your double to a float.

double d = getInfoValueNumeric();
float f = (float)d;

Also notice that the primitive types can NOT store an infinite set of numbers:

float range: from 1.40129846432481707e-45 to 3.40282346638528860e+38
double range: from 1.7e–308 to 1.7e+308

Close a MessageBox after several seconds

The System.Windows.MessageBox.Show() method has an overload which takes an owner Window as the first parameter. If we create an invisible owner Window which we then close after a specified time, it's child message box would close as well.

Window owner = CreateAutoCloseWindow(dialogTimeout);
MessageBoxResult result = MessageBox.Show(owner, ...

So far so good. But how do we close a window if the UI thread is blocked by the message box and UI controls can't be accessed from a worker thread? The answer is - by sending a WM_CLOSE windows message to the owner window handle:

Window CreateAutoCloseWindow(TimeSpan timeout)
{
    Window window = new Window()
    {
        WindowStyle = WindowStyle.None,
        WindowState = System.Windows.WindowState.Maximized,
        Background =  System.Windows.Media.Brushes.Transparent, 
        AllowsTransparency = true,
        ShowInTaskbar = false,
        ShowActivated = true,
        Topmost = true
    };

    window.Show();

    IntPtr handle = new WindowInteropHelper(window).Handle;

    Task.Delay((int)timeout.TotalMilliseconds).ContinueWith(
        t => NativeMethods.SendMessage(handle, 0x10 /*WM_CLOSE*/, IntPtr.Zero, IntPtr.Zero));

    return window;
}

And here is the import for the SendMessage Windows API method:

static class NativeMethods
{
    [DllImport("user32.dll", CharSet = CharSet.Auto)]
    public static extern IntPtr SendMessage(IntPtr hWnd, UInt32 Msg, IntPtr wParam, IntPtr lParam);
}

What are the nuances of scope prototypal / prototypical inheritance in AngularJS?

Quick answer:
A child scope normally prototypically inherits from its parent scope, but not always. One exception to this rule is a directive with scope: { ... } -- this creates an "isolate" scope that does not prototypically inherit. This construct is often used when creating a "reusable component" directive.

As for the nuances, scope inheritance is normally straightfoward... until you need 2-way data binding (i.e., form elements, ng-model) in the child scope. Ng-repeat, ng-switch, and ng-include can trip you up if you try to bind to a primitive (e.g., number, string, boolean) in the parent scope from inside the child scope. It doesn't work the way most people expect it should work. The child scope gets its own property that hides/shadows the parent property of the same name. Your workarounds are

  1. define objects in the parent for your model, then reference a property of that object in the child: parentObj.someProp
  2. use $parent.parentScopeProperty (not always possible, but easier than 1. where possible)
  3. define a function on the parent scope, and call it from the child (not always possible)

New AngularJS developers often do not realize that ng-repeat, ng-switch, ng-view, ng-include and ng-if all create new child scopes, so the problem often shows up when these directives are involved. (See this example for a quick illustration of the problem.)

This issue with primitives can be easily avoided by following the "best practice" of always have a '.' in your ng-models – watch 3 minutes worth. Misko demonstrates the primitive binding issue with ng-switch.

Having a '.' in your models will ensure that prototypal inheritance is in play. So, use

<input type="text" ng-model="someObj.prop1">

<!--rather than
<input type="text" ng-model="prop1">`
-->


L-o-n-g answer:

JavaScript Prototypal Inheritance

Also placed on the AngularJS wiki: https://github.com/angular/angular.js/wiki/Understanding-Scopes

It is important to first have a solid understanding of prototypal inheritance, especially if you are coming from a server-side background and you are more familiar with class-ical inheritance. So let's review that first.

Suppose parentScope has properties aString, aNumber, anArray, anObject, and aFunction. If childScope prototypically inherits from parentScope, we have:

prototypal inheritance

(Note that to save space, I show the anArray object as a single blue object with its three values, rather than an single blue object with three separate gray literals.)

If we try to access a property defined on the parentScope from the child scope, JavaScript will first look in the child scope, not find the property, then look in the inherited scope, and find the property. (If it didn't find the property in the parentScope, it would continue up the prototype chain... all the way up to the root scope). So, these are all true:

childScope.aString === 'parent string'
childScope.anArray[1] === 20
childScope.anObject.property1 === 'parent prop1'
childScope.aFunction() === 'parent output'

Suppose we then do this:

childScope.aString = 'child string'

The prototype chain is not consulted, and a new aString property is added to the childScope. This new property hides/shadows the parentScope property with the same name. This will become very important when we discuss ng-repeat and ng-include below.

property hiding

Suppose we then do this:

childScope.anArray[1] = '22'
childScope.anObject.property1 = 'child prop1'

The prototype chain is consulted because the objects (anArray and anObject) are not found in the childScope. The objects are found in the parentScope, and the property values are updated on the original objects. No new properties are added to the childScope; no new objects are created. (Note that in JavaScript arrays and functions are also objects.)

follow the prototype chain

Suppose we then do this:

childScope.anArray = [100, 555]
childScope.anObject = { name: 'Mark', country: 'USA' }

The prototype chain is not consulted, and child scope gets two new object properties that hide/shadow the parentScope object properties with the same names.

more property hiding

Takeaways:

  • If we read childScope.propertyX, and childScope has propertyX, then the prototype chain is not consulted.
  • If we set childScope.propertyX, the prototype chain is not consulted.

One last scenario:

delete childScope.anArray
childScope.anArray[1] === 22  // true

We deleted the childScope property first, then when we try to access the property again, the prototype chain is consulted.

after removing a child property


Angular Scope Inheritance

The contenders:

  • The following create new scopes, and inherit prototypically: ng-repeat, ng-include, ng-switch, ng-controller, directive with scope: true, directive with transclude: true.
  • The following creates a new scope which does not inherit prototypically: directive with scope: { ... }. This creates an "isolate" scope instead.

Note, by default, directives do not create new scope -- i.e., the default is scope: false.

ng-include

Suppose we have in our controller:

$scope.myPrimitive = 50;
$scope.myObject    = {aNumber: 11};

And in our HTML:

<script type="text/ng-template" id="/tpl1.html">
<input ng-model="myPrimitive">
</script>
<div ng-include src="'/tpl1.html'"></div>

<script type="text/ng-template" id="/tpl2.html">
<input ng-model="myObject.aNumber">
</script>
<div ng-include src="'/tpl2.html'"></div>

Each ng-include generates a new child scope, which prototypically inherits from the parent scope.

ng-include child scopes

Typing (say, "77") into the first input textbox causes the child scope to get a new myPrimitive scope property that hides/shadows the parent scope property of the same name. This is probably not what you want/expect.

ng-include with a primitive

Typing (say, "99") into the second input textbox does not result in a new child property. Because tpl2.html binds the model to an object property, prototypal inheritance kicks in when the ngModel looks for object myObject -- it finds it in the parent scope.

ng-include with an object

We can rewrite the first template to use $parent, if we don't want to change our model from a primitive to an object:

<input ng-model="$parent.myPrimitive">

Typing (say, "22") into this input textbox does not result in a new child property. The model is now bound to a property of the parent scope (because $parent is a child scope property that references the parent scope).

ng-include with $parent

For all scopes (prototypal or not), Angular always tracks a parent-child relationship (i.e., a hierarchy), via scope properties $parent, $$childHead and $$childTail. I normally don't show these scope properties in the diagrams.

For scenarios where form elements are not involved, another solution is to define a function on the parent scope to modify the primitive. Then ensure the child always calls this function, which will be available to the child scope due to prototypal inheritance. E.g.,

// in the parent scope
$scope.setMyPrimitive = function(value) {
     $scope.myPrimitive = value;
}

Here is a sample fiddle that uses this "parent function" approach. (The fiddle was written as part of this answer: https://stackoverflow.com/a/14104318/215945.)

See also https://stackoverflow.com/a/13782671/215945 and https://github.com/angular/angular.js/issues/1267.

ng-switch

ng-switch scope inheritance works just like ng-include. So if you need 2-way data binding to a primitive in the parent scope, use $parent, or change the model to be an object and then bind to a property of that object. This will avoid child scope hiding/shadowing of parent scope properties.

See also AngularJS, bind scope of a switch-case?

ng-repeat

Ng-repeat works a little differently. Suppose we have in our controller:

$scope.myArrayOfPrimitives = [ 11, 22 ];
$scope.myArrayOfObjects    = [{num: 101}, {num: 202}]

And in our HTML:

<ul><li ng-repeat="num in myArrayOfPrimitives">
       <input ng-model="num">
    </li>
<ul>
<ul><li ng-repeat="obj in myArrayOfObjects">
       <input ng-model="obj.num">
    </li>
<ul>

For each item/iteration, ng-repeat creates a new scope, which prototypically inherits from the parent scope, but it also assigns the item's value to a new property on the new child scope. (The name of the new property is the loop variable's name.) Here's what the Angular source code for ng-repeat actually is:

childScope = scope.$new();  // child scope prototypically inherits from parent scope
...
childScope[valueIdent] = value;  // creates a new childScope property

If item is a primitive (as in myArrayOfPrimitives), essentially a copy of the value is assigned to the new child scope property. Changing the child scope property's value (i.e., using ng-model, hence child scope num) does not change the array the parent scope references. So in the first ng-repeat above, each child scope gets a num property that is independent of the myArrayOfPrimitives array:

ng-repeat with primitives

This ng-repeat will not work (like you want/expect it to). Typing into the textboxes changes the values in the gray boxes, which are only visible in the child scopes. What we want is for the inputs to affect the myArrayOfPrimitives array, not a child scope primitive property. To accomplish this, we need to change the model to be an array of objects.

So, if item is an object, a reference to the original object (not a copy) is assigned to the new child scope property. Changing the child scope property's value (i.e., using ng-model, hence obj.num) does change the object the parent scope references. So in the second ng-repeat above, we have:

ng-repeat with objects

(I colored one line gray just so that it is clear where it is going.)

This works as expected. Typing into the textboxes changes the values in the gray boxes, which are visible to both the child and parent scopes.

See also Difficulty with ng-model, ng-repeat, and inputs and https://stackoverflow.com/a/13782671/215945

ng-controller

Nesting controllers using ng-controller results in normal prototypal inheritance, just like ng-include and ng-switch, so the same techniques apply. However, "it is considered bad form for two controllers to share information via $scope inheritance" -- http://onehungrymind.com/angularjs-sticky-notes-pt-1-architecture/ A service should be used to share data between controllers instead.

(If you really want to share data via controllers scope inheritance, there is nothing you need to do. The child scope will have access to all of the parent scope properties. See also Controller load order differs when loading or navigating)

directives

  1. default (scope: false) - the directive does not create a new scope, so there is no inheritance here. This is easy, but also dangerous because, e.g., a directive might think it is creating a new property on the scope, when in fact it is clobbering an existing property. This is not a good choice for writing directives that are intended as reusable components.
  2. scope: true - the directive creates a new child scope that prototypically inherits from the parent scope. If more than one directive (on the same DOM element) requests a new scope, only one new child scope is created. Since we have "normal" prototypal inheritance, this is like ng-include and ng-switch, so be wary of 2-way data binding to parent scope primitives, and child scope hiding/shadowing of parent scope properties.
  3. scope: { ... } - the directive creates a new isolate/isolated scope. It does not prototypically inherit. This is usually your best choice when creating reusable components, since the directive cannot accidentally read or modify the parent scope. However, such directives often need access to a few parent scope properties. The object hash is used to set up two-way binding (using '=') or one-way binding (using '@') between the parent scope and the isolate scope. There is also '&' to bind to parent scope expressions. So, these all create local scope properties that are derived from the parent scope. Note that attributes are used to help set up the binding -- you can't just reference parent scope property names in the object hash, you have to use an attribute. E.g., this won't work if you want to bind to parent property parentProp in the isolated scope: <div my-directive> and scope: { localProp: '@parentProp' }. An attribute must be used to specify each parent property that the directive wants to bind to: <div my-directive the-Parent-Prop=parentProp> and scope: { localProp: '@theParentProp' }.
    Isolate scope's __proto__ references Object. Isolate scope's $parent references the parent scope, so although it is isolated and doesn't inherit prototypically from the parent scope, it is still a child scope.
    For the picture below we have
    <my-directive interpolated="{{parentProp1}}" twowayBinding="parentProp2"> and
    scope: { interpolatedProp: '@interpolated', twowayBindingProp: '=twowayBinding' }
    Also, assume the directive does this in its linking function: scope.someIsolateProp = "I'm isolated"
    isolated scope
    For more information on isolate scopes see http://onehungrymind.com/angularjs-sticky-notes-pt-2-isolated-scope/
  4. transclude: true - the directive creates a new "transcluded" child scope, which prototypically inherits from the parent scope. The transcluded and the isolated scope (if any) are siblings -- the $parent property of each scope references the same parent scope. When a transcluded and an isolate scope both exist, isolate scope property $$nextSibling will reference the transcluded scope. I'm not aware of any nuances with the transcluded scope.
    For the picture below, assume the same directive as above with this addition: transclude: true
    transcluded scope

This fiddle has a showScope() function that can be used to examine an isolate and transcluded scope. See the instructions in the comments in the fiddle.


Summary

There are four types of scopes:

  1. normal prototypal scope inheritance -- ng-include, ng-switch, ng-controller, directive with scope: true
  2. normal prototypal scope inheritance with a copy/assignment -- ng-repeat. Each iteration of ng-repeat creates a new child scope, and that new child scope always gets a new property.
  3. isolate scope -- directive with scope: {...}. This one is not prototypal, but '=', '@', and '&' provide a mechanism to access parent scope properties, via attributes.
  4. transcluded scope -- directive with transclude: true. This one is also normal prototypal scope inheritance, but it is also a sibling of any isolate scope.

For all scopes (prototypal or not), Angular always tracks a parent-child relationship (i.e., a hierarchy), via properties $parent and $$childHead and $$childTail.

Diagrams were generated with "*.dot" files, which are on github. Tim Caswell's "Learning JavaScript with Object Graphs" was the inspiration for using GraphViz for the diagrams.

Find the item with maximum occurrences in a list

My (simply) code (three months studying Python):

def more_frequent_item(lst):
    new_lst = []
    times = 0
    for item in lst:
        count_num = lst.count(item)
        new_lst.append(count_num)
        times = max(new_lst)
    key = max(lst, key=lst.count)
    print("In the list: ")
    print(lst)
    print("The most frequent item is " + str(key) + ". Appears " + str(times) + " times in this list.")


more_frequent_item([1, 2, 45, 55, 5, 4, 4, 4, 4, 4, 4, 5456, 56, 6, 7, 67])

The output will be:

In the list: 
[1, 2, 45, 55, 5, 4, 4, 4, 4, 4, 4, 5456, 56, 6, 7, 67]
The most frequent item is 4. Appears 6 times in this list.

How to convert an NSString into an NSNumber

Here's a working sample of NSNumberFormatter reading localized number NSString (xCode 3.2.4, osX 10.6), to save others the hours I've just spent messing around. Beware: while it can handle trailing blanks ("8,765.4 " works), this cannot handle leading white space and this cannot handle stray text characters. (Bad input strings: " 8" and "8q" and "8 q".)

NSString *tempStr = @"8,765.4";  
     // localization allows other thousands separators, also.
NSNumberFormatter * myNumFormatter = [[NSNumberFormatter alloc] init];
[myNumFormatter setLocale:[NSLocale currentLocale]]; // happen by default?
[myNumFormatter setFormatterBehavior:NSNumberFormatterBehavior10_4];
     // next line is very important!
[myNumFormatter setNumberStyle:NSNumberFormatterDecimalStyle]; // crucial

NSNumber *tempNum = [myNumFormatter numberFromString:tempStr];
NSLog(@"string '%@' gives NSNumber '%@' with intValue '%i'", 
    tempStr, tempNum, [tempNum intValue]);
[myNumFormatter release];  // good citizen

How to render pdfs using C#

Use the web browser control. This requires Adobe reader to be installed but most likely you have it anyway. Set the UrL of the control to the file location.

Last Key in Python Dictionary

yes there is : len(data)-1.

For the first element it´s : 0

Pseudo-terminal will not be allocated because stdin is not a terminal

Try ssh -t -t(or ssh -tt for short) to force pseudo-tty allocation even if stdin isn't a terminal.

See also: Terminating SSH session executed by bash script

From ssh manpage:

-T      Disable pseudo-tty allocation.

-t      Force pseudo-tty allocation.  This can be used to execute arbitrary 
        screen-based programs on a remote machine, which can be very useful,
        e.g. when implementing menu services.  Multiple -t options force tty
        allocation, even if ssh has no local tty.

How do you make a div follow as you scroll?

You can either use the css property Fixed, or if you need something more fine-tuned then you need to use javascript and track the scrollTop property which defines where the user agent's scrollbar location is (0 being at the top ... and x being at the bottom)

.Fixed
{
    position: fixed;
    top: 20px;
}

or with jQuery:

$('#ParentContainer').scroll(function() { 
    $('#FixedDiv').css('top', $(this).scrollTop());
});

What is the best Java email address validation method?

This is the best method:

public static boolean isValidEmail(String enteredEmail){
        String EMAIL_REGIX = "^[\\\\w!#$%&’*+/=?`{|}~^-]+(?:\\\\.[\\\\w!#$%&’*+/=?`{|}~^-]+)*@(?:[a-zA-Z0-9-]+\\\\.)+[a-zA-Z]{2,6}$";
        Pattern pattern = Pattern.compile(EMAIL_REGIX);
        Matcher matcher = pattern.matcher(enteredEmail);
        return ((!enteredEmail.isEmpty()) && (enteredEmail!=null) && (matcher.matches()));
    }

Sources:- http://howtodoinjava.com/2014/11/11/java-regex-validate-email-address/

http://www.rfc-editor.org/rfc/rfc5322.txt

What is "loose coupling?" Please provide examples

Definition

Essentially, coupling is how much a given object or set of object relies on another object or another set of objects in order to accomplish its task.

High Coupling

Think of a car. In order for the engine to start, a key must be inserted into the ignition, turned, gasoline must be present, a spark must occur, pistons must fire, and the engine must come alive. You could say that a car engine is highly coupled to several other objects. This is high coupling, but it's not really a bad thing.

Loose Coupling

Think of a user control for a web page that is responsible for allowing users to post, edit, and view some type of information. The single control could be used to let a user post a new piece of information or edit a new piece of information. The control should be able to be shared between two different paths - new and edit. If the control is written in such a way that it needs some type of data from the pages that will contain it, then you could say it's too highly coupled. The control should not need anything from its container page.

Checking if any elements in one list are in another

I wrote the following code in one of my projects. It basically compares each individual element of the list. Feel free to use it, if it works for your requirement.

def reachedGoal(a,b):
    if(len(a)!=len(b)):
        raise ValueError("Wrong lists provided")

    for val1 in range(0,len(a)):
        temp1=a[val1]
        temp2=b[val1]
        for val2 in range(0,len(b)):
            if(temp1[val2]!=temp2[val2]):
                return False
    return True

Stop an input field in a form from being submitted

Add disabled="disabled" in input and while jquery remove the attribute disabled when you want to submit it using .removeAttr('disabled')

HTML:

<input type="hidden" name="test" value="test" disabled='disabled'/>

jquery:

$("input[name='test']").removeAttr('disabled');

IntelliJ, can't start simple web application: Unable to ping server at localhost:1099

I solve this problem adding the environment variables JAVA_HOME(C:\Program Files\Java\jdkx.x.x_xx) and JRE_HOME.

How to get the current time in YYYY-MM-DD HH:MI:Sec.Millisecond format in Java?

I don't see a reference to this:

SimpleDateFormat f = new SimpleDateFormat("yyyyMMddHHmmssSSS");

above format is also useful.

http://www.java2s.com/Tutorials/Java/Date/Date_Format/Format_date_in_yyyyMMddHHmmssSSS_format_in_Java.htm

Print all properties of a Python Class

In this simple case you can use vars():

an = Animal()
attrs = vars(an)
# {'kids': 0, 'name': 'Dog', 'color': 'Spotted', 'age': 10, 'legs': 2, 'smell': 'Alot'}
# now dump this in some way or another
print(', '.join("%s: %s" % item for item in attrs.items()))

If you want to store Python objects on the disk you should look at shelve — Python object persistence.

Property '...' has no initializer and is not definitely assigned in the constructor

If you want to initialize an object based on an interface you can initialize it empty with following statement.

myObj: IMyObject = {} as IMyObject;

How to fix 'Unchecked runtime.lastError: The message port closed before a response was received' chrome issue?

For those coming here to debug this error in Chrome 73, one possibility is because Chrome 73 onwards disallows cross-origin requests in content scripts.

More reading:

  1. https://www.chromestatus.com/feature/5629709824032768
  2. https://www.chromium.org/Home/chromium-security/extension-content-script-fetches

This affects many Chrome extension authors, who now need to scramble to fix the extensions because Chrome thinks "Our data shows that most extensions will not be affected by this change."

(it has nothing to do with your app code)

UPDATE: I fixed the CORs issue but I still see this error. I suspect it is Chrome's fault here.

How to get only numeric column values?

Use This [Tested]

To get numeric

SELECT column1
FROM table
WHERE Isnumeric(column1) = 1; // will return Numeric values

To get non-numeric

SELECT column1
FROM table
WHERE Isnumeric(column1) = 0; // will return non-numeric values

Print number of keys in Redis

For getting count total number of keys, use below command:

127.0.0.1:6379> DBSIZE

Find text in string with C#

You could use Regex:

var regex = new Regex(".*my (.*) is.*");
if (regex.IsMatch("This is an example string and my data is here"))
{
    var myCapturedText = regex.Match("This is an example string and my data is here").Groups[1].Value;
    Console.WriteLine("This is my captured text: {0}", myCapturedText);
}

Questions every good .NET developer should be able to answer?

Martin Fowler prefers design skills over platform knowledge. On the other hand you can ask a question which will show knowledge of design patterns and .NET platform like this:

  • Name design patterns and principles you know and how they are utilized in .NET Framework?

Increase max execution time for php

There's probably a limit set in your webserver. Some browsers/proxies will also implement a timeout. Invoking long running processes via an HTTP request is just plain silly. The right way to solve the problem (assuming you can't make the processing any faster) is to use the HTTP request to trigger processing outside of the webserver session group then poll the status via HTTP until you've got a result set.

Angular is automatically adding 'ng-invalid' class on 'required' fields

Thanks to this post, I use this style to remove the red border that appears automatically with bootstrap when a required field is displayed, but user didn't have a chance to input anything already:

input.ng-pristine.ng-invalid {
    -webkit-box-shadow: none;
    -ms-box-shadow: none;
    box-shadow:none;
}

Maven and adding JARs to system scope

System scope was only designed to deal with 'system' files; files sitting in some fixed location. Files in /usr/lib, or ${java.home} (e.g. tools.jar). It wasn't designed to support miscellaneous .jar files in your project.

The authors intentionally refused to make the pathname expansions work right for that to discourage you. As a result, in the short term you can use install:install-file to install into the local repo, and then some day use a repo manager to share.

how to get domain name from URL

Basically, what you want is:

google.com        -> google.com    -> google
www.google.com    -> google.com    -> google
google.co.uk      -> google.co.uk  -> google
www.google.co.uk  -> google.co.uk  -> google
www.google.org    -> google.org    -> google
www.google.org.uk -> google.org.uk -> google

Optional:

www.google.com     -> google.com    -> www.google
images.google.com  -> google.com    -> images.google
mail.yahoo.co.uk   -> yahoo.co.uk   -> mail.yahoo
mail.yahoo.com     -> yahoo.com     -> mail.yahoo
www.mail.yahoo.com -> yahoo.com     -> mail.yahoo

You don't need to construct an ever-changing regex as 99% of domains will be matched properly if you simply look at the 2nd last part of the name:

(co|com|gov|net|org)

If it is one of these, then you need to match 3 dots, else 2. Simple. Now, my regex wizardry is no match for that of some other SO'ers, so the best way I've found to achieve this is with some code, assuming you've already stripped off the path:

 my @d=split /\./,$domain;                # split the domain part into an array
 $c=@d;                                   # count how many parts
 $dest=$d[$c-2].'.'.$d[$c-1];             # use the last 2 parts
 if ($d[$c-2]=~m/(co|com|gov|net|org)/) { # is the second-last part one of these?
   $dest=$d[$c-3].'.'.$dest;              # if so, add a third part
 };
 print $dest;                             # show it

To just get the name, as per your question:

 my @d=split /\./,$domain;                # split the domain part into an array
 $c=@d;                                   # count how many parts
 if ($d[$c-2]=~m/(co|com|gov|net|org)/) { # is the second-last part one of these?
   $dest=$d[$c-3];                        # if so, give the third last
   $dest=$d[$c-4].'.'.$dest if ($c>3);    # optional bit
 } else {
   $dest=$d[$c-2];                        # else the second last
   $dest=$d[$c-3].'.'.$dest if ($c>2);    # optional bit 
 };
 print $dest;                             # show it

I like this approach because it's maintenance-free. Unless you want to validate that it's actually a legitimate domain, but that's kind of pointless because you're most likely only using this to process log files and an invalid domain wouldn't find its way in there in the first place.

If you'd like to match "unofficial" subdomains such as bozo.za.net, or bozo.au.uk, bozo.msf.ru just add (za|au|msf) to the regex.

I'd love to see someone do all of this using just a regex, I'm sure it's possible.

How to deal with certificates using Selenium?

Whenever I run into this issue with newer browsers, I just use AppRobotic Personal edition to click specific screen coordinates, or tab through the buttons and click.

Basically it's just using its macro functionality, but won't work on headless setups though.

String contains another string

You can use .indexOf():

if(str.indexOf(substr) > -1) {

}

File path for project files?

Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"JukeboxV2.0\JukeboxV2.0\Datos\ich will.mp3")

base directory + your filename

Session only cookies with Javascript

For creating session only cookie with java script, you can use the following. This works for me.

document.cookie = "cookiename=value; expires=0; path=/";

then get cookie value as following

 //get cookie 
var cookiename = getCookie("cookiename");
if (cookiename == "value") {
    //write your script
}

//function getCookie        
function getCookie(cname) {
    var name = cname + "=";
    var ca = document.cookie.split(';');
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') c = c.substring(1);
        if (c.indexOf(name) != -1) return c.substring(name.length, c.length);
    }
    return "";
}

Okay to support IE we can leave "expires" completely and can use this

document.cookie = "mtracker=somevalue; path=/";

Jquery Setting Value of Input Field

$('.formData').attr('value','YOUR_VALUE')

Dynamic require in RequireJS, getting "Module name has not been loaded yet for context" error?

The limitation relates to the simplified CommonJS syntax vs. the normal callback syntax:

Loading a module is inherently an asynchronous process due to the unknown timing of downloading it. However, RequireJS in emulation of the server-side CommonJS spec tries to give you a simplified syntax. When you do something like this:

var foomodule = require('foo');
// do something with fooModule

What's happening behind the scenes is that RequireJS is looking at the body of your function code and parsing out that you need 'foo' and loading it prior to your function execution. However, when a variable or anything other than a simple string, such as your example...

var module = require(path); // Call RequireJS require

...then Require is unable to parse this out and automatically convert it. The solution is to convert to the callback syntax;

var moduleName = 'foo';
require([moduleName], function(fooModule){
    // do something with fooModule
})

Given the above, here is one possible rewrite of your 2nd example to use the standard syntax:

define(['dyn_modules'], function (dynModules) {
    require(dynModules, function(){
        // use arguments since you don't know how many modules you're getting in the callback
        for (var i = 0; i < arguments.length; i++){
            var mymodule = arguments[i];
            // do something with mymodule...
        }
    });

});

EDIT: From your own answer, I see you're using underscore/lodash, so using _.values and _.object can simplify the looping through arguments array as above.

How to find children of nodes using BeautifulSoup

Perhaps you want to do

soup.find("li", { "class" : "test" }).find('a')

Python code to remove HTML tags from a string

Note that this isn't perfect, since if you had something like, say, <a title=">"> it would break. However, it's about the closest you'd get in non-library Python without a really complex function:

import re

TAG_RE = re.compile(r'<[^>]+>')

def remove_tags(text):
    return TAG_RE.sub('', text)

However, as lvc mentions xml.etree is available in the Python Standard Library, so you could probably just adapt it to serve like your existing lxml version:

def remove_tags(text):
    return ''.join(xml.etree.ElementTree.fromstring(text).itertext())

How to update one file in a zip archive

Try the following:

zip [zipfile] [file to update] 

An example:

$ zip test.zip test/test.txt
updating: test/test.txt (stored 0%)

How do I get the total number of unique pairs of a set in the database?

I was solving this algorithm and get stuck with the pairs part.

This explanation help me a lot https://betterexplained.com/articles/techniques-for-adding-the-numbers-1-to-100/

So to calculate the sum of series of numbers:

n(n+1)/2

But you need to calculate this

1 + 2 + ... + (n-1)

So in order to get this you can use

n(n+1)/2 - n

that is equal to

n(n-1)/2

.includes() not working in Internet Explorer

You can do the same with !! and ~ operators

 var myString = 'this is my string';

 !!~myString.indexOf('string');
 // -> true

 !!~myString.indexOf('hello');
 // -> false

here's the explanation of the two operators (!! and ~ )

What is the !! (not not) operator in JavaScript?

https://www.joezimjs.com/javascript/great-mystery-of-the-tilde/

Pass a String from one Activity to another Activity in Android

You need to pass it as an extra:

String easyPuzzle  = "630208010200050089109060030"+
                     "008006050000187000060500900"+
                     "09007010681002000502003097";

Intent i = new Intent(this, ToClass.class);
i.putExtra("epuzzle", easyPuzzle);
startActivity(i); 

Then extract it from your new activity like this:

Intent intent = getIntent();
String easyPuzzle = intent.getExtras().getString("epuzzle");

Registry key Error: Java version has value '1.8', but '1.7' is required

As for me on win7 64bit.

Copy the java.exe javaw.exe javaws.exe in the folder C:\Program Files\Java\jre1.8.0_91\bin to the C:\Windows\System32.

and then open cmd, type java -version.

C:\Users\HEcom>java -version
java version "1.8.0_91"
Java(TM) SE Runtime Environment (build 1.8.0_91-b14)
Java HotSpot(TM) 64-Bit Server VM (build 25.91-b14, mixed mode)

Before the above make sure the Registry's CurrentVersion is 1.8

In the START menu type "regedit" to open the Registry editor

  1. Go to "HKEY_LOCAL_MACHINE" on the left-hand side registry explorer/tree menu
  2. Click "SOFTWARE" within the "HKEY_LOCAL_MACHINE" registries
  3. Click "JavaSoft" within the "SOFTWARE" registries
  4. Click "Java Runtime Environment" within the "JavaSoft" list of registries here you can see different versions of installed java
  5. Click "Java Runtime Environment"- On right hand side you will get 4-5 rows . Please select "CurrentVersion" and right Click( select modify option) make sure the version is "1.8"

Prevent linebreak after </div>

The div elements are block elements, so by default they take upp the full available width.

One way is to turn them into inline elements:

.label, .text { display: inline; }

This will have the same effect as using span elements instead of div elements.

Another way is to float the elements:

.label, .text { float: left; }

This will change how the width of the elements is decided, so that thwy will only be as wide as their content. It will also make the elements float beside each other, similar to how images flow beside each other.

You can also consider changing the elements. The div element is intended for document divisions, I usually use a label and a span element for a construct like this:

<label>My Label:</label>
<span>My text</span>

Regular expression to match a word or its prefix

I test examples in js. Simplest solution - just add word u need inside / /:

var reg = /cat/;
reg.test('some cat here');//1 test
true // result
reg.test('acatb');//2 test
true // result

Now if u need this specific word with boundaries, not inside any other signs-letters. We use b marker:

var reg = /\bcat\b/
reg.test('acatb');//1 test 
false // result
reg.test('have cat here');//2 test
true // result

We have also exec() method in js, whichone returns object-result. It helps f.g. to get info about place/index of our word.

var matchResult = /\bcat\b/.exec("good cat good");
console.log(matchResult.index); // 5

If we need get all matched words in string/sentence/text, we can use g modifier (global match):

"cat good cat good cat".match(/\bcat\b/g).length
// 3 

Now the last one - i need not 1 specific word, but some of them. We use | sign, it means choice/or.

"bad dog bad".match(/\bcat|dog\b/g).length
// 1

How can I add a variable to console.log?

console.log takes multiple arguments, so just use:

console.log("story", name, "story");

If name is an object or an array then using multiple arguments is better than concatenation. If you concatenate an object or array into a string you simply log the type rather than the content of the variable.

But if name is just a primitive type then multiple arguments works the same as concatenation.

Counter exit code 139 when running, but gdb make it through

this error is also caused by null pointer reference. if you are using a pointer who is not initialized then it causes this error.

to check either a pointer is initialized or not you can try something like

Class *pointer = new Class();
if(pointer!=nullptr){
    pointer->myFunction();
}

What is the main difference between Collection and Collections in Java?

Collections is a class which has some static methods and that method returns the collection. Collection is an interface,rather than root interface in collection hierarchy.

Embed YouTube video - Refused to display in a frame because it set 'X-Frame-Options' to 'SAMEORIGIN'

Along with the embed, I also had to install the Google Cast extension in my browser.

<iframe width="1280" height="720" src="https://www.youtube.com/embed/4u856utdR94" frameborder="0" allowfullscreen></iframe>

How to kill a process in MacOS?

If you're trying to kill -9 it, you have the correct PID, and nothing happens, then you don't have permissions to kill the process.

Solution:

$ sudo kill -9 PID

Okay, sure enough Mac OS/X does give an error message for this case:

$ kill -9 196
-bash: kill: (196) - Operation not permitted

So, if you're not getting an error message, you somehow aren't getting the right PID.

Android - Set text to TextView

final TextView err = (TextView)findViewById(R.id.texto);
err.setText("Escriba su mensaje y luego seleccione el canal.");

you can find every thing you need about textview here

Collections.emptyList() vs. new instance

Starting with Java 5.0 you can specify the type of element in the container:

Collections.<Foo>emptyList()

I concur with the other responses that for cases where you want to return an empty list that stays empty, you should use this approach.

Send a base64 image in HTML email

An alternative approach may be to embed images in the email using the cid method. (Basically including the image as an attachment, and then embedding it). In my experience, this approach seems to be well supported these days.

enter image description here

Source: https://www.campaignmonitor.com/blog/how-to/2008/08/embedding-images-revisited/

How can I send JSON response in symfony2 controller

Symfony 2.1 has a JsonResponse class.

return new JsonResponse(array('name' => $name));

The passed in array will be JSON encoded the status code will default to 200 and the content type will be set to application/json.

There is also a handy setCallback function for JSONP.

jquery stop child triggering parent event

The simplest solution is to add this CSS to the children:

.your-child {
    pointer-events: none;
}

Nested select statement in SQL Server

The answer provided by Joe Stefanelli is already correct.

SELECT name FROM (SELECT name FROM agentinformation) as a  

We need to make an alias of the subquery because a query needs a table object which we will get from making an alias for the subquery. Conceptually, the subquery results are substituted into the outer query. As we need a table object in the outer query, we need to make an alias of the inner query.

Statements that include a subquery usually take one of these forms:

  • WHERE expression [NOT] IN (subquery)
  • WHERE expression comparison_operator [ANY | ALL] (subquery)
  • WHERE [NOT] EXISTS (subquery)

Check for more subquery rules and subquery types.

More examples of Nested Subqueries.

  1. IN / NOT IN – This operator takes the output of the inner query after the inner query gets executed which can be zero or more values and sends it to the outer query. The outer query then fetches all the matching [IN operator] or non matching [NOT IN operator] rows.

  2. ANY – [>ANY or ANY operator takes the list of values produced by the inner query and fetches all the values which are greater than the minimum value of the list. The

e.g. >ANY(100,200,300), the ANY operator will fetch all the values greater than 100.

  1. ALL – [>ALL or ALL operator takes the list of values produced by the inner query and fetches all the values which are greater than the maximum of the list. The

e.g. >ALL(100,200,300), the ALL operator will fetch all the values greater than 300.

  1. EXISTS – The EXISTS keyword produces a Boolean value [TRUE/FALSE]. This EXISTS checks the existence of the rows returned by the sub query.

Running JAR file on Windows 10

How do I run an executable JAR file? If you have a jar file called Example.jar, follow these rules:

Open a notepad.exe.
Write : java -jar Example.jar.
Save it with the extension .bat.
Copy it to the directory which has the .jar file.
Double click it to run your .jar file.

Cannot invoke an expression whose type lacks a call signature

I had the same issue with numeral, a JS library. The fix was to install the typings again with this command:

npm install --save @types/numeral

Read text file into string array (and write)

You can use os.File (which implements the io.Reader interface) with the bufio package for that. However, those packages are build with fixed memory usage in mind (no matter how large the file is) and are quite fast.

Unfortunately this makes reading the whole file into the memory a bit more complicated. You can use a bytes.Buffer to join the parts of the line if they exceed the line limit. Anyway, I recommend you to try to use the line reader directly in your project (especially if do not know how large the text file is!). But if the file is small, the following example might be sufficient for you:

package main

import (
    "os"
    "bufio"
    "bytes"
    "fmt"
)

// Read a whole file into the memory and store it as array of lines
func readLines(path string) (lines []string, err os.Error) {
    var (
        file *os.File
        part []byte
        prefix bool
    )
    if file, err = os.Open(path); err != nil {
        return
    }
    reader := bufio.NewReader(file)
    buffer := bytes.NewBuffer(make([]byte, 1024))
    for {
        if part, prefix, err = reader.ReadLine(); err != nil {
            break
        }
        buffer.Write(part)
        if !prefix {
            lines = append(lines, buffer.String())
            buffer.Reset()
        }
    }
    if err == os.EOF {
        err = nil
    }
    return
}

func main() {
    lines, err := readLines("foo.txt")
    if err != nil {
        fmt.Println("Error: %s\n", err)
        return
    }
    for _, line := range lines {
        fmt.Println(line)
    }
}

Another alternative might be to use io.ioutil.ReadAll to read in the complete file at once and do the slicing by line afterwards. I don't give you an explicit example of how to write the lines back to the file, but that's basically an os.Create() followed by a loop similar to that one in the example (see main()).

Get current index from foreach loop

Use Enumerable.Select<TSource, TResult> Method (IEnumerable<TSource>, Func<TSource, Int32, TResult>)

list = list.Cast<object>().Select( (v, i) => new {Value= v, Index = i});

foreach(var row in list)
{
    bool IsChecked = (bool)((CheckBox)DataGridDetail.Columns[0].GetCellContent(row.Value)).IsChecked;
    row.Index ...
}

Hash table in JavaScript

If all you want to do is store some static values in a lookup table, you can use an Object Literal (the same format used by JSON) to do it compactly:

var table = { one: [1,10,5], two: [2], three: [3, 30, 300] }

And then access them using JavaScript's associative array syntax:

alert(table['one']);    // Will alert with [1,10,5]
alert(table['one'][1]); // Will alert with 10

Round up to Second Decimal Place in Python

Note that the ceil(num * 100) / 100 trick will crash on some degenerate inputs, like 1e308. This may not come up often but I can tell you it just cost me a couple of days. To avoid this, "it would be nice if" ceil() and floor() took a decimal places argument, like round() does... Meanwhile, anyone know a clean alternative that won't crash on inputs like this? I had some hopes for the decimal package but it seems to die too:

>>> from math import ceil
>>> from decimal import Decimal, ROUND_DOWN, ROUND_UP
>>> num = 0.1111111111000
>>> ceil(num * 100) / 100
0.12
>>> float(Decimal(num).quantize(Decimal('.01'), rounding=ROUND_UP))
0.12
>>> num = 1e308
>>> ceil(num * 100) / 100
Traceback (most recent call last):
  File "<string>", line 301, in runcode
  File "<interactive input>", line 1, in <module>
OverflowError: cannot convert float infinity to integer
>>> float(Decimal(num).quantize(Decimal('.01'), rounding=ROUND_UP))
Traceback (most recent call last):
  File "<string>", line 301, in runcode
  File "<interactive input>", line 1, in <module>
decimal.InvalidOperation: [<class 'decimal.InvalidOperation'>]

Of course one might say that crashing is the only sane behavior on such inputs, but I would argue that it's not the rounding but the multiplication that's causing the problem (that's why, eg, 1e306 doesn't crash), and a cleaner implementation of the round-up-nth-place fn would avoid the multiplication hack.

setting JAVA_HOME & CLASSPATH in CentOS 6

I created a folder named a in /home/prasanth and copied your code to a file named A.java. I compiled from /home/prasanth as javac a/A.java and run javac a.A. I got output as

a!

How do I print colored output to the terminal in Python?

A side note: Windows users should run os.system('color') first, otherwise you would see some ANSI escape sequences rather than a colored output.

In PHP, how do you change the key of an array element?

The way you would do this and preserve the ordering of the array is by putting the array keys into a separate array, find and replace the key in that array and then combine it back with the values.

Here is a function that does just that:

function change_key( $array, $old_key, $new_key ) {

    if( ! array_key_exists( $old_key, $array ) )
        return $array;

    $keys = array_keys( $array );
    $keys[ array_search( $old_key, $keys ) ] = $new_key;

    return array_combine( $keys, $array );
}

ASP.NET MVC: No parameterless constructor defined for this object

This error started for me when I added a new way to instantiate a class.

Example:

    public class myClass
    {
         public string id{ get; set; }
         public List<string> myList{get; set;}

         // error happened after I added this
         public myClass(string id, List<string> lst)
         {
             this.id= id;
             this.myList= lst;
         }
     }

The error was resolved when I added when I made this change, adding a parameterless constructor. I believe the compiler creates a parameterless constuctor by default but if you add your own then you must explicitly create it.

    public class myClass
    {
         public string id{ get; set; }
         public List<string> myList{get; set;}

         // error doesn't happen when I add this
         public myClass() { }

         // error happened after I added this, but no longer happens after adding above
         public myClass(string id, List<string> lst)
         {
             this.id= id;
             this.myList= lst;
         }
     }

How to find elements by class

CSS selectors

single class first match

soup.select_one('.stylelistrow')

list of matches

soup.select('.stylelistrow')

compound class (i.e. AND another class)

soup.select_one('.stylelistrow.otherclassname')
soup.select('.stylelistrow.otherclassname')

Spaces in compound class names e.g. class = stylelistrow otherclassname are replaced with ".". You can continue to add classes.

list of classes (OR - match whichever present

soup.select_one('.stylelistrow, .otherclassname')
soup.select('.stylelistrow, .otherclassname')

bs4 4.7.1 +

Specific class whose innerText contains a string

soup.select_one('.stylelistrow:contains("some string")')
soup.select('.stylelistrow:contains("some string")')

Specific class which has a certain child element e.g. a tag

soup.select_one('.stylelistrow:has(a)')
soup.select('.stylelistrow:has(a)')

html <input type="text" /> onchange event not working

onchange only occurs when the change to the input element is committed by the user, most of the time this is when the element loses focus.

if you want your function to fire everytime the element value changes you should use the oninput event - this is better than the key up/down events as the value can be changed with the user's mouse ie pasted in, or auto-fill etc

Read more about the change event here

Read more about the input event here

Border for an Image view in Android?

I almost gave up about this.

This is my condition using glide to load image, see detailed glide issue here about rounded corner transformations and here

I've also the same attributes for my ImageView, for everyone answer here 1, here 2 & here 3

android:cropToPadding="true"
android:adjustViewBounds="true"
android:scaleType="fitCenter"`
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/path_to_rounded_drawable"

But still no success.

After researching for awhile, using a foreground attributes from this SO answer here give a result android:foreground="@drawable/all_round_border_white"

unfortunately it giving me the "not nice" border corner like below image:

enter image description here

automating telnet session using bash scripts

Play with tcpdump or wireshark and see what commands are sent to the server itself

Try this

printf (printf "$username\r\n$password\r\nwhoami\r\nexit\r\n") | ncat $target 23

Some servers require a delay with the password as it does not hold lines on the stack

printf (printf "$username\r\n";sleep 1;printf "$password\r\nwhoami\r\nexit\r\n") | ncat $target 23**

Reading file using fscanf() in C

In your code:

while(fscanf(fp,"%s %c",item,&status) == 1)  

why 1 and not 2? The scanf functions return the number of objects read.

Error "package android.support.v7.app does not exist"

Switching to AndroidX helped me: import androidx.appcompat.app.AppCompatActivity;

Quick way to list all files in Amazon S3 bucket?

function showUploads(){
    if (!class_exists('S3')) require_once 'S3.php';
    // AWS access info
    if (!defined('awsAccessKey')) define('awsAccessKey', '234567665464tg');
    if (!defined('awsSecretKey')) define('awsSecretKey', 'dfshgfhfghdgfhrt463457');
    $bucketName = 'my_bucket1234';
    $s3 = new S3(awsAccessKey, awsSecretKey);
    $contents = $s3->getBucket($bucketName);
    echo "<hr/>List of Files in bucket : {$bucketName} <hr/>";
    $n = 1;
    foreach ($contents as $p => $v):
        echo $p."<br/>";
        $n++;
    endforeach;
}

Generate pdf from HTML in div using Javascript

One way is to use window.print() function. Which does not require any library

Pros

1.No external library require.

2.We can print only selected parts of body also.

3.No css conflicts and js issues.

4.Core html/js functionality

---Simply add below code

CSS to

@media print {
        body * {
            visibility: hidden; // part to hide at the time of print
            -webkit-print-color-adjust: exact !important; // not necessary use         
               if colors not visible
        }

        #printBtn {
            visibility: hidden !important; // To hide 
        }

        #page-wrapper * {
            visibility: visible; // Print only required part
            text-align: left;
            -webkit-print-color-adjust: exact !important;
        }
    }

JS code - Call bewlow function on btn click

$scope.printWindow = function () {
  window.print()
}

Note: Use !important in every css object

Example -

.legend  {
  background: #9DD2E2 !important;
}

jQuery - simple input validation - "empty" and "not empty"

Actually there is a simpler way to do this, just:

if ($("#input").is(':empty')) {
console.log('empty');
} else {
console.log('not empty');
}

src: https://www.geeksforgeeks.org/how-to-check-an-html-element-is-empty-using-jquery/

How to stop app that node.js express 'npm start'

If is very simple, just kill the process..

localmacpro$ ps
  PID TTY           TIME CMD
 5014 ttys000    0:00.05 -bash
 6906 ttys000    0:00.29 npm   
 6907 ttys000    0:06.39 node /Users/roger_macpro/my-project/node_modules/.bin/webpack-dev-server --inline --progress --config build/webpack.dev.conf.js
 6706 ttys001    0:00.05 -bash
 7157 ttys002    0:00.29 -bash

localmacpro$ kill -9 6907 6906

For loop for HTMLCollection elements

On Edge

if(!NodeList.prototype.forEach) {
  NodeList.prototype.forEach = function(fn, scope) {
    for(var i = 0, len = this.length; i < len; ++i) {
      fn.call(scope, this[i], i, this);
    }
  }
}

When do I need to use a semicolon vs a slash in Oracle SQL?

I know this is an old thread, but I just stumbled upon it and I feel this has not been explained completely.

There is a huge difference in SQL*Plus between the meaning of a / and a ; because they work differently.

The ; ends a SQL statement, whereas the / executes whatever is in the current "buffer". So when you use a ; and a / the statement is actually executed twice.

You can easily see that using a / after running a statement:

SQL*Plus: Release 11.2.0.1.0 Production on Wed Apr 18 12:37:20 2012

Copyright (c) 1982, 2010, Oracle.  All rights reserved.

Connected to:
Oracle Database 11g Enterprise Edition Release 11.2.0.1.0 - Production
With the Partitioning and OLAP options

SQL> drop table foo;

Table dropped.

SQL> /
drop table foo
           *
ERROR at line 1:
ORA-00942: table or view does not exist

In this case one actually notices the error.


But assuming there is a SQL script like this:

drop table foo;
/

And this is run from within SQL*Plus then this will be very confusing:

SQL*Plus: Release 11.2.0.1.0 Production on Wed Apr 18 12:38:05 2012

Copyright (c) 1982, 2010, Oracle.  All rights reserved.


Connected to:
Oracle Database 11g Enterprise Edition Release 11.2.0.1.0 - Production
With the Partitioning and OLAP options

SQL> @drop

Table dropped.

drop table foo
           *
ERROR at line 1:
ORA-00942: table or view does not exist

The / is mainly required in order to run statements that have embedded ; like a CREATE PROCEDURE statement.

How to format DateTime in Flutter , How to get current time in flutter?

You can use DateFormat from intl package.

import 'package:intl/intl.dart';

DateTime now = DateTime.now();
String formattedDate = DateFormat('yyyy-MM-dd – kk:mm').format(now);

"Missing return statement" within if / for / while

If you put return statement in if, while or for statement then it may or may not return value. If it will not go inside these statement then also that method should return some value ( that could be null). To ensure that, compiler will force you to write this return statement which is after if, while or for.

But if you write if / else block and each one of them is having return in it then compiler knows that either if or else will get execute and method will return a value. So this time compiler will not force you.

if(condition)
{
 return;
}
else
{
 return;
}

Python basics printing 1 to 100

When you change count = count + 1 to count = count + 3 or count = count + 9, count will never be equal to 100. At the very best it'll be 99. That's not enough.

What you've got here is the classic case of infinite loop: count is never equal to 100 (sure, at some point it'll be greater than 100, but your while loop doesn't check for this condition) and the while loop goes on and on.

What you want is probably:

while count < 100: # Or <=, if you feel like printing a hundred.

Not:

while count != 0:  # Spaces around !=. Makes Guido van Rossum happy.

Now the loop will terminate when count >= 100.

Take a look at Python documentation.

Windows equivalent of linux cksum command

In the year 2019, Microsoft offers the following solution for Windows 10. This solution works for SHA256 checksum.

https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/get-filehash?view=powershell-6

Press the Windows key. Type PowerShell. Select Windows Powershell. Press Enter key. Paste the command

Get-FileHash C:\Users\Donald\Downloads\File-to-be-checked-by-sha256.exe | Format-List

Replace File-to-be-checked-by-sha256.exe by the name of your file to be checked.

Replace the path to your path where the file is. Press Enter key. Powershell shows then the following

Algorithm : SHA256 Hash : 123456789ABCDEFGH1234567890... Path : C:\Users\Donald\Downloads\File-to-be-checked-by-sha256.exe

Converting string format to datetime in mm/dd/yyyy

I did like this

var datetoEnter= DateTime.ParseExact(createdDate, "dd/mm/yyyy", CultureInfo.InvariantCulture);

Java Reflection Performance

If there really is need for something faster than reflection, and it's not just a premature optimization, then bytecode generation with ASM or a higher level library is an option. Generating the bytecode the first time is slower than just using reflection, but once the bytecode has been generated, it is as fast as normal Java code and will be optimized by the JIT compiler.

Some examples of applications which use code generation:

  • Invoking methods on proxies generated by CGLIB is slightly faster than Java's dynamic proxies, because CGLIB generates bytecode for its proxies, but dynamic proxies use only reflection (I measured CGLIB to be about 10x faster in method calls, but creating the proxies was slower).

  • JSerial generates bytecode for reading/writing the fields of serialized objects, instead of using reflection. There are some benchmarks on JSerial's site.

  • I'm not 100% sure (and I don't feel like reading the source now), but I think Guice generates bytecode to do dependency injection. Correct me if I'm wrong.

cancelling a handler.postdelayed process

Another way is to handle the Runnable itself:

Runnable r = new Runnable {
    public void run() {
        if (booleanCancelMember != false) {
            //do what you need
        }
    }
}

PHP array value passes to next row

Change the checkboxes so that the name includes the index inside the brackets:

<input type="checkbox" class="checkbox_veh" id="checkbox_addveh<?php echo $i; ?>" <?php if ($vehicle_feature[$i]->check) echo "checked"; ?> name="feature[<?php echo $i; ?>]" value="<?php echo $vehicle_feature[$i]->id; ?>"> 

The checkboxes that aren't checked are never submitted. The boxes that are checked get submitted, but they get numbered consecutively from 0, and won't have the same indexes as the other corresponding input fields.

How to preview git-pull without doing fetch?

I may be late to the party, but this is something which bugged me for too long. In my experience, I would rather want to see which changes are pending than update my working copy and deal with those changes.

This goes in the ~/.gitconfig file:

[alias]
        diffpull=!git fetch && git diff HEAD..@{u}

It fetches the current branch, then does a diff between the working copy and this fetched branch. So you should only see the changes that would come with git pull.

XAMPP, Apache - Error: Apache shutdown unexpectedly

One of the causes could be that you are not running the XAMPP Control Panel as an administrator.

Different ways of loading a file as an InputStream

It Works , try out this :

InputStream in_s1 =   TopBrandData.class.getResourceAsStream("/assets/TopBrands.xml");

Make docker use IPv4 for port binding

As @daniel-t points out in the comment: github.com/docker/docker/issues/2174 is about showing binding only to IPv6 in netstat, but that is not an issue. As that github issues states:

When setting up the proxy, Docker requests the loopback address '127.0.0.1', Linux realises this is an address that exists in IPv6 (as ::0) and opens on both (but it is formally an IPv6 socket). When you run netstat it sees this and tells you it is an IPv6 - but it is still listening on IPv4. If you have played with your settings a little, you may have disabled this trick Linux does - by setting net.ipv6.bindv6only = 1.

In other words, just because you see it as IPv6 only, it is still able to communicate on IPv4 unless you have IPv6 set to only bind on IPv6 with the net.ipv6.bindv6only setting. To be clear, net.ipv6.bindv6only should be 0 - you can run sysctl net.ipv6.bindv6only to verify.

How to install/start Postman native v4.10.3 on Ubuntu 16.04 LTS 64-bit?

Yes, you can install Postman using these commands:

wget https://dl.pstmn.io/download/latest/linux64 -O postman.tar.gz
sudo tar -xzf postman.tar.gz -C /opt
rm postman.tar.gz
sudo ln -s /opt/Postman/Postman /usr/bin/postman

You can also get Postman to show up in the Unity Launcher:

cat > ~/.local/share/applications/postman.desktop <<EOL
[Desktop Entry]
Encoding=UTF-8
Name=Postman
Exec=postman
Icon=/opt/Postman/app/resources/app/assets/icon.png
Terminal=false
Type=Application
Categories=Development;
EOL

You don't need node.js or any other dependencies with a standard Ubuntu dev install.

See more at our blog post at https://blog.bluematador.com/posts/postman-how-to-install-on-ubuntu-1604/.

EDIT: Changed icon.png location. Latest versions of Postman changed their directory structure slightly.

adb shell command to make Android package uninstall dialog appear

In my case, I do an adb shell pm list packages to see first what are the packages/apps installed in my Android device or emulator, then upon locating the desired package/app, I do an adb shell pm uninstall -k com.package.name.

Could not load file or assembly 'EntityFramework' after downgrading EF 5.0.0.0 --> 4.3.1.0

While Building a Project, if in the project properties it shows that it is build under Target.NET Framework 4.5, update it to 4.6 or 4.6.1. Then the build will be able to locate Entity Framework 6.0 in the Web.config file. This approach solved my problem. Selecting Target framework from Project Properties

Java compile error: "reached end of file while parsing }"

It happens when you don't properly close the code block:

if (condition){
  // your code goes here*
  { // This doesn't close the code block

Correct way:

if (condition){
  // your code goes here
} // Close the code block

How can I delete all cookies with JavaScript?

This is a function we are using in our application and it is working fine.

delete cookie: No argument method

function clearListCookies()
{   
    var cookies = document.cookie.split(";");
    for (var i = 0; i < cookies.length; i++)
    {   
        var spcook =  cookies[i].split("=");
        deleteCookie(spcook[0]);
    }
    function deleteCookie(cookiename)
    {
        var d = new Date();
        d.setDate(d.getDate() - 1);
        var expires = ";expires="+d;
        var name=cookiename;
        //alert(name);
        var value="";
        document.cookie = name + "=" + value + expires + "; path=/acc/html";                    
    }
    window.location = ""; // TO REFRESH THE PAGE
}

Edit: This will delete the cookie by setting it to yesterday's date.

Disable HttpClient logging

This took me ages to figure out once, you need this:

log4j.logger.httpclient.wire=ERROR

I guess HttpClient uses "httpclient.wire" as its logger name, not "org.apache.commons.httpclient".

Sneaky buggers.

Detect HTTP or HTTPS then force HTTPS in JavaScript

Not a Javascript way to answer this but if you use CloudFlare you can write page rules that redirect the user much faster to HTTPS and it's free. Looks like this in CloudFlare's Page Rules:

enter image description here

How to iterate through a table rows and get the cell values using jQuery

Hello every one thanks for the help below is the working code for my question

$("#TableView tr.item").each(function() { 
    var quantity1=$(this).find("input.name").val(); 
    var quantity2=$(this).find("input.id").val(); 
});

Modifying a query string without reloading the page

I want to improve Fabio's answer and create a function which adds custom key to the URL string without reloading the page.

function insertUrlParam(key, value) {
    if (history.pushState) {
        let searchParams = new URLSearchParams(window.location.search);
        searchParams.set(key, value);
        let newurl = window.location.protocol + "//" + window.location.host + window.location.pathname + '?' + searchParams.toString();
        window.history.pushState({path: newurl}, '', newurl);
    }
}

Alter Table Add Column Syntax

The correct syntax for adding column into table is:

ALTER TABLE table_name
  ADD column_name column-definition;

In your case it will be:

ALTER TABLE Employees
  ADD EmployeeID int NOT NULL IDENTITY (1, 1)

To add multiple columns use brackets:

ALTER TABLE table_name
  ADD (column_1 column-definition,
       column_2 column-definition,
       ...
       column_n column_definition);

COLUMN keyword in SQL SERVER is used only for altering:

ALTER TABLE table_name
  ALTER COLUMN column_name column_type;

Create a button with rounded border

If you don't want to use OutlineButton and want to stick to normal RaisedButton, you can wrap your button in ClipRRect or ClipOval like:

ClipRRect(
  borderRadius: BorderRadius.circular(40),
  child: RaisedButton(
    child: Text("Button"),
    onPressed: () {},
  ),
),

Multiple commands in an alias for bash

This would run the 2 commands one after another:

alias lock='gnome-screensaver ; gnome-screensaver-command --lock'

How can I catch an error caused by mail()?

PHPMailer handles errors nicely, also a good script to use for sending mail via SMTP...

if(!$mail->Send()) {
  echo "Mailer Error: " . $mail->ErrorInfo;
} else {
  echo "Message sent!";
}

Excel VBA: Copying multiple sheets into new workbook

Rethink your approach. Why would you copy only part of the sheet? You are referring to a named range "WholePrintArea" which doesn't exist. Also you should never use activate, select, copy or paste in your script. These make the "script" vulnerable to user actions and other simultaneous executions. In worst case scenario data ends up in wrong hands.

base64 encoded images in email signatures

The image should be embedded in the message as an attachment like this:

--boundary
Content-Type: image/png; name="sig.png"
Content-Disposition: inline; filename="sig.png"
Content-Transfer-Encoding: base64
Content-ID: <0123456789>
Content-Location: sig.png

base64 data

--boundary

And, the HTML part would reference the image like this:

<img src="cid:0123456789">

In some clients, src="sig.png" will work too.

You'd basically have a multipart/mixed, multipart/alternative, multipart/related message where the image attachment is in the related part.

Clients shouldn't block this image either as it isn't remote.

Or, here's a multipart/alternative, multipart/related example as an mbox file (save as windows newline format and put a blank line at the end. And, use no extension or the .mbs extension):

From 
From: [email protected]
To: [email protected]
Subject: HTML Messages with Embedded Pic in Signature
MIME-Version: 1.0
Content-Type: multipart/alternative; boundary="alternative_boundary"

This is a message with multiple parts in MIME format.

--alternative_boundary
Content-Type: text/plain; charset="utf-8"
Content-Transfer-Encoding: 8bit

test

-- 
[Picture of a Christmas Tree]

--alternative_boundary
Content-Type: multipart/related; boundary="related_boundary"

--related_boundary
Content-Type: text/html; charset="utf-8"
Content-Transfer-Encoding: 8bit

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title></title>
    </head>
    <body>
        <p>test</p>
        <p class="sig">-- <br><img src="cid:0123456789"></p>
    </body>
</html>

--related_boundary
Content-Type: image/png; name="sig.png"
Content-Disposition: inline; filename="sig.png"
Content-Location: sig.png
Content-ID: <0123456789>
Content-Transfer-Encoding: base64

R0lGODlhKAA8AIMLAAD//wAhAABKAABrAACUAAC1AADeAAD/AGsAAP8zM///AP//
///M//////+ZAMwAACH/C05FVFNDQVBFMi4wAwGgDwAh+QQJFAALACwAAAAAKAA8
AAME+3DJSWt1Nuu9Mf+g5IzK6IXopaxn6orlKy/jMc6vQRy4GySABK+HAiaIoQdg
uUSCBAKAYTBwbgyGA2AgsGqo0wMh7K0YEuj0sUxRoAfqB1vycBN21Ki8vOofBndR
c1AKgH8ETE1lBgo7O2JaU2UFAgRoDGoAXV4PD2qYagl7Vp0JDKenfwado0QCAQOQ
DIcDBgIFVgYBAlOxswR5r1VIUbCHwH8HlQWFRLYABVOWamACCkiJAAehaX0rPZ1B
oQSg3Z04AuFqB2IMd+atLwUBtpAHqKdUtbwGM1BTOgA5YhBr374ZAxhAqRVLzA53
OwTEAjhDIZYs09aBASYq+94HfAq3cRt57sWDct2EvEsTpBMVF6sYeEpDQIFDdo62
BHwZApjEhjW94RyQTWK/FPx+Ahpg09GdOzoJ/ESx0JaOQ42e2tsiEYpCEFwAGi04
8g6gSgNOovD0gBeVjCPR2BIAkgOrmSNxPo3rbhgHZiMFPnLkBg2BAuQ2XdmlwK1Z
ooZu1sRz6xWlxd4U9GIHwOmdzFgCFKCERYNoeo2BZsPp0KY+A/OAfZDYWKJZLZBo
1mQXdlojvxNYiXrD8I+2uEvTdFJQksID0XjXiUwjJm6CzBVeBQgwBop1ZPpC8RKt
YN5RCpS6XiyMht093o8KcFFf/vKE0dCmaLeWYhQMwbeQaHLRfNk9o5Q13lQGklFQ
aMLFRLcwcN5qSWmGxS2jKQQFL9nEAgxsDEiwlAHaPPJWIfroo6FVEun0VkL4UABA
CAjUiIAFM2YQogzcoLCjC3HNsYB1aSBB5JFrZBABACH5BAkUAAsALAAAAAAoADwA
AwT7cMlJa3U2670x/6DkjKQXnleJrqnJruMxvq8xHDQbJEyC5yheAnh6MI5HYkgg
YNgGSo7BcGAMBNHNYGA7ELpZiyFBLg/DFvLArEBPHoAEgXDYChQP90IAoNYJCoGB
aACFhX8HBwoGegYAdHReijZoBXxmPWRYYQ8PZmSZZHmcnqBITp2jSgIBN5BVBFwC
BVkGAQJPiVV2rFCrCq1/sXUHAgQFAL45BncFNgSfW8wASoKBB59lhoVAnQqfDNCf
AJ05At5msHPiCeSqLwUBzF6nVnXSuIwvTDYGsXPhiMmSRUOWAC436HmZU+yGDQYF
81FhV+aevzUM3oHoZBD7W7Zs9VaUIhOn4pwE38p0srLCQCqSciBFUuBFGgEryj7E
Ojhg2yOG1hQMIMCEy4p8PB8llKmAIReiW040keUvmUygiexcwbWJwxUrzBDW+Thn
qLEB5UDUe0LxYwJmAhKk+pAqVLZE69qWGZpTQwG7ZISuw7uwzDFAXTXYYoJraKym
Q/HSASDpiiUFljbYitfYRtCF635yMRBUn4UA8aYclCw0shefW7gUgPxBKGPHA5pK
MpwsKy5AcmNZSIVHjdjI2eLwVZlK44IHQT8lkq7XTDznrAIEWMTErZwbsT/hQj1L
noXLV6YwS5eIJqIDf4tyLZB5Av1ZNrLzQSplrXVkOgxItBU1E+DCwC2xFZUME5dZ
c5AB9aw2jXkSQLhFIrj4xAx9szGWzwABdkGATwuAeEokW4wY24oK8MMViAjxxcc8
E0CUAYETIKAjAifgWGMI2ehBgVtCeleGEkYmeUYGEQAAIfkECRQACwAsAAAAACgA
PAADBPtwyUlrdTbrvTH/oOSMpBeeV4muqcmu4zG+r6EcNBskSoLnJ4VQCAw9ErzE
oxgSCBSGwYDJMRgOhIGAupFGsVEG12JAmpHicaU3QDPe6fHjoSAQDlIBY6leDIUD
dnp9C04DdXh3eAaEUTeKdwJRagUCBGdnW3JHmJh8XHNmWAeLDwCfRQIBA6MMiQMG
AgBcBgGSUgeuWQMAvb1MAgWruXAMrJYAUkU2wVGXDGZeAIxMCgVfaJhOVkB/PWeX
nXM5AnScSKR2dmZzqCwFUAKjo1l4XpLULNuwWXYHAHgWCYD15AXBgV+wEACg7sDA
A45oaLFy5ZKvXvYMEPCGYvvOwQOYAHRCQufFuU7/wp2Zo2AKCgPtwN3xR8/LLpcg
kg1khaVlQyw8GRAwlC8nvp2HeM5UR8CYxp05L8ay8YcplmLGtmniwCtKLFhJR9oR
amnAuBAiH9wK9G1kAgaxBCg5u6HdSUzp1LlNCqJAgZGBaC41Q6DAUAUfajm5ZUdK
v7z08ATjmKGWAltecaVTqE5oFisB/EIpSiH06IcKpQTa3JSVagPCWm7wZsgOwJkg
3xaTrJFkFgvtFHDywmt1J2iB2pC0C9x0yItnsLx1K8xdoQDYCcQ9I5KwaynaalUS
RnpBpYH4YiXoTipgIlIFtLSUFKwSBb/NtGCnb2Zl51fHo8hnhRZbSfCEKkgZkkcw
TgBgyVdxeQNRMNNMoMBOpBxFUSx+ObgYPgS1BBRss/jxxzwAqsbLRfwh1VJyF5WI
2AkIAIAAAiiUKMGMICDRXQIn6IiCW4Qs4NYZTByppBkbRAAAIf4ZQm95J3MgSGFw
cHkgSG9saWRheXMgUGFnZQA7

--related_boundary--

--alternative_boundary--

You can import that into Sylpheed or Thunderbird (with the Import/Export tools extension) or Opera's built-in mail client. Then, in Opera for example, you can toggle "prefer plain text" to see the difference between the HTML and text version. Anyway, you'll see the HTML version makes use of the embedded pic in the sig.

Fluid width with equally spaced DIVs

See: http://jsfiddle.net/thirtydot/EDp8R/

  • This works in IE6+ and all modern browsers!
  • I've halved your requested dimensions just to make it easier to work with.
  • text-align: justify combined with .stretch is what's handling the positioning.
  • display:inline-block; *display:inline; zoom:1 fixes inline-block for IE6/7, see here.
  • font-size: 0; line-height: 0 fixes a minor issue in IE6.

_x000D_
_x000D_
#container {_x000D_
  border: 2px dashed #444;_x000D_
  height: 125px;_x000D_
  text-align: justify;_x000D_
  -ms-text-justify: distribute-all-lines;_x000D_
  text-justify: distribute-all-lines;_x000D_
  /* just for demo */_x000D_
  min-width: 612px;_x000D_
}_x000D_
_x000D_
.box1,_x000D_
.box2,_x000D_
.box3,_x000D_
.box4 {_x000D_
  width: 150px;_x000D_
  height: 125px;_x000D_
  vertical-align: top;_x000D_
  display: inline-block;_x000D_
  *display: inline;_x000D_
  zoom: 1_x000D_
}_x000D_
_x000D_
.stretch {_x000D_
  width: 100%;_x000D_
  display: inline-block;_x000D_
  font-size: 0;_x000D_
  line-height: 0_x000D_
}_x000D_
_x000D_
.box1,_x000D_
.box3 {_x000D_
  background: #ccc_x000D_
}_x000D_
_x000D_
.box2,_x000D_
.box4 {_x000D_
  background: #0ff_x000D_
}
_x000D_
<div id="container">_x000D_
  <div class="box1"></div>_x000D_
  <div class="box2"></div>_x000D_
  <div class="box3"></div>_x000D_
  <div class="box4"></div>_x000D_
  <span class="stretch"></span>_x000D_
</div>
_x000D_
_x000D_
_x000D_

The extra span (.stretch) can be replaced with :after.

This still works in all the same browsers as the above solution. :after doesn't work in IE6/7, but they're using distribute-all-lines anyway, so it doesn't matter.

See: http://jsfiddle.net/thirtydot/EDp8R/3/

There's a minor downside to :after: to make the last row work perfectly in Safari, you have to be careful with the whitespace in the HTML.

Specifically, this doesn't work:

<div id="container">
    ..
    <div class="box3"></div>
    <div class="box4"></div>
</div>

And this does:

<div id="container">
    ..
    <div class="box3"></div>
    <div class="box4"></div></div>

You can use this for any arbitrary number of child divs without adding a boxN class to each one by changing

.box1, .box2, .box3, .box4 { ...

to

#container > div { ...

This selects any div that is the first child of the #container div, and no others below it. To generalize the background colors, you can use the CSS3 nth-order selector, although it's only supported in IE9+ and other modern browsers:

.box1, .box3 { ...

becomes:

#container > div:nth-child(odd) { ...

See here for a jsfiddle example.

Hibernate Union alternatives

I have a solution for one critical scenario (for which I struggled a lot )with union in HQL .

e.g. Instead of not working :-

select i , j from A a  , (select i , j from B union select i , j from C) d where a.i = d.i 

OR

select i , j from A a  JOIN (select i , j from B union select i , j from C) d on a.i = d.i 

YOU could do in Hibernate HQL ->

Query q1 =session.createQuery(select i , j from A a JOIN B b on a.i = b.i)
List l1 = q1.list();

Query q2 = session.createQuery(select i , j from A a JOIN C b on a.i = b.i)
List l2 = q2.list();

then u can add both list ->

l1.addAll(l2);

How do I use LINQ Contains(string[]) instead of Contains(string)

Dim stringArray() = {"Pink Floyd", "AC/DC"}
Dim inSQL = From alb In albums Where stringArray.Contains(alb.Field(Of String)("Artiste").ToString())
Select New With
  {
     .Album = alb.Field(Of String)("Album"),
     .Annee = StrReverse(alb.Field(Of Integer)("Annee").ToString()) 
  }

What is the difference between typeof and instanceof and when should one be used vs. the other?

Coming from a strict OO upbringing I'd go for

callback instanceof Function

Strings are prone to either my awful spelling or other typos. Plus I feel it reads better.

Filter Extensions in HTML form upload

Another solution with a few lines

function checkFile(i){
  i = i.substr(i.length - 4, i.length).toLowerCase();
  i = i.replace('.','');
  switch(i){
    case 'jpg':
    case 'jpeg':
    case 'png':
    case 'gif':
      // do OK stuff
      break;
    default:
      // do error stuff
      break;
  }
}

How to make an android app to always run in background?

You have to start a service in your Application class to run it always. If you do that, your service will be always running. Even though user terminates your app from task manager or force stop your app, it will start running again.

Create a service:

public class YourService extends Service {

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        // do your jobs here
        return super.onStartCommand(intent, flags, startId);
    }
}

Create an Application class and start your service:

public class App extends Application {

    @Override
    public void onCreate() {
        super.onCreate();

        startService(new Intent(this, YourService.class));
    }
}

Add "name" attribute into the "application" tag of your AndroidManifest.xml

android:name=".App"

Also, don't forget to add your service in the "application" tag of your AndroidManifest.xml

<service android:name=".YourService"/>

And also this permission request in the "manifest" tag (if API level 28 or higher):

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

UPDATE

After Android Oreo, Google introduced some background limitations. Therefore, this solution above won't work probably. When a user kills your app from task manager, Android System will kill your service as well. If you want to run a service which is always alive in the background. You have to run a foreground service with showing an ongoing notification. So, edit your service like below.

public class YourService extends Service {

    private static final int NOTIF_ID = 1;
    private static final String NOTIF_CHANNEL_ID = "Channel_Id";

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId){

        // do your jobs here

        startForeground();
        
        return super.onStartCommand(intent, flags, startId);
    }

    private void startForeground() {
        Intent notificationIntent = new Intent(this, MainActivity.class);

        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,
                notificationIntent, 0);

        startForeground(NOTIF_ID, new NotificationCompat.Builder(this, 
                NOTIF_CHANNEL_ID) // don't forget create a notification channel first
                .setOngoing(true)
                .setSmallIcon(R.drawable.ic_notification)
                .setContentTitle(getString(R.string.app_name))
                .setContentText("Service is running background")
                .setContentIntent(pendingIntent)
                .build());         
    }
}

EDIT: RESTRICTED OEMS

Unfortunately, some OEMs (Xiaomi, OnePlus, Samsung, Huawei etc.) restrict background operations due to provide longer battery life. There is no proper solution for these OEMs. Users need to allow some special permissions that are specific for OEMs or they need to add your app into whitelisted app list by device settings. You can find more detail information from https://dontkillmyapp.com/.

If background operations are an obligation for you, you need to explain it to your users why your feature is not working and how they can enable your feature by allowing those permissions. I suggest you to use AutoStarter library (https://github.com/judemanutd/AutoStarter) in order to redirect your users regarding permissions page easily from your app.

By the way, if you need to run some periodic work instead of having continuous background job. You better take a look WorkManager (https://developer.android.com/topic/libraries/architecture/workmanager)

How to create json by JavaScript for loop?

var sels = //Here is your array of SELECTs
var json = { };

for(var i = 0, l = sels.length; i < l; i++) {
  json[sels[i].id] = sels[i].value;
}

How to remove an element slowly with jQuery?

$('#ur_id').slideUp("slow", function() { $('#ur_id').remove();});

Sending the bearer token with axios

If you want to some data after passing token in header so that try this code

const api = 'your api'; 
const token = JSON.parse(sessionStorage.getItem('data'));
const token = user.data.id; /*take only token and save in token variable*/
axios.get(api , { headers: {"Authorization" : `Bearer ${token}`} })
.then(res => {
console.log(res.data);
.catch((error) => {
  console.log(error)
});

HTML forms - input type submit problem with action=URL when URL contains index.aspx

Put the query arguments in hidden input fields:

<form action="http://spufalcons.com/index.aspx">
    <input type="hidden" name="tab" value="gymnastics" />
    <input type="hidden" name="path" value="gym" />
    <input type="submit" value="SPU Gymnastics"/>
</form>

git clone through ssh

You need to run the clone command on what you are calling the server. But I bet you are not running an ssh server on your local client so that won't work anyway. Suggest you follow this approach (check the manual 'cause I'm doing this from memory)

  1. Log into the server machine.
  2. Create a bare repo using git init --bare
  3. On the client machine you can push your repo to the server. git remote add origin ssh://user@server:/GitRepos/myproject.git followed by git push origin master

Go back button in a page

onclick="history.go(-1)" Simply

How to check if the user can go back in browser history or not

I was trying to find a solution and this is the best i could get (but works great and it's the easiest solution i've found even here).

In my case, i wanted to go back on history with an back button, but if the first page the user opened was an subpage of my app, it would go back to the main page.

The solution was, as soon the app is loaded, i just did an replace on the history state:

history.replaceState( {root: true}, '', window.location.pathname + window.location.hash)

This way, i just need to check history.state.root before go back. If true, i make an history replace instead:

if(history.state && history.state.root)
    history.replaceState( {root: true}, '', '/')
else
    history.back() 

How does one make random number between range for arc4random_uniform()?

The answer is just 1 line code:

let randomNumber = arc4random_uniform(8999) + 1000 //for 4 digit random number
let randomNumber = arc4random_uniform(899999999) + 100000000 //for 9 digit random number
let randomNumber = arc4random_uniform(89) + 10    //for 2 digit random number
let randomNumber = arc4random_uniform(899) + 100  //for 3 digit random number

The alternate solution is:

    func generateRandomNumber(numDigits: Int) -> Int{
    var place = 1
    var finalNumber = 0;
    var finanum = 0;
    for var i in 0 ..< numDigits {
        place *= 10
        let randomNumber = arc4random_uniform(10)         
        finalNumber += Int(randomNumber) * place
        finanum = finalNumber / 10
           i += 1
    }
    return finanum
}

Although the drawback is that number cannot start from 0.

java: use StringBuilder to insert at the beginning

This thread is quite old, but you could also think about a recursive solution passing the StringBuilder to fill. This allows to prevent any reverse processing etc. Just need to design your iteration with a recursion and carefully decide for an exit condition.

public class Test {

    public static void main(String[] args) {
        StringBuilder sb = new StringBuilder();
        doRecursive(sb, 100, 0);
        System.out.println(sb.toString());
    }

    public static void doRecursive(StringBuilder sb, int limit, int index) {
        if (index < limit) {
            doRecursive(sb, limit, index + 1);
            sb.append(Integer.toString(index));
        }
    }
}

XMLHttpRequest blocked by CORS Policy

I believe sideshowbarker 's answer here has all the info you need to fix this. If your problem is just No 'Access-Control-Allow-Origin' header is present on the response you're getting, you can set up a CORS proxy to get around this. Way more info on it in the linked answer

Update elements in a JSONObject

Use the put method: https://developer.android.com/reference/org/json/JSONObject.html

JSONObject person =  jsonArray.getJSONObject(0).getJSONObject("person");
person.put("name", "Sammie");

Building a complete online payment gateway like Paypal

What you're talking about is becoming a payment service provider. I have been there and done that. It was a lot easier about 10 years ago than it is now, but if you have a phenomenal amount of time, money and patience available, it is still possible.

You will need to contact an acquiring bank. You didnt say what region of the world you are in, but by this I dont mean a local bank branch. Each major bank will generally have a separate card acquiring arm. So here in the UK we have (eg) Natwest bank, which uses Streamline (or Worldpay) as its acquiring arm. In total even though we have scores of major banks, they all end up using one of five or so card acquirers.

Happily, all UK card acquirers use a standard protocol for communication of authorisation requests, and end of day settlement. You will find minor quirks where some acquiring banks support some features and have slightly different syntax, but the differences are fairly minor. The UK standards are published by the Association for Payment Clearing Services (APACS) (which is now known as the UKPA). The standards are still commonly referred to as APACS 30 (authorization) and APACS 29 (settlement), but are now formally known as APACS 70 (books 1 through 7).

Although the APACS standard is widely supported across the UK (Amex and Discover accept messages in this format too) it is not used in other countries - each country has it's own - for example: Carte Bancaire in France, CartaSi in Italy, Sistema 4B in Spain, Dankort in Denmark etc. An effort is under way to unify the protocols across Europe - see EPAS.org

Communicating with the acquiring bank can be done a number of ways. Again though, it will depend on your region. In the UK (and most of Europe) we have one communications gateway that provides connectivity to all the major acquirers, they are called TNS and there are dozens of ways of communicating through them to the acquiring bank, from dialup 9600 baud modems, ISDN, HTTPS, VPN or dedicated line. Ultimately the authorisation request will be converted to X25 protocol, which is the protocol used by these acquiring banks when communicating with each other.

In summary then: it all depends on your region.

  • Contact a major bank and try to get through to their card acquiring arm.
  • Explain that you're setting up as a payment service provider, and request details on comms format for authorization requests and end of day settlement files
  • Set up a test merchant account and develop auth/settlement software and go through the accreditation process. Most acquirers help you through this process for free, but when you want to register as an accredited PSP some will request a fee.
  • you will need to comply with some regulations too, for example you may need to register as a payment institution

Once you are registered and accredited you'll then be able to accept customers and set up merchant accounts on behalf of the bank/s you're accredited against (bearing in mind that each acquirer will generally support multiple banks). Rinse and repeat with other acquirers as you see necessary.

Beyond that you have lots of other issues, mainly dealing with PCI-DSS. Thats a whole other topic and there are already some q&a's on this site regarding that. Like I say, its a phenomenal undertaking - most likely a multi-year project even for a reasonably sized team, but its certainly possible.

How do I get milliseconds from epoch (1970-01-01) in Java?

java.time

Using the java.time framework built into Java 8 and later.

import java.time.Instant;

Instant.now().toEpochMilli(); //Long = 1450879900184
Instant.now().getEpochSecond(); //Long = 1450879900

This works in UTC because Instant.now() is really call to Clock.systemUTC().instant()

https://docs.oracle.com/javase/8/docs/api/java/time/Instant.html

linux shell script: split string, put them in an array then loop through them

Here is an example code that you may use:

$ STR="String;1;2;3"
$ for EACH in `echo "$STR" | grep -o -e "[^;]*"`; do
    echo "Found: \"$EACH\"";
done

grep -o -e "[^;]*" will select anything that is not ';', therefore spliting the string by ';'.

Hope that help.

MySQL Insert query doesn't work with WHERE clause

You can't use INSERT and WHERE together. You can use UPDATE clause for add value to particular column in particular field like below code;

UPDATE Users
SET weight='160',desiredWeight ='145'  
WHERE id =1

Pandas rename column by position?

You can do this:

df.rename(columns={ df.columns[1]: "whatever" })

What happens to C# Dictionary<int, int> lookup if the key does not exist?

You should check for Dictionary.ContainsKey(int key) before trying to pull out the value.

Dictionary<int, int> myDictionary = new Dictionary<int, int>();
myDictionary.Add(2,4);
myDictionary.Add(3,5);

int keyToFind = 7;
if(myDictionary.ContainsKey(keyToFind))
{
    myValueLookup = myDictionay[keyToFind];
    // do work...
}
else
{
    // the key doesn't exist.
}

how to set radio option checked onload with jQuery

I liked the answer by @Amc. I found the expression could be condensed further to not use a filter() call (@chaiko apparently also noticed this). Also, prop() is the way to go vs attr() for jQuery v1.6+, see the jQuery documentation for prop() for the official best practices on the subject.

Consider the same input tags from @Paolo Bergantino's answer.

<input type='radio' name='gender' value='Male'>
<input type='radio' name='gender' value='Female'>

The updated one-liner might read something like:

$('input:radio[name="gender"][value="Male"]').prop('checked', true);

How to disable a ts rule for a specific line?

You can use /* tslint:disable-next-line */ to locally disable tslint. However, as this is a compiler error disabling tslint might not help.

You can always temporarily cast $ to any:

delete ($ as any).summernote.options.keyMap.pc.TAB

which will allow you to access whatever properties you want.


Edit: As of Typescript 2.6, you can now bypass a compiler error/warning for a specific line:

if (false) {
    // @ts-ignore: Unreachable code error
    console.log("hello");
}

Note that the official docs "recommend you use [this] very sparingly". It is almost always preferable to cast to any instead as that better expresses intent.

T-SQL Subquery Max(Date) and Joins

Please try next code example:

select t1.*, t2.partprice, t2.partdate 
from myparts t1
join myprices t2 
on t1.partid = t2.partid
where partdate = 
(select max(partdate) from myprices t3 
where t3.partid = t2.partid group by partid)

Objective-C Static Class Level variables

As of Xcode 8, you can define class properties in Obj-C. This has been added to interoperate with Swift's static properties.

Objective-C now supports class properties, which interoperate with Swift type properties. They are declared as: @property (class) NSString *someStringProperty;. They are never synthesized. (23891898)

Here is an example

@interface YourClass : NSObject

@property (class, nonatomic, assign) NSInteger currentId;

@end

@implementation YourClass

static NSInteger _currentId = 0;

+ (NSInteger)currentId {
    return _currentId;
}

+ (void)setCurrentId:(NSInteger)newValue {
    _currentId = newValue;
}

@end

Then you can access it like this:

YourClass.currentId = 1;
val = YourClass.currentId;

Here is a very interesting explanatory post I used as a reference to edit this old answer.


2011 Answer: (don't use this, it's terrible)

If you really really don't want to declare a global variable, there another option, maybe not very orthodox :-), but works... You can declare a "get&set" method like this, with an static variable inside:

+ (NSString*)testHolder:(NSString*)_test {
    static NSString *test;

    if(_test != nil) {
        if(test != nil)
            [test release];
        test = [_test retain];
    }

    // if(test == nil)
    //     test = @"Initialize the var here if you need to";

    return test;
}

So, if you need to get the value, just call:

NSString *testVal = [MyClass testHolder:nil]

And then, when you want to set it:

[MyClass testHolder:testVal]

In the case you want to be able to set this pseudo-static-var to nil, you can declare testHolder as this:

+ (NSString*)testHolderSet:(BOOL)shouldSet newValue:(NSString*)_test {
    static NSString *test;

    if(shouldSet) {
        if(test != nil)
            [test release];
        test = [_test retain];
    }

    return test;
}

And two handy methods:

+ (NSString*)test {
    return [MyClass testHolderSet:NO newValue:nil];
}

+ (void)setTest:(NSString*)_test {
    [MyClass testHolderSet:YES newValue:_test];
}

Hope it helps! Good luck.

How can I get browser to prompt to save password?

I had similar problem, login was done with ajax, but browsers (firefox, chrome, safari and IE 7-10) would not offer to save password if form (#loginForm) is submitted with ajax.

As a SOLUTION I have added hidden submit input (#loginFormHiddenSubmit) to form that was submitted by ajax and after ajax call would return success I would trigger a click to hidden submit input. The page any way needed to refreshed. The click can be triggered with:

jQuery('#loginFormHiddenSubmit').click();

Reason why I have added hidden submit button is because:

jQuery('#loginForm').submit();

would not offer to save password in IE (although it has worked in other browsers).

How to break out from foreach loop in javascript

Use a for loop instead of .forEach()

var myObj = [{"a": "1","b": null},{"a": "2","b": 5}]
var result = false

for(var call of myObj) {
    console.log(call)
    
    var a = call['a'], b = call['b']
     
    if(a == null || b == null) {
        result = false
        break
    }
}

Links not going back a directory?

You need to give a relative file path of <a href="../index.html">Home</a>

Alternately you can specify a link from the root of your site with <a href="/pages/en/index.html">Home</a>

.. and . have special meanings in file paths, .. means up one directory and . means current directory.

so <a href="index.html">Home</a> is the same as <a href="./index.html">Home</a>

Xcode 5 and iOS 7: Architecture and Valid architectures

When you set 64-bit the resulting binary is a "Fat" binary, which contains all three Mach-O images bundled with a thin fat header. You can see that using otool or jtool. You can check out some fat binaries included as part of the iOS 7.0 SDK, for example the AVFoundation Framework, like so:

% cd  /Developer/Platforms/iPhoneOS.platform/DeviceSupport/7.0\ \(11A465\)/Symbols/System/Library/Frameworks/AVFoundation.framework/

%otool -V -f AVFoundation                                                                     9:36
Fat headers
fat_magic FAT_MAGIC
nfat_arch 3
architecture arm64     # The 64-bit version (A7)
    cputype CPU_TYPE_ARM64
    cpusubtype CPU_SUBTYPE_ARM64_ALL
    capabilities 0x0
    offset 16384
    size 2329888
    align 2^14 (16384)
architecture armv7        # A5X - packaged after the arm64version
    cputype CPU_TYPE_ARM
    cpusubtype CPU_SUBTYPE_ARM_V7
    capabilities 0x0
    offset 2359296
    size 2046336
    align 2^14 (16384)
architecture armv7s       # A6 - packaged after the armv7 version
    cputype CPU_TYPE_ARM
    cpusubtype CPU_SUBTYPE_ARM_V7S
    capabilities 0x0
    offset 4407296
    size 2046176
    align 2^14 (16384)

As for the binary itself, it uses the ARM64 bit instruction set, which is (mostly compatible with 32-bit, but) a totally different instruction set. This is especially important for graphics program (using NEON instructions and registers). Likewise, the CPU has more registers, which makes quite an impact on program speed. There's an interesting discussion in http://blogs.barrons.com/techtraderdaily/2013/09/19/apple-the-64-bit-question/?mod=yahoobarrons on whether or not this makes a difference; benchmarking tests have so far clearly indicated that it does.

Using otool -tV will dump the assembly (if you have XCode 5 and later), and then you can see the instruction set differences for yourself. Most (but not all) developers will remain agnostic to the changes, as for the most part they do not directly affect Obj-C (CG* APIs notwithstanding), and have to do more with low level pointer handling. The compiler will work its magic and optimizations.

How to get a table cell value using jQuery?

$('#mytable tr').each(function() {
  // need this to skip the first row
  if ($(this).find("td:first").length > 0) {
    var cutomerId = $(this).find("td:first").html();
  }
});

Adding CSRFToken to Ajax request

If you are working in node.js with lusca try also this:

$.ajax({
url: "http://test.com",
type:"post"
headers: {'X-CSRF-Token': $('meta[name="csrf-token"]').attr('content')}
})

How to inject a Map using the @Value Spring Annotation?

You can inject values into a Map from the properties file using the @Value annotation like this.

The property in the properties file.

propertyname={key1:'value1',key2:'value2',....}

In your code.

@Value("#{${propertyname}}")  private Map<String,String> propertyname;

Note the hashtag as part of the annotation.

Populating a data frame in R in a loop

I had a case in where I was needing to use a data frame within a for loop function. In this case, it was the "efficient", however, keep in mind that the database was small and the iterations in the loop were very simple. But maybe the code could be useful for some one with similar conditions.

The for loop purpose was to use the raster extract function along five locations (i.e. 5 Tokio, New York, Sau Paulo, Seul & Mexico city) and each location had their respective raster grids. I had a spatial point database with more than 1000 observations allocated within the 5 different locations and I was needing to extract information from 10 different raster grids (two grids per location). Also, for the subsequent analysis, I was not only needing the raster values but also the unique ID for each observations.

After preparing the spatial data, which included the following tasks:

  1. Import points shapefile with the readOGR function (rgdap package)
  2. Import raster files with the raster function (raster package)
  3. Stack grids from the same location into one file, with the function stack (raster package)

Here the for loop code with the use of a data frame:

1. Add stacked rasters per location into a list

raslist <- list(LOC1,LOC2,LOC3,LOC4,LOC5)

2. Create an empty dataframe, this will be the output file

TB <- data.frame(VAR1=double(),VAR2=double(),ID=character())

3. Set up for loop function

L1 <- seq(1,5,1) # the location ID is a numeric variable with values from 1 to 5 

for (i in 1:length(L1)) {
  dat=subset(points,LOCATION==i) # select corresponding points for location [i] 
  t=data.frame(extract(raslist[[i]],dat),dat$ID) # run extract function with points & raster stack for location [i]
  names(t)=c("VAR1","VAR2","ID") 
  TB=rbind(TB,t)
}

Use a.any() or a.all()

You comment:

valeur is a vector equal to [ 0. 1. 2. 3.] I am interested in each single term. For the part below 0.6, then return "this works"....

If you are interested in each term, then write the code so it deals with each. For example.

for b in valeur<=0.6:
    if b:
        print ("this works")
    else:   
        print ("valeur is too high")

This will write 2 lines.

The error is produced by numpy code when you try to use it a context that expects a single, scalar, value. if b:... can only do one thing. It does not, by itself, iterate through the elements of b doing a different thing for each.

You could also cast that iteration as list comprehension, e.g.

['yes' if b else 'no' for b in np.array([True, False, True])]

password-check directive in angularjs

Creating a separate directive for this is not needed. There is already a build in Angular UI password validation tool. With this you could do:

<input name="password" required ng-model="password">
<input name="confirm_password"
       ui-validate=" '$value==password' "
       ui-validate-watch=" 'password' ">

 Passwords match? {{!!form.confirm_password.$error.validator}}

How to convert java.util.Date to java.sql.Date?

Format your java.util.Date first. Then use the formatted date to get the date in java.sql.Date

java.util.Date utilDate = "Your date"
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
final String stringDate= dateFormat.format(utilDate);
final java.sql.Date sqlDate=  java.sql.Date.valueOf(stringDate);

How do I sort a Set to a List in Java?

List myList = new ArrayList(collection);
Collections.sort(myList);

… should do the trick however. Add flavour with Generics where applicable.

RequestDispatcher.forward() vs HttpServletResponse.sendRedirect()

Technically redirect should be used either if we need to transfer control to different domain or to achieve separation of task.

For example in the payment application we do the PaymentProcess first and then redirect to displayPaymentInfo. If the client refreshes the browser only the displayPaymentInfo will be done again and PaymentProcess will not be repeated. But if we use forward in this scenario, both PaymentProcess and displayPaymentInfo will be re-executed sequentially, which may result in incosistent data.

For other scenarios, forward is efficient to use since as it is faster than sendRedirect

Installing R with Homebrew

This is what actually worked for me on OSX Yosemite.

brew install cask
brew install Caskroom/cask/xquartz
brew install r

Creating a byte array from a stream

i was able to make it work on a single line:

byte [] byteArr= ((MemoryStream)localStream).ToArray();

as clarified by johnnyRose, Above code will only work for MemoryStream

Get key from a HashMap using the value

We can get KEY from VALUE. Below is a sample code_

 public class Main {
  public static void main(String[] args) {
    Map map = new HashMap();
    map.put("key_1","one");
    map.put("key_2","two");
    map.put("key_3","three");
    map.put("key_4","four");
System.out.println(getKeyFromValue(map,"four")); } public static Object getKeyFromValue(Map hm, Object value) { for (Object o : hm.keySet()) { if (hm.get(o).equals(value)) { return o; } } return null; } }

I hope this will help everyone.

Change the background color of CardView programmatically

Use the property card_view:cardBackgroundColor:

<android.support.v7.widget.CardView xmlns:card_view="http://schemas.android.com/apk/res-auto"
    android:id="@+id/card_view"
    android:layout_width="fill_parent"
    android:layout_height="150dp"
    android:layout_gravity="center"
    card_view:cardCornerRadius="4dp"
    android:layout_margin="10dp"
    card_view:cardBackgroundColor="#fff"
    >

IPC performance: Named Pipe vs Socket

Named pipes and sockets are not functionally equivalent; sockets provide more features (they are bidirectional, for a start).

We cannot tell you which will perform better, but I strongly suspect it doesn't matter.

Unix domain sockets will do pretty much what tcp sockets will, but only on the local machine and with (perhaps a bit) lower overhead.

If a Unix socket isn't fast enough and you're transferring a lot of data, consider using shared memory between your client and server (which is a LOT more complicated to set up).

Unix and NT both have "Named pipes" but they are totally different in feature set.

What is the optimal algorithm for the game 2048?

This is not a direct answer to OP's question, this is more of the stuffs (experiments) I tried so far to solve the same problem and obtained some results and have some observations that I want to share, I am curious if we can have some further insights from this.

I just tried my minimax implementation with alpha-beta pruning with search-tree depth cutoff at 3 and 5. I was trying to solve the same problem for a 4x4 grid as a project assignment for the edX course ColumbiaX: CSMM.101x Artificial Intelligence (AI).

I applied convex combination (tried different heuristic weights) of couple of heuristic evaluation functions, mainly from intuition and from the ones discussed above:

  1. Monotonicity
  2. Free Space Available

In my case, the computer player is completely random, but still i assumed adversarial settings and implemented the AI player agent as the max player.

I have 4x4 grid for playing the game.

Observation:

If I assign too much weights to the first heuristic function or the second heuristic function, both the cases the scores the AI player gets are low. I played with many possible weight assignments to the heuristic functions and take a convex combination, but very rarely the AI player is able to score 2048. Most of the times it either stops at 1024 or 512.

I also tried the corner heuristic, but for some reason it makes the results worse, any intuition why?

Also, I tried to increase the search depth cut-off from 3 to 5 (I can't increase it more since searching that space exceeds allowed time even with pruning) and added one more heuristic that looks at the values of adjacent tiles and gives more points if they are merge-able, but still I am not able to get 2048.

I think it will be better to use Expectimax instead of minimax, but still I want to solve this problem with minimax only and obtain high scores such as 2048 or 4096. I am not sure whether I am missing anything.

Below animation shows the last few steps of the game played by the AI agent with the computer player:

enter image description here

Any insights will be really very helpful, thanks in advance. (This is the link of my blog post for the article: https://sandipanweb.wordpress.com/2017/03/06/using-minimax-with-alpha-beta-pruning-and-heuristic-evaluation-to-solve-2048-game-with-computer/ and the youtube video: https://www.youtube.com/watch?v=VnVFilfZ0r4)

The following animation shows the last few steps of the game played where the AI player agent could get 2048 scores, this time adding the absolute value heuristic too:

enter image description here

The following figures show the game tree explored by the player AI agent assuming the computer as adversary for just a single step:

enter image description here enter image description here enter image description here enter image description here enter image description here enter image description here

How to Alter a table for Identity Specification is identity SQL Server

You cannot "convert" an existing column into an IDENTITY column - you will have to create a new column as INT IDENTITY:

ALTER TABLE ProductInProduct 
ADD NewId INT IDENTITY (1, 1);

Update:

OK, so there is a way of converting an existing column to IDENTITY. If you absolutely need this - check out this response by Martin Smith with all the gory details.

$.ajax - dataType

jQuery Ajax loader is not working well when you call two APIs simultaneously. To resolve this problem you have to call the APIs one by one using the isAsync property in Ajax setting. You also need to make sure that there should not be any error in the setting. Otherwise, the loader will not work. E.g undefined content-type, data-type for POST/PUT/DELETE/GET call.

Is an anchor tag without the href attribute safe?

If you have to use href for backwards compability, you can also use

<a href="javascript:void(0)">link</a>

instead of # ,if you don't want to use the attribute

How do I force Robocopy to overwrite files?

This is really weird, why nobody is mentioning the /IM switch ?! I've been using it for a long time in backup jobs. But I tried googling just now and I couldn't land on a single web page that says anything about it even on MS website !!! Also found so many user posts complaining about the same issue!!

Anyway.. to use Robocopy to overwrite EVERYTHING what ever size or time in source or distination you must include these three switches in your command (/IS /IT /IM)

/IS :: Include Same files. (Includes same size files)
/IT :: Include Tweaked files. (Includes same files with different Attributes)
/IM :: Include Modified files (Includes same files with different times).

This is the exact command I use to transfer few TeraBytes of mostly 1GB+ files (ISOs - Disk Images - 4K Videos):

robocopy B:\Source D:\Destination /E /J /COPYALL /MT:1 /DCOPY:DATE /IS /IT /IM /X /V /NP /LOG:A:\ROBOCOPY.LOG

I did a small test for you .. and here is the result:

               Total    Copied   Skipped  Mismatch    FAILED    Extras
    Dirs :      1028      1028         0         0         0       169
   Files :      8053      8053         0         0         0         1
   Bytes : 649.666 g 649.666 g         0         0         0   1.707 g
   Times :   2:46:53   0:41:43                       0:00:00   0:41:44


   Speed :           278653398 Bytes/sec.
   Speed :           15944.675 MegaBytes/min.
   Ended : Friday, August 21, 2020 7:34:33 AM

Dest, Disk: WD Gold 6TB (Compare the write speed with my result)

Even with those "Extras", that's for reporting only because of the "/X" switch. As you can see nothing was Skipped and Total number and size of all files are equal to the Copied. Sometimes It will show small number of skipped files when I abuse it and cancel it multiple times during operation but even with that the values in the first 2 columns are always Equal. I also confirmed that once before by running a PowerShell script that scans all files in destination and generate a report of all time-stamps.

Some performance tips from my history with it and so many tests & troubles!:

. Despite of what most users online advise to use maximum threads "/MT:128" like it's a general trick to get the best performance ... PLEASE DON'T USE "/MT:128" WITH VERY LARGE FILES ... that's a big mistake and it will decrease your drive performance dramatically after several runs .. it will create very high fragmentation or even cause the files system to fail in some cases and you end up spending valuable time trying to recover a RAW partition and all that nonsense. And above all that, It will perform 4-6 times slower!!

For very large files:

  1. Use Only "One" thread "/MT:1" | Impact: BIG
  2. Must use "/J" to disable buffering. | Impact: High
  3. Use "/NP" with "/LOG:file" and Don't output to the console by "/TEE" | Impact: Medium.
  4. Put the "/LOG:file" on a separate drive from the source or destination | Impact: Low.

For regular big files:

  1. Use multi threads, I would not exceed "/MT:4" | Impact: BIG
  2. IF destination disk has low Cache specs use "/J" to disable buffering | Impact: High
  3. & 4 same as above.

For thousands of tiny files:

  1. Go nuts :) with Multi threads, at first I would start with 16 and multibly by 2 while monitoring the disk performance. Once it starts dropping I'll fall back to the prevouse value and stik with it | Impact: BIG
  2. Don't use "/J" | Impact: High
  3. Use "/NP" with "/LOG:file" and Don't output to the console by "/TEE" | Impact: HIGH.
  4. Put the "/LOG:file" on a separate drive from the source or destination | Impact: HIGH.

Constraint Layout Vertical Align Center

I also had a requirement something similar to it. I wanted to have a container in the center of the screen and inside the container there are many views. Following is the xml layout code. Here i'm using nested constraint layout to create container in the center of the screen.

    <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/gradient_background"
tools:context=".activities.AppInfoActivity">

<ImageView
    android:id="@+id/ivClose"
    android:layout_width="30dp"
    android:layout_height="30dp"
    android:layout_marginStart="20dp"
    android:layout_marginTop="20dp"
    android:src="@drawable/ic_round_close_24"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

<androidx.constraintlayout.widget.ConstraintLayout
    android:layout_width="300dp"
    android:layout_height="300dp"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintVertical_bias="0.5">

    <ImageView
        android:id="@+id/ivAppIcon"
        android:layout_width="100dp"
        android:layout_height="100dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:srcCompat="@drawable/dead" />

    <TextView
        android:id="@+id/tvAppName"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Birds Shooter Plane"
        android:textAlignment="center"
        android:textSize="30sp"
        android:textStyle="bold"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/ivAppIcon" />

    <TextView
        android:id="@+id/tvAppVersion"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Version : 1.0"
        android:textAlignment="center"
        android:textSize="12sp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/tvAppName" />

    <TextView
        android:id="@+id/tvDevelopedBy"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="25dp"
        android:text="Developed by"
        android:textAlignment="center"
        android:textSize="12sp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/tvAppVersion" />

    <TextView
        android:id="@+id/tvDevelopedName"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="5dp"
        android:text="K Pradeep Kumar Reddy"
        android:textAlignment="center"
        android:textSize="14sp"
        android:textStyle="bold"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/tvDevelopedBy" />

    <TextView
        android:id="@+id/tvContact"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="5dp"
        android:text="Contact : [email protected]"
        android:textAlignment="center"
        android:textSize="12sp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/tvDevelopedName" />

    <TextView
        android:id="@+id/tvCheckForUpdate"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="25dp"
        android:text="@string/check_for_update"
        android:textAlignment="center"
        android:textSize="14sp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/tvContact" />
</androidx.constraintlayout.widget.ConstraintLayout>

</androidx.constraintlayout.widget.ConstraintLayout>

Here is the screenshot of the layout enter image description here

Other solution is to remove the nested constraint layout and add constraint_vertical_bias = 0.5 attribute to the top element in the center of layout. I think this is called as chaining of views.

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/gradient_background"
tools:context=".activities.AppInfoActivity">

<ImageView
android:id="@+id/ivClose"
android:layout_width="30dp"
android:layout_height="30dp"
android:layout_marginStart="20dp"
android:layout_marginTop="20dp"
android:src="@drawable/ic_round_close_24"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />

<ImageView
android:id="@+id/ivAppIcon"
android:layout_width="100dp"
android:layout_height="100dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.5"
app:srcCompat="@drawable/dead" />

<TextView
android:id="@+id/tvAppName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/app_display_name"
android:textAlignment="center"
android:textSize="30sp"
android:textStyle="bold"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/ivAppIcon" />

<TextView
android:id="@+id/tvAppVersion"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/version"
android:textAlignment="center"
android:textSize="12sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/tvAppName" />

<TextView
android:id="@+id/tvDevelopedBy"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="25dp"
android:text="@string/developed_by"
android:textAlignment="center"
android:textSize="12sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/tvAppVersion" />

<TextView
android:id="@+id/tvDevelopedName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:text="@string/developer_name"
android:textAlignment="center"
android:textSize="14sp"
android:textStyle="bold"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/tvDevelopedBy" />

<TextView
android:id="@+id/tvContact"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:text="@string/developer_email"
android:textAlignment="center"
android:textSize="12sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/tvDevelopedName" />
<TextView
android:id="@+id/tvCheckForUpdate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="25dp"
android:text="@string/check_for_update"
android:textAlignment="center"
android:textSize="14sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/tvContact" />
</androidx.constraintlayout.widget.ConstraintLayout>

Here is the screenshot of the layout enter image description here

Include CSS and Javascript in my django template

Read this https://docs.djangoproject.com/en/dev/howto/static-files/:

For local development, if you are using runserver or adding staticfiles_urlpatterns to your URLconf, you’re done with the setup – your static files will automatically be served at the default (for newly created projects) STATIC_URL of /static/.

And try:

~/tmp$ django-admin.py startproject myprj
~/tmp$ cd myprj/
~/tmp/myprj$ chmod a+x manage.py
~/tmp/myprj$ ./manage.py startapp myapp

Then add 'myapp' to INSTALLED_APPS (myprj/settings.py).

~/tmp/myprj$ cd myapp/
~/tmp/myprj/myapp$ mkdir static
~/tmp/myprj/myapp$ echo 'alert("hello!");' > static/hello.js
~/tmp/myprj/myapp$ mkdir templates
~/tmp/myprj/myapp$ echo '<script src="{{ STATIC_URL }}hello.js"></script>' > templates/hello.html

Edit myprj/urls.py:

from django.conf.urls import patterns, include, url
from django.views.generic import TemplateView

class HelloView(TemplateView):
    template_name = "hello.html"

urlpatterns = patterns('',
    url(r'^$', HelloView.as_view(), name='hello'),
)

And run it:

~/tmp/myprj/myapp$ cd ..
~/tmp/myprj$ ./manage.py runserver

It works!

Why use deflate instead of gzip for text files served by Apache?

GZip is simply deflate plus a checksum and header/footer. Deflate is faster, though, as I learned the hard way.

gzip vs deflate graph

How to list the contents of a package using YUM?

rpm -ql [packageName]

Example

# rpm -ql php-fpm

/etc/php-fpm.conf
/etc/php-fpm.d
/etc/php-fpm.d/www.conf
/etc/sysconfig/php-fpm
...
/run/php-fpm
/usr/lib/systemd/system/php-fpm.service
/usr/sbin/php-fpm
/usr/share/doc/php-fpm-5.6.0
/usr/share/man/man8/php-fpm.8.gz
...
/var/lib/php/sessions
/var/log/php-fpm

No need to install yum-utils, or to know the location of the rpm file.

Run reg command in cmd (bat file)?

In command line it's better to use REG tool rather than REGEDIT:

REG IMPORT yourfile.reg

REG is designed for console mode, while REGEDIT is for graphical mode. This is why running regedit.exe /S yourfile.reg is a bad idea, since you will not be notified if the there's an error, whereas REG Tool will prompt:

>  REG IMPORT missing_file.reg

ERROR: Error opening the file. There may be a disk or file system error.

>  %windir%\System32\reg.exe /?

REG Operation [Parameter List]

  Operation  [ QUERY   | ADD    | DELETE  | COPY    |
               SAVE    | LOAD   | UNLOAD  | RESTORE |
               COMPARE | EXPORT | IMPORT  | FLAGS ]

Return Code: (Except for REG COMPARE)

  0 - Successful
  1 - Failed

For help on a specific operation type:

  REG Operation /?

Examples:

  REG QUERY /?
  REG ADD /?
  REG DELETE /?
  REG COPY /?
  REG SAVE /?
  REG RESTORE /?
  REG LOAD /?
  REG UNLOAD /?
  REG COMPARE /?
  REG EXPORT /?
  REG IMPORT /?
  REG FLAGS /?

Android YouTube app Play Video Intent

You can also just grab the WebViewClient

wvClient = new WebViewClient() {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
  if (url.startsWith("youtube:")) {
    String youtubeUrl = "http://www.youtube.com/watch?v="
    + url.Replace("youtube:", "");
  startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(youtubeUrl)));
}
return false;
}

Worked fine in my app.

react router v^4.0.0 Uncaught TypeError: Cannot read property 'location' of undefined

Replace

import { Router, Route, Link, browserHistory } from 'react-router';

With

import { BrowserRouter as Router, Route } from 'react-router-dom';

It will start working. It is because react-router-dom exports BrowserRouter

ORA-00054: resource busy and acquire with NOWAIT specified or timeout expired

Your problem looks like you are mixing DML & DDL operations. See this URL which explains this issue:

http://www.orafaq.com/forum/t/54714/2/

curl error 18 - transfer closed with outstanding read data remaining

I had this problem working with pycurl and I solved it using

c.setopt(pycurl.HTTP_VERSION, pycurl.CURL_HTTP_VERSION_1_0) 

like Eric Caron says.

Check time difference in Javascript

grab the input values after form submission in php

$start_time = $_POST('start_time');
$end_time =$_POST('end_time');
$start = $start_time;
$end = $end_time;
$datetime1 = new DateTime($end);
$datetime2 = new DateTime($start);
//echo $datetime1->format('H:i:s');
$interval = $datetime1->diff($datetime2);
$elapsed = $interval->format('%h:%i');
$time = explode(":",$elapsed);
$hours = $time[0];
$minutes = $time[1];
$tminutes = $minutes + ($hours*60);

the variable $tminutes is total diff in minutes , working hour is $hour . this code is for php use this logic and convert this code to js

how to implement a long click listener on a listview

or try this code:

listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {

            public boolean onItemLongClick(AdapterView<?> arg0, View v,
                    int index, long arg3) {

    Toast.makeText(list.this,myList.getItemAtPosition(index).toString(), Toast.LENGTH_LONG).show();
                return false;
            }
}); 

Get city name using geolocation

Here is another go at it .. Adding more to the accepted answer possibly more comprehensive .. of course switch -case will make it look for elegant.

function parseGeoLocationResults(result) {
    const parsedResult = {}
    const {address_components} = result;

    for (var i = 0; i < address_components.length; i++) {
        for (var b = 0; b < address_components[i].types.length; b++) {
            if (address_components[i].types[b] == "street_number") {
                //this is the object you are looking for
                parsedResult.street_number = address_components[i].long_name;
                break;
            }
            else if (address_components[i].types[b] == "route") {
                //this is the object you are looking for
                parsedResult.street_name = address_components[i].long_name;
                break;
            }
            else if (address_components[i].types[b] == "sublocality_level_1") {
                //this is the object you are looking for
                parsedResult.sublocality_level_1 = address_components[i].long_name;
                break;
            }
            else if (address_components[i].types[b] == "sublocality_level_2") {
                //this is the object you are looking for
                parsedResult.sublocality_level_2 = address_components[i].long_name;
                break;
            }
            else if (address_components[i].types[b] == "sublocality_level_3") {
                //this is the object you are looking for
                parsedResult.sublocality_level_3 = address_components[i].long_name;
                break;
            }
            else if (address_components[i].types[b] == "neighborhood") {
                //this is the object you are looking for
                parsedResult.neighborhood = address_components[i].long_name;
                break;
            }
            else if (address_components[i].types[b] == "locality") {
                //this is the object you are looking for
                parsedResult.city = address_components[i].long_name;
                break;
            }
            else if (address_components[i].types[b] == "administrative_area_level_1") {
                //this is the object you are looking for
                parsedResult.state = address_components[i].long_name;
                break;
            }

            else if (address_components[i].types[b] == "postal_code") {
                //this is the object you are looking for
                parsedResult.zip = address_components[i].long_name;
                break;
            }
            else if (address_components[i].types[b] == "country") {
                //this is the object you are looking for
                parsedResult.country = address_components[i].long_name;
                break;
            }
        }
    }
    return parsedResult;
}

Add a CSS class to <%= f.submit %>

As Srdjan Pejic says, you can use

<%= f.submit 'name', :class => 'button' %>

or the new syntax which would be:

<%= f.submit 'name', class: 'button' %>

Match exact string

Use the start and end delimiters: ^abc$

Visual studio equivalent of java System.out

Try: Console.WriteLine (type out for a Visual Studio snippet)

Console.WriteLine(stuff);

Another way is to use System.Diagnostics.Debug.WriteLine:

System.Diagnostics.Debug.WriteLine(stuff);

Debug.WriteLine may suit better for Output window in IDE because it will be rendered for both Console and Windows applications. Whereas Console.WriteLine won't be rendered in Output window but only in the Console itself in case of Console Application type.

Another difference is that Debug.WriteLine will not print anything in Release configuration.

Manually highlight selected text in Notepad++

To highlight a block of code in Notepad++, please do the following steps

  1. Select the required text.
  2. Right click to display the context menu
  3. Choose Style token and select any of the five choices available ( styles from Using 1st style to using 5th style). Each is of different colors.If you want yellow color choose using 3rd style.

If you want to create your own style you can use Style Configurator under Settings menu.

Change default global installation directory for node.js modules in Windows?

trying to install global packages into C:\Program Files (x86)\nodejs\ gave me Run as Administrator issues, because npm was trying to install into
C:\Program Files (x86)\nodejs\node_modules\

to resolve this, change global install directory to C:\Users\{username}\AppData\Roaming\npm:

in C:\Users\{username}\, create .npmrc file with contents:

prefix = "C:\\Users\\{username}\\AppData\\Roaming\\npm"

reference

environment
nodejs x86 installer into C:\Program Files (x86)\nodejs\ on Windows 7 Ultimate N 64-bit SP1
node --version : v0.10.28
npm --version : 1.4.10

How to convert JTextField to String and String to JTextField?

// to string
String text = textField.getText();

// to JTextField
textField.setText(text);

You can also create a new text field: new JTextField(text)

Note that this is not conversion. You have two objects, where one has a property of the type of the other one, and you just set/get it.

Reference: javadocs of JTextField

Putting GridView data in a DataTable

protected void btnExportExcel_Click(object sender, EventArgs e)
{
    DataTable _datatable = new DataTable();
    for (int i = 0; i < grdReport.Columns.Count; i++)
    {
        _datatable.Columns.Add(grdReport.Columns[i].ToString());
    }
    foreach (GridViewRow row in grdReport.Rows)
    {
        DataRow dr = _datatable.NewRow();
        for (int j = 0; j < grdReport.Columns.Count; j++)
        {
            if (!row.Cells[j].Text.Equals("&nbsp;"))
                dr[grdReport.Columns[j].ToString()] = row.Cells[j].Text;
        }

        _datatable.Rows.Add(dr);
    }
    ExportDataTableToExcel(_datatable);
}

How to remove close button on the jQuery UI dialog?

How about using this pure CSS line? I find this the cleanest solution for a dialog with given Id:

.ui-dialog[aria-describedby="IdValueOfDialog"] .ui-dialog-titlebar-close { display: none; }

Bulk create model objects in django

worked for me to use manual transaction handling for the loop(postgres 9.1):

from django.db import transaction
with transaction.commit_on_success():
    for item in items:
        MyModel.objects.create(name=item.name)

in fact it's not the same, as 'native' database bulk insert, but it allows you to avoid/descrease transport/orms operations/sql query analyse costs

python exception message capturing

There are some cases where you can use the e.message or e.messages.. But it does not work in all cases. Anyway the more safe is to use the str(e)

try:
  ...
except Exception as e:
  print(e.message)

Declare variable MySQL trigger

Agree with neubert about the DECLARE statements, this will fix syntax error. But I would suggest you to avoid using openning cursors, they may be slow.

For your task: use INSERT...SELECT statement which will help you to copy data from one table to another using only one query.

INSERT ... SELECT Syntax.

Use of Java's Collections.singletonList()?

singletonList can hold instance of any object. Object state can be modify.

List<Character> list = new ArrayList<Character>();
list.add('X');
list.add('Y');
System.out.println("Initial list: "+ list);
List<List<Character>> list2 = Collections.singletonList(list);
list.add('Z');
System.out.println(list);
System.out.println(list2);

We can not define unmodifiableList like above.

How to remove the first Item from a list?

If you are working with numpy you need to use the delete method:

import numpy as np

a = np.array([1, 2, 3, 4, 5])

a = np.delete(a, 0)

print(a) # [2 3 4 5]

Loading .sql files from within PHP

Just to restate the problem for everyone:

PHP's mysql_query, automatically end-delimits each SQL commands, and additionally is very vague about doing so in its manual. Everything beyond one command will yield an error.

On the other mysql_query is fine with a string containing SQL-style comments, \n, \r..

The limitation of mysql_query reveals itself in that the SQL parser reports the problem to be directly at the next command e.g.

 You have an error in your SQL syntax; check the manual that corresponds to your
 MySQL server version for the right syntax to use near 'INSERT INTO `outputdb:`
 (`intid`, `entry_id`, `definition`) VALUES...

Here is a quick solution: (assuming well formatted SQL;

$sqlCmds = preg_split("/[\n|\t]*;[\n|\t]*[\n|\r]$/", $sqlDump);