Programs & Examples On #Single responsibility principle

The Single Responsibility Principle in object-oriented programming, one of the SOLID principles - A class should have only one reason to change.

Can Selenium WebDriver open browser windows silently in the background?

Chrome 57 has an option to pass the --headless flag, which makes the window invisible.

This flag is different from the --no-startup-window as the last doesn't launch a window. It is used for hosting background apps, as this page says.

Java code to pass the flag to Selenium webdriver (ChromeDriver):

ChromeOptions options = new ChromeOptions();
options.addArguments("--headless");
ChromeDriver chromeDriver = new ChromeDriver(options);

Which command in VBA can count the number of characters in a string variable?

Try this:

word = "habit"
findchar = 'b"
replacechar = ""
charactercount = len(word) - len(replace(word,findchar,replacechar))

What is the use of WPFFontCache Service in WPF? WPFFontCache_v0400.exe taking 100 % CPU all the time this exe is running, why?

for win xp

Steps

  1. [windows key] + R, type services.msc, search for the running instance of "Windows Presentation Foundation (WPF) Font Cache". For my case its 4.0. Stop the service.
  2. [windows key] + R, type C:\Documents and Settings\LocalService\Local Settings\Application Data\, delete all font cache files.
  3. Start the "Windows Presentation Foundation (WPF) Font Cache" service.

Changing button text onclick

It seems like there is just a simple typo error:

  1. Remove the semicolon after change(), there should not be any in the function declaration.
  2. Add a quote in front of the myButton1 declaration.

Corrected code:

<input onclick="change()" type="button" value="Open Curtain" id="myButton1" />
...
function change()
{
    document.getElementById("myButton1").value="Close Curtain"; 
}

A faster and simpler solution would be to include the code in your button and use the keyword this to access the button.

<input onclick="this.value='Close Curtain'" type="button" value="Open Curtain" id="myButton1" />

Android camera android.hardware.Camera deprecated

API Documentation

According to the Android developers guide for android.hardware.Camera, they state:

We recommend using the new android.hardware.camera2 API for new applications.

On the information page about android.hardware.camera2, (linked above), it is stated:

The android.hardware.camera2 package provides an interface to individual camera devices connected to an Android device. It replaces the deprecated Camera class.

The problem

When you check that documentation you'll find that the implementation of these 2 Camera API's are very different.

For example getting camera orientation on android.hardware.camera

@Override
public int getOrientation(final int cameraId) {
    Camera.CameraInfo info = new Camera.CameraInfo();
    Camera.getCameraInfo(cameraId, info);
    return info.orientation;
}

Versus android.hardware.camera2

@Override
public int getOrientation(final int cameraId) {
    try {
        CameraManager manager = (CameraManager) context.getSystemService(Context.CAMERA_SERVICE);
        String[] cameraIds = manager.getCameraIdList();
        CameraCharacteristics characteristics = manager.getCameraCharacteristics(cameraIds[cameraId]);
        return characteristics.get(CameraCharacteristics.SENSOR_ORIENTATION);
    } catch (CameraAccessException e) {
        // TODO handle error properly or pass it on
        return 0;
    }
}

This makes it hard to switch from one to another and write code that can handle both implementations.

Note that in this single code example I already had to work around the fact that the olde camera API works with int primitives for camera IDs while the new one works with String objects. For this example I quickly fixed that by using the int as an index in the new API. If the camera's returned aren't always in the same order this will already cause issues. Alternative approach is to work with String objects and String representation of the old int cameraIDs which is probably safer.

One away around

Now to work around this huge difference you can implement an interface first and reference that interface in your code.

Here I'll list some code for that interface and the 2 implementations. You can limit the implementation to what you actually use of the camera API to limit the amount of work.

In the next section I'll quickly explain how to load one or another.

The interface wrapping all you need, to limit this example I only have 2 methods here.

public interface CameraSupport {
    CameraSupport open(int cameraId);
    int getOrientation(int cameraId);
}

Now have a class for the old camera hardware api:

@SuppressWarnings("deprecation")
public class CameraOld implements CameraSupport {

    private Camera camera;

    @Override
    public CameraSupport open(final int cameraId) {
        this.camera = Camera.open(cameraId);
        return this;
    }

    @Override
    public int getOrientation(final int cameraId) {
       Camera.CameraInfo info = new Camera.CameraInfo();
       Camera.getCameraInfo(cameraId, info);
       return info.orientation;
    }
}

And another one for the new hardware api:

public class CameraNew implements CameraSupport {

    private CameraDevice camera;
    private CameraManager manager;

    public CameraNew(final Context context) {
        this.manager = (CameraManager) context.getSystemService(Context.CAMERA_SERVICE);
    }

    @Override
    public CameraSupport open(final int cameraId) {
        try {
            String[] cameraIds = manager.getCameraIdList();
            manager.openCamera(cameraIds[cameraId], new CameraDevice.StateCallback() {
                @Override
                public void onOpened(CameraDevice camera) {
                    CameraNew.this.camera = camera;
                }

                @Override
                public void onDisconnected(CameraDevice camera) {
                    CameraNew.this.camera = camera;
                    // TODO handle
                }

                @Override
                public void onError(CameraDevice camera, int error) {
                    CameraNew.this.camera = camera;
                    // TODO handle
                }
            }, null);
        } catch (Exception e) {
            // TODO handle
        }
        return this;
    }

    @Override
    public int getOrientation(final int cameraId) {
        try {
            String[] cameraIds = manager.getCameraIdList();
            CameraCharacteristics characteristics = manager.getCameraCharacteristics(cameraIds[cameraId]);
            return characteristics.get(CameraCharacteristics.SENSOR_ORIENTATION);
        } catch (CameraAccessException e) {
            // TODO handle
            return 0;
        }
    }
}

Loading the proper API

Now to load either your CameraOld or CameraNew class you'll have to check the API level since CameraNew is only available from api level 21.

If you have dependency injection set up already you can do so in your module when providing the CameraSupport implementation. Example:

@Module public class CameraModule {

    @Provides
    CameraSupport provideCameraSupport(){
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            return new CameraNew(context);
        } else {
            return new CameraOld();
        }
    } 
}

If you don't use DI you can just make a utility or use Factory pattern to create the proper one. Important part is that the API level is checked.

Get loop count inside a Python FOR loop

The pythonic way is to use enumerate:

for idx,item in enumerate(list):

NameError: global name 'unicode' is not defined - in Python 3

If you need to have the script keep working on python2 and 3 as I did, this might help someone

import sys
if sys.version_info[0] >= 3:
    unicode = str

and can then just do for example

foo = unicode.lower(foo)

Is there a Java equivalent or methodology for the typedef keyword in C++?

Java has primitive types, objects and arrays and that's it. No typedefs.

VBA Runtime Error 1004 "Application-defined or Object-defined error" when Selecting Range

You may receive a "Run-time error 1004" error message when you programmatically set a large array string to a range in Excel 2003

In Office Excel 2003, when you programmatically set a range value with an array containing a large string, you may receive an error message similar to the following:

Run-time error '1004'. Application-defined or operation-defined error.

This issue may occur if one or more of the cells in an array (range of cells) contain a character string that is set to contain more than 911 characters.

To work around this issue, edit the script so that no cells in the array contain a character string that holds more than 911 characters.

For example, the following line of code from the example code block below defines a character string that contains 912 characters:

Sub XLTest()
Dim aValues(4)

  aValues(0) = "Test1"
  aValues(1) = "Test2"
  aValues(2) = "Test3"

  MsgBox "First the Good range set."
  aValues(3) = String(911, 65)

  Range("A1:D1").Value = aValues

  MsgBox "Now the bad range set."
  aValues(3) = String(912, 66)
  Range("A2:D2").Value = aValues

End Sub

Other versions of Excel or free alternatives like Calc should work as well.

Creating a segue programmatically

By definition a segue can't really exist independently of a storyboard. It's even there in the name of the class: UIStoryboardSegue. You don't create segues programmatically - it is the storyboard runtime that creates them for you. You can normally call performSegueWithIdentifier: in your view controller's code, but this relies on having a segue already set up in the storyboard to reference.

What I think you are asking though is how you can create a method in your common view controller (base class) that will transition to a new view controller, and will be inherited by all derived classes. You could do this by creating a method like this one to your base class view controller:

- (IBAction)pushMyNewViewController
{
    MyNewViewController *myNewVC = [[MyNewViewController alloc] init];

    // do any setup you need for myNewVC

    [self presentModalViewController:myNewVC animated:YES];
}

and then in your derived class, call that method when the appropriate button is clicked or table row is selected or whatever.

Can (a== 1 && a ==2 && a==3) ever evaluate to true?

Okay, another hack with generators:

_x000D_
_x000D_
const value = function* () {_x000D_
  let i = 0;_x000D_
  while(true) yield ++i;_x000D_
}();_x000D_
_x000D_
Object.defineProperty(this, 'a', {_x000D_
  get() {_x000D_
    return value.next().value;_x000D_
  }_x000D_
});_x000D_
_x000D_
if (a === 1 && a === 2 && a === 3) {_x000D_
  console.log('yo!');_x000D_
}
_x000D_
_x000D_
_x000D_

Is it possible to run .php files on my local computer?

Sure you just need to setup a local web server. Check out XAMPP: http://www.apachefriends.org/en/xampp.html

That will get you up and running in about 10 minutes.

There is now a way to run php locally without installing a server: https://stackoverflow.com/a/21872484/672229


Yes but the files need to be processed. For example you can install test servers like mamp / lamp / wamp depending on your plateform.

Basically you need apache / php running.

How to SHA1 hash a string in Android?

String.format("%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X", result[0], result[1], result[2], result[3], 
    result[4], result[5], result[6], result[7],
    result[8], result[9], result[10], result[11],
    result[12], result[13], result[14], result[15],
    result[16], result[17], result[18], result[19]);

Django - filtering on foreign key properties

student_user = User.objects.get(id=user_id)
available_subjects = Subject.objects.exclude(subject_grade__student__user=student_user) # My ans
enrolled_subjects = SubjectGrade.objects.filter(student__user=student_user)
context.update({'available_subjects': available_subjects, 'student_user': student_user, 
                'request':request, 'enrolled_subjects': enrolled_subjects})

In my application above, i assume that once a student is enrolled, a subject SubjectGrade instance will be created that contains the subject enrolled and the student himself/herself.

Subject and Student User model is a Foreign Key to the SubjectGrade Model.

In "available_subjects", i excluded all the subjects that are already enrolled by the current student_user by checking all subjectgrade instance that has "student" attribute as the current student_user

PS. Apologies in Advance if you can't still understand because of my explanation. This is the best explanation i Can Provide. Thank you so much

Check if a specific tab page is selected (active)

To check if a specific tab page is the currently selected page of a tab control is easy; just use the SelectedTab property of the tab control:

if (tabControl1.SelectedTab == someTabPage)
{
// Do stuff here...
}

This is more useful if the code is executed based on some event other than the tab page being selected (in which case SelectedIndexChanged would be a better choice).

For example I have an application that uses a timer to regularly poll stuff over TCP/IP connection, but to avoid unnecessary TCP/IP traffic I only poll things that update GUI controls in the currently selected tab page.

Show pop-ups the most elegant way

See http://adamalbrecht.com/2013/12/12/creating-a-simple-modal-dialog-directive-in-angular-js/ for a simple way of doing modal dialog with Angular and without needing bootstrap

Edit: I've since been using ng-dialog from http://likeastore.github.io/ngDialog which is flexible and doesn't have any dependencies.

Checkout another branch when there are uncommitted changes on the current branch

The correct answer is

git checkout -m origin/master

It merges changes from the origin master branch with your local even uncommitted changes.

React native text going off my screen, refusing to wrap. What to do?

you just need to have a wrapper for your <Text> with flex like below;

<View style={{ flex: 1 }}>
  <Text>Your Text</Text>
</View>

Equivalent VB keyword for 'break'

In both Visual Basic 6.0 and VB.NET you would use:

  • Exit For to break from For loop
  • Wend to break from While loop
  • Exit Do to break from Do loop

depending on the loop type. See Exit Statements for more details.

How to open a Bootstrap modal window using jQuery?

Here is how to load bootstrap alert as soon as the document is ready. It is very easy just add

 $(document).ready(function(){
   $("#myModal").modal();
});

I made a demo on W3Schools.

_x000D_
_x000D_
<!DOCTYPE html>_x000D_
<html lang="en">_x000D_
<head>_x000D_
  <title>Bootstrap Example</title>_x000D_
  <meta charset="utf-8">_x000D_
  <meta name="viewport" content="width=device-width, initial-scale=1">_x000D_
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">_x000D_
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>_x000D_
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>_x000D_
</head>_x000D_
<body>_x000D_
_x000D_
<div class="container">_x000D_
  <h2>Here is how to load a bootstrap modal as soon as the document is ready </h2>_x000D_
  <!-- Trigger the modal with a button -->_x000D_
_x000D_
_x000D_
  <!-- Modal -->_x000D_
  <div class="modal fade" id="myModal" role="dialog">_x000D_
    <div class="modal-dialog">_x000D_
    _x000D_
      <!-- Modal content-->_x000D_
      <div class="modal-content">_x000D_
        <div class="modal-header">_x000D_
          <button type="button" class="close" data-dismiss="modal">&times;</button>_x000D_
          <h4 class="modal-title">Modal Header</h4>_x000D_
        </div>_x000D_
        <div class="modal-body">_x000D_
          <p>Some text in the modal.</p>_x000D_
        </div>_x000D_
        <div class="modal-footer">_x000D_
          <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>_x000D_
        </div>_x000D_
      </div>_x000D_
      _x000D_
    </div>_x000D_
  </div>_x000D_
  _x000D_
</div>_x000D_
_x000D_
<script>_x000D_
$(document).ready(function(){_x000D_
   $("#myModal").modal();_x000D_
});_x000D_
</script>_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

How find out which process is using a file in Linux?

@jim's answer is correct -- fuser is what you want.

Additionally (or alternately), you can use lsof to get more information including the username, in case you need permission (without having to run an additional command) to kill the process. (THough of course, if killing the process is what you want, fuser can do that with its -k option. You can have fuser use other signals with the -s option -- check the man page for details.)

For example, with a tail -F /etc/passwd running in one window:

ghoti@pc:~$ lsof | grep passwd
tail      12470    ghoti    3r      REG  251,0     2037 51515911 /etc/passwd

Note that you can also use lsof to find out what processes are using particular sockets. An excellent tool to have in your arsenal.

Calling a Fragment method from a parent Activity

you also call fragment method using interface like

first you create interface

public interface InterfaceName {
    void methodName();
}

after creating interface you implement interface in your fragment

MyFragment extends Fragment implements InterfaceName {
    @overide
    void methodName() {

    }
}

and you create the reference of interface in your activity

class Activityname extends AppCompatActivity {
    Button click;
    MyFragment fragment;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity);

        click = findViewById(R.id.button);

        fragment = new MyFragment();

        click.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
               fragment.methodName();
            }
        });
    }
}

Is there a way to create multiline comments in Python?

I would advise against using """ for multi line comments!

Here is a simple example to highlight what might be considered an unexpected behavior:

print('{}\n{}'.format(
    'I am a string',
    """
    Some people consider me a
    multi-line comment, but
    """
    'clearly I am also a string'
    )
)

Now have a look at the output:

I am a string

    Some people consider me a
    multi-line comment, but
    clearly I am also a string

The multi line string was not treated as comment, but it was concatenated with 'clearly I'm also a string' to form a single string.

If you want to comment multiple lines do so according to PEP 8 guidelines:

print('{}\n{}'.format(
    'I am a string',
    # Some people consider me a
    # multi-line comment, but
    'clearly I am also a string'
    )
)

Output:

I am a string
clearly I am also a string

Convert pandas DataFrame into list of lists

There is a built in method which would be the fastest method also, calling tolist on the .values np array:

df.values.tolist()

[[0.0, 3.61, 380.0, 3.0],
 [1.0, 3.67, 660.0, 3.0],
 [1.0, 3.19, 640.0, 4.0],
 [0.0, 2.93, 520.0, 4.0]]

CSS Disabled scrolling

Try using the following code snippet. This should solve your issue.

body, html { 
    overflow-x: hidden; 
    overflow-y: auto;
}

Postgresql : Connection refused. Check that the hostname and port are correct and that the postmaster is accepting TCP/IP connections

The error you quote has nothing to do with pg_hba.conf; it's failing to connect, not failing to authorize the connection.

Do what the error message says:

Check that the hostname and port are correct and that the postmaster is accepting TCP/IP connections

You haven't shown the command that produces the error. Assuming you're connecting on localhost port 5432 (the defaults for a standard PostgreSQL install), then either:

  • PostgreSQL isn't running

  • PostgreSQL isn't listening for TCP/IP connections (listen_addresses in postgresql.conf)

  • PostgreSQL is only listening on IPv4 (0.0.0.0 or 127.0.0.1) and you're connecting on IPv6 (::1) or vice versa. This seems to be an issue on some older Mac OS X versions that have weird IPv6 socket behaviour, and on some older Windows versions.

  • PostgreSQL is listening on a different port to the one you're connecting on

  • (unlikely) there's an iptables rule blocking loopback connections

(If you are not connecting on localhost, it may also be a network firewall that's blocking TCP/IP connections, but I'm guessing you're using the defaults since you didn't say).

So ... check those:

  • ps -f -u postgres should list postgres processes

  • sudo lsof -n -u postgres |grep LISTEN or sudo netstat -ltnp | grep postgres should show the TCP/IP addresses and ports PostgreSQL is listening on

BTW, I think you must be on an old version. On my 9.3 install, the error is rather more detailed:

$ psql -h localhost -p 12345
psql: could not connect to server: Connection refused
        Is the server running on host "localhost" (::1) and accepting
        TCP/IP connections on port 12345?

How to stop a looping thread in Python?

My solution is:

import threading, time

def a():
    t = threading.currentThread()
    while getattr(t, "do_run", True):
    print('Do something')
    time.sleep(1)

def getThreadByName(name):
    threads = threading.enumerate() #Threads list
    for thread in threads:
        if thread.name == name:
            return thread

threading.Thread(target=a, name='228').start() #Init thread
t = getThreadByName('228') #Get thread by name
time.sleep(5)
t.do_run = False #Signal to stop thread
t.join()

Pandas read_csv from url

To Import Data through URL in pandas just apply the simple below code it works actually better.

import pandas as pd
train = pd.read_table("https://urlandfile.com/dataset.csv")
train.head()

If you are having issues with a raw data then just put 'r' before URL

import pandas as pd
train = pd.read_table(r"https://urlandfile.com/dataset.csv")
train.head()

Can multiple different HTML elements have the same ID if they're different elements?

I think you can't do it because Id is unique you have to use it for one element . You can use class for the purpose

How do I find an array item with TypeScript? (a modern, easier way)

Part One - Polyfill

For browsers that haven't implemented it, a polyfill for array.find. Courtesy of MDN.

if (!Array.prototype.find) {
  Array.prototype.find = function(predicate) {
    if (this == null) {
      throw new TypeError('Array.prototype.find called on null or undefined');
    }
    if (typeof predicate !== 'function') {
      throw new TypeError('predicate must be a function');
    }
    var list = Object(this);
    var length = list.length >>> 0;
    var thisArg = arguments[1];
    var value;

    for (var i = 0; i < length; i++) {
      value = list[i];
      if (predicate.call(thisArg, value, i, list)) {
        return value;
      }
    }
    return undefined;
  };
}

Part Two - Interface

You need to extend the open Array interface to include the find method.

interface Array<T> {
    find(predicate: (search: T) => boolean) : T;
}

When this arrives in TypeScript, you'll get a warning from the compiler that will remind you to delete this.

Part Three - Use it

The variable x will have the expected type... { id: number }

var x = [{ "id": 1 }, { "id": -2 }, { "id": 3 }].find(myObj => myObj.id < 0);

Why would one omit the close tag?

As my question was marked as duplicate of this one, I think it's O.K. to post why NOT omitting closing tag ?> can be for some reasons desired.

  • With complete Processing Instructions Syntax (<?php ... ?>) PHP source is valid SGML document, which can be parsed and processed without problems with SGML parser. With additional restrictions it can be valid XML/XHTML as well.

Nothing prevents you from writing valid XML/HTML/SGML code. PHP documentation is aware of this. Excerpt:

Note: Also note that if you are embedding PHP within XML or XHTML you will need to use the < ?php ?> tags to remain compliant with standards.

Of course PHP syntax is not strict SGML/XML/HTML and you create a document, which is not SGML/XML/HTML, just like you can turn HTML into XHTML to be XML compliant or not.

  • At some point you may want to concatenate sources. This will be not as easy as simply doing cat source1.php source2.php if you have inconsistency introduced by omitting closing ?> tags.

  • Without ?> it's harder to tell if document was left in PHP escape mode or PHP ignore mode (PI tag <?php may have been opened or not). Life is easier if you consistently leave your documents in PHP ignore mode. It's just like work with well formatted HTML documents compared to documents with unclosed, badly nested tags etc.

  • It seems that some editors like Dreamweaver may have problems with PI left open [1].

C#: how to get first char of a string?

Following example for getting first character from a string might help someone

string anyNameForString = "" + stringVariableName[0];

Converting xml to string using C#

As Chris suggests, you can do it like this:

public string GetXMLAsString(XmlDocument myxml)
{
    return myxml.OuterXml;
}

Or like this:

public string GetXMLAsString(XmlDocument myxml)
    {

        StringWriter sw = new StringWriter();
        XmlTextWriter tx = new XmlTextWriter(sw);
        myxml.WriteTo(tx);

        string str = sw.ToString();// 
        return str;
    }

and if you really want to create a new XmlDocument then do this

XmlDocument newxmlDoc= myxml

What are file descriptors, explained in simple terms?

Any operating system has processes (p's) running, say p1, p2, p3 and so forth. Each process usually makes an ongoing usage of files.

Each process is consisted of a process tree (or a process table, in another phrasing).

Usually, Operating systems represent each file in each process by a number (that is to say, in each process tree/table).

The first file used in the process is file0, second is file1, third is file2, and so forth.

Any such number is a file descriptor.

File descriptors are usually integers (0, 1, 2 and not 0.5, 1.5, 2.5).

Given we often describe processes as "process-tables", and given that tables has rows (entries) we can say that the file descriptor cell in each entry, uses to represent the whole entry.

In a similar way, when you open a network socket, it has a socket descriptor.

In some operating systems, you can run out of file descriptors, but such case is extremely rare, and the average computer user shouldn't worry from that.

File descriptors might be global (process A starts in say 0, and ends say in 1 ; Process B starts say in 2, and ends say in 3) and so forth, but as far as I know, usually in modern operating systems, file descriptors are not global, and are actually process-specific (process A starts in say 0 and ends say in 5, while process B starts in 0 and ends say in 10).

Regular Expression: Allow letters, numbers, and spaces (with at least one letter or number)

$("#ValuationName").bind("keypress", function (event) {
    if (event.charCode!=0) {
        var regex = new RegExp("^[a-zA-Z ]+$");
        var key = String.fromCharCode(!event.charCode ? event.which : event.charCode);
        if (!regex.test(key)) {
            event.preventDefault();
            return false;
        }
    }
});

How to exit from Python without traceback?

I would do it this way:

import sys

def do_my_stuff():
    pass

if __name__ == "__main__":
    try:
        do_my_stuff()
    except SystemExit, e:
        print(e)

Vertically centering Bootstrap modal window

Use this simple script that centers the modals.

If you want you can set a custom class (ex: .modal.modal-vcenter instead of .modal) to limit the functionality only to some modals.

var modalVerticalCenterClass = ".modal";

function centerModals($element) {
    var $modals;
    if ($element.length) {
      $modals = $element;
    } else {
    $modals = $(modalVerticalCenterClass + ':visible');
}
$modals.each( function(i) {
    var $clone = $(this).clone().css('display', 'block').appendTo('body');
    var top = Math.round(($clone.height() - $clone.find('.modal-content').height()) / 2);
    top = top > 0 ? top : 0;
    $clone.remove();
    $(this).find('.modal-content').css("margin-top", top);
});
}
$(modalVerticalCenterClass).on('show.bs.modal', function(e) {
    centerModals($(this));
});
$(window).on('resize', centerModals);

Also add this CSS fix for the modal's horizontal spacing; we show the scroll on the modals, the body scrolls is hidden automatically by Bootstrap:

/* scroll fixes */
.modal-open .modal {
  padding-left: 0px !important;
  padding-right: 0px !important;
  overflow-y: scroll;
}

Typescript export vs. default export

Default Export (export default)

// MyClass.ts -- using default export
export default class MyClass { /* ... */ }

The main difference is that you can only have one default export per file and you import it like so:

import MyClass from "./MyClass";

You can give it any name you like. For example this works fine:

import MyClassAlias from "./MyClass";

Named Export (export)

// MyClass.ts -- using named exports
export class MyClass { /* ... */ }
export class MyOtherClass { /* ... */ }

When you use a named export, you can have multiple exports per file and you need to import the exports surrounded in braces:

import { MyClass } from "./MyClass";

Note: Adding the braces will fix the error you're describing in your question and the name specified in the braces needs to match the name of the export.

Or say your file exported multiple classes, then you could import both like so:

import { MyClass, MyOtherClass } from "./MyClass";
// use MyClass and MyOtherClass

Or you could give either of them a different name in this file:

import { MyClass, MyOtherClass as MyOtherClassAlias } from "./MyClass";
// use MyClass and MyOtherClassAlias

Or you could import everything that's exported by using * as:

import * as MyClasses from "./MyClass";
// use MyClasses.MyClass and MyClasses.MyOtherClass here

Which to use?

In ES6, default exports are concise because their use case is more common; however, when I am working on code internal to a project in TypeScript, I prefer to use named exports instead of default exports almost all the time because it works very well with code refactoring. For example, if you default export a class and rename that class, it will only rename the class in that file and not any of the other references in other files. With named exports it will rename the class and all the references to that class in all the other files.

It also plays very nicely with barrel files (files that use namespace exports—export *—to export other files). An example of this is shown in the "example" section of this answer.

Note that my opinion on using named exports even when there is only one export is contrary to the TypeScript Handbook—see the "Red Flags" section. I believe this recommendation only applies when you are creating an API for other people to use and the code is not internal to your project. When I'm designing an API for people to use, I'll use a default export so people can do import myLibraryDefaultExport from "my-library-name";. If you disagree with me about doing this, I would love to hear your reasoning.

That said, find what you prefer! You could use one, the other, or both at the same time.

Additional Points

A default export is actually a named export with the name default, so if the file has a default export then you can also import by doing:

import { default as MyClass } from "./MyClass";

And take note these other ways to import exist: 

import MyDefaultExportedClass, { Class1, Class2 } from "./SomeFile";
import MyDefaultExportedClass, * as Classes from "./SomeFile";
import "./SomeFile"; // runs SomeFile.js without importing any exports

What is Teredo Tunneling Pseudo-Interface?

Unless you have some kind of really weird problem, keep it. The number of IPv6 sites is very small, but there are some and it will let you get to them even if you're at an IPv4 only location.

If it is causing you a problem, it's best to fix it. I've seen a number of people recommending removing it to solve problems. However, they're not actually solving the root cause of the issue. In all the cases I've seen, removing Teredo just happens to cause a side-effect that fixes their problem... :)

How to convert ‘false’ to 0 and ‘true’ to 1 in Python

Any of the following will work:

s = "true"

(s == 'true').real
1

(s == 'false').real
0

(s == 'true').conjugate()    
1

(s == '').conjugate()
0

(s == 'true').__int__()
1

(s == 'opal').__int__()    
0


def as_int(s):
    return (s == 'true').__int__()

>>>> as_int('false')
0
>>>> as_int('true')
1

Understanding Fragment's setRetainInstance(boolean)

setRetainInstance() - Deprecated

As Fragments Version 1.3.0-alpha01

The setRetainInstance() method on Fragments has been deprecated. With the introduction of ViewModels, developers have a specific API for retaining state that can be associated with Activities, Fragments, and Navigation graphs. This allows developers to use a normal, not retained Fragment and keep the specific state they want retained separate, avoiding a common source of leaks while maintaining the useful properties of a single creation and destruction of the retained state (namely, the constructor of the ViewModel and the onCleared() callback it receives).

Merge trunk to branch in Subversion

Is there something that prevents you from merging all revisions on trunk since the last merge?

svn merge -rLastRevisionMergedFromTrunkToBranch:HEAD url/of/trunk path/to/branch/wc

should work just fine. At least if you want to merge all changes on trunk to your branch.

Why is this rsync connection unexpectedly closed on Windows?

I had this error coming up between 2 Linux boxes. Easily solved by installing RSYNC on the remote box as well as the local one.

Automatically capture output of last command into a variable using Bash?

I just distilled this bash function from the suggestions here:

grab() {     
  grab=$("$@")
  echo $grab
}

Then, you just do:

> grab date
Do 16. Feb 13:05:04 CET 2012
> echo $grab
Do 16. Feb 13:05:04 CET 2012

Update: an anonymous user suggested to replace echo by printf '%s\n' which has the advantage that it doesn't process options like -e in the grabbed text. So, if you expect or experience such peculiarities, consider this suggestion. Another option is to use cat <<<$grab instead.

Skip rows during csv import pandas

I got the same issue while running the skiprows while reading the csv file. I was doning skip_rows=1 this will not work

Simple example gives an idea how to use skiprows while reading csv file.

import pandas as pd

#skiprows=1 will skip first line and try to read from second line
df = pd.read_csv('my_csv_file.csv', skiprows=1)  ## pandas as pd

#print the data frame
df

Statistics: combinations in Python

That's probably as fast as you can do it in pure python for reasonably large inputs:

def choose(n, k):
    if k == n: return 1
    if k > n: return 0
    d, q = max(k, n-k), min(k, n-k)
    num =  1
    for n in xrange(d+1, n+1): num *= n
    denom = 1
    for d in xrange(1, q+1): denom *= d
    return num / denom

how to convert rgb color to int in java

Try this one:

Color color = new Color (10,10,10)


myPaint.setColor(color.getRGB());

When to use EntityManager.find() vs EntityManager.getReference() with JPA

I usually use getReference method when i do not need to access database state (I mean getter method). Just to change state (I mean setter method). As you should know, getReference returns a proxy object which uses a powerful feature called automatic dirty checking. Suppose the following

public class Person {

    private String name;
    private Integer age;

}


public class PersonServiceImpl implements PersonService {

    public void changeAge(Integer personId, Integer newAge) {
        Person person = em.getReference(Person.class, personId);

        // person is a proxy
        person.setAge(newAge);
    }

}

If i call find method, JPA provider, behind the scenes, will call

SELECT NAME, AGE FROM PERSON WHERE PERSON_ID = ?

UPDATE PERSON SET AGE = ? WHERE PERSON_ID = ?

If i call getReference method, JPA provider, behind the scenes, will call

UPDATE PERSON SET AGE = ? WHERE PERSON_ID = ?

And you know why ???

When you call getReference, you will get a proxy object. Something like this one (JPA provider takes care of implementing this proxy)

public class PersonProxy {

    // JPA provider sets up this field when you call getReference
    private Integer personId;

    private String query = "UPDATE PERSON SET ";

    private boolean stateChanged = false;

    public void setAge(Integer newAge) {
        stateChanged = true;

        query += query + "AGE = " + newAge;
    }

}

So before transaction commit, JPA provider will see stateChanged flag in order to update OR NOT person entity. If no rows is updated after update statement, JPA provider will throw EntityNotFoundException according to JPA specification.

regards,

Oracle Installer:[INS-13001] Environment does not meet minimum requirements

i was also getting this error, remove oracle folder from

C:\Program Files (x86)\Oracle\Inventory

and

C:\Program Files\Oracle\Inventory

Also remove all component of oracle other version (which you had already in your system).

Go to services and remove all oracle component and delete old client from

C:\app\username\product\11.2.0\client_1\

Why I can't access remote Jupyter Notebook server?

Anyone who is still stuck - follow the instructions on this page.

Basically:

  1. Follow the steps as initially described by AWS.

    1. Open SSH as normal.
    2. source activate python3
    3. Jupyter Notebook
  2. Don't cut and paste anything. Instead open a new terminal window without closing the first one.

  3. In the new window enter enter the SSH command as described in the above link.

  4. Open a web browser and go to http://127.0.0.1:8157

Content Type text/xml; charset=utf-8 was not supported by service

In my case, I had to specify messageEncoding to Mtom in app.config of the client application like that:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <startup> 
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1" />
    </startup>
    <system.serviceModel>
        <bindings>
            <basicHttpBinding>
                <binding name="IntegrationServiceSoap" messageEncoding="Mtom"/>
            </basicHttpBinding>
        </bindings>
        <client>
            <endpoint address="http://localhost:29495/IntegrationService.asmx"
                binding="basicHttpBinding" bindingConfiguration="IntegrationServiceSoap"
                contract="IntegrationService.IntegrationServiceSoap" name="IntegrationServiceSoap" />
        </client>
    </system.serviceModel>
</configuration>

Both my client and server use basicHttpBinding. I hope this helps the others :)

ASP.NET Core Web API Authentication

ASP.NET Core 2.0 with Angular

https://fullstackmark.com/post/13/jwt-authentication-with-aspnet-core-2-web-api-angular-5-net-core-identity-and-facebook-login

Make sure to use type of authentication filter

[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]

How to Logout of an Application Where I Used OAuth2 To Login With Google?

this code will work to sign out

    <script>
      function signOut() 
      {
        var auth2 = gapi.auth2.getAuthInstance();
        auth2.signOut().then(function () {   
        console.log('User signed out.');   
        auth2.disconnect();   
      }); 
        auth2.disconnect();
      } 
    </script>

How to use @Nullable and @Nonnull annotations more effectively?

Short answer: I guess these annotations are only useful for your IDE to warn you of potentially null pointer errors.

As said in the "Clean Code" book, you should check your public method's parameters and also avoid checking invariants.

Another good tip is never returning null values, but using Null Object Pattern instead.

Can a CSV file have a comment?

If you're parsing the file with a FOR command in a batch file a semicolon works (;)

REM test.bat contents

for /F "tokens=1-3 delims=," %%a in (test.csv) do @Echo %%a, %%b, %%c

;test.csv contents (this line is a comment)

;1,ignore this line,no it shouldn't

2,parse this line,yes it should!

;3,ignore this line,no it shouldn't

4,parse this line,yes it should!

OUTPUT:

2, parse this line, yes it should!

4, parse this line, yes it should!

How to return a result (startActivityForResult) from a TabHost Activity?

Oh, god! After spending several hours and downloading the Android sources, I have finally come to a solution.

If you look at the Activity class, you will see, that finish() method only sends back the result if there is a mParent property set to null. Otherwise the result is lost.

public void finish() {
    if (mParent == null) {
        int resultCode;
        Intent resultData;
        synchronized (this) {
            resultCode = mResultCode;
            resultData = mResultData;
        }
        if (Config.LOGV) Log.v(TAG, "Finishing self: token=" + mToken);
        try {
            if (ActivityManagerNative.getDefault()
                .finishActivity(mToken, resultCode, resultData)) {
                mFinished = true;
            }
        } catch (RemoteException e) {
            // Empty
        }
    } else {
        mParent.finishFromChild(this);
    }
}

So my solution is to set result to the parent activity if present, like that:

Intent data = new Intent();
 [...]
if (getParent() == null) {
    setResult(Activity.RESULT_OK, data);
} else {
    getParent().setResult(Activity.RESULT_OK, data);
}
finish();

I hope that will be helpful if someone looks for this problem workaround again.

Try-catch block in Jenkins pipeline script

try/catch is scripted syntax. So any time you are using declarative syntax to use something from scripted in general you can do so by enclosing the scripted syntax in the scripts block in a declarative pipeline. So your try/catch should go inside stage >steps >script.

This holds true for any other scripted pipeline syntax you would like to use in a declarative pipeline as well.

Bootstrap 4: Multilevel Dropdown Inside Navigation

Updated 2018

Here is another variation on the Bootstrap 4.1 Navbar with multi-level dropdown. This one uses minimal CSS for the submenu, and can be re-positioned as desired:

enter image description here

https://www.codeply.com/go/nG6iMAmI2X

.dropdown-submenu {
  position: relative;
}

.dropdown-submenu .dropdown-menu {
  top: 0;
  left: 100%;
  margin-top: -1px;
}

jQuery to control display of submenus:

$('.dropdown-submenu > a').on("click", function(e) {
    var submenu = $(this);
    $('.dropdown-submenu .dropdown-menu').removeClass('show');
    submenu.next('.dropdown-menu').addClass('show');
    e.stopPropagation();
});

$('.dropdown').on("hidden.bs.dropdown", function() {
    // hide any open menus when parent closes
    $('.dropdown-menu.show').removeClass('show');
});

See this answer for activating the Bootstrap 4 submenus on hover

How to wait for the 'end' of 'resize' event and only then perform an action?

var flag=true;
var timeloop;

$(window).resize(function(){
    rtime=new Date();
    if(flag){
        flag=false;
        timeloop=setInterval(function(){
            if(new Date()-rtime>100)
                myAction();
        },100);
    }
})
function myAction(){
    clearInterval(timeloop);
    flag=true;
    //any other code...
}

How to get input field value using PHP

Use PHP's $_POST or $_GET superglobals to retrieve the value of the input tag via the name of the HTML tag.

For Example, change the method in your form and then echo out the value by the name of the input:

Using $_GET method:

<form name="form" action="" method="get">
  <input type="text" name="subject" id="subject" value="Car Loan">
</form>

To show the value:

<?php echo $_GET['subject']; ?>

Using $_POST method:

<form name="form" action="" method="post">
  <input type="text" name="subject" id="subject" value="Car Loan">
</form>

To show the value:

<?php echo $_POST['subject']; ?>

Android Studio gradle takes too long to build

I had the same problem, even the gradle build ran for 8 hours and i was worried. But later on i changed the compile sdk version and minimum sdk version in build.gradle file like this.

Older:

android {
compileSdkVersion 25
buildToolsVersion "29.0.2"

defaultConfig {
    applicationId "com.uwebtechnology.salahadmin"
    minSdkVersion 9
    targetSdkVersion 25
}

New (Updated):

android 
{
  compileSdkVersion 28
   buildToolsVersion "25.0.2"

 defaultConfig {
    applicationId "com.uwebtechnology.salahadmin"
    minSdkVersion 15
    targetSdkVersion 28
 }

Python OpenCV2 (cv2) wrapper to get image size?

cv2 uses numpy for manipulating images, so the proper and best way to get the size of an image is using numpy.shape. Assuming you are working with BGR images, here is an example:

>>> import numpy as np
>>> import cv2
>>> img = cv2.imread('foo.jpg')
>>> height, width, channels = img.shape
>>> print height, width, channels
  600 800 3

In case you were working with binary images, img will have two dimensions, and therefore you must change the code to: height, width = img.shape

Should I initialize variable within constructor or outside constructor

I would say, it depends on the default. For example

public Bar
{
  ArrayList<Foo> foos;
}

I would make a new ArrayList outside of the constructor, if I always assume foos can not be null. If Bar is a valid object, not caring if foos is null or not, I would put it in the constructor.

You might disagree and say that it's the constructors job to put the object in a valid state. However, if clearly all the constructors should do exactly the same thing(initialize foos), why duplicate that code?

Remove carriage return in Unix

If you are running an X environment and have a proper editor (visual studio code), then I would follow the reccomendation:

Visual Studio Code: How to show line endings

Just go to the bottom right corner of your screen, visual studio code will show you both the file encoding and the end of line convention followed by the file, an just with a simple click you can switch that around.

Just use visual code as your replacement for notepad++ on a linux environment and you are set to go.

How to get visitor's location (i.e. country) using geolocation?

You can use ip-api.io to get visitor's location. It supports IPv6.

As a bonus it allows to check whether ip address is a tor node, public proxy or spammer.

JavaScript Code:

function getIPDetails() {
    var ipAddress = document.getElementById("txtIP").value;

    var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function () {
        if (this.readyState == 4 && this.status == 200) {
            console.log(JSON.parse(xhttp.responseText));
        }
    };
    xhttp.open("GET", "http://ip-api.io/json/" + ipAddress, true);
    xhttp.send();
}

<input type="text" id="txtIP" placeholder="Enter the ip address" />
<button onclick="getIPDetails()">Get IP Details</button>

jQuery Code:

$(document).ready(function () {
        $('#btnGetIpDetail').click(function () {
            if ($('#txtIP').val() == '') {
                alert('IP address is reqired');
                return false;
            }
            $.getJSON("http://ip-api.io/json/" + $('#txtIP').val(),
                 function (result) {
                     alert('Country Name: ' + result.country_name)
                     console.log(result);
                 });
        });
    });

<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<div>
    <input type="text" id="txtIP" />
    <button id="btnGetIpDetail">Get Location of IP</button>
</div>

Which keycode for escape key with jQuery

Your code works just fine. It's most likely the window thats not focused. I use a similar function to close iframe boxes etc.

$(document).ready(function(){

    // Set focus
    setTimeout('window.focus()',1000);

});

$(document).keypress(function(e) {

    // Enable esc
    if (e.keyCode == 27) {
      parent.document.getElementById('iframediv').style.display='none';
      parent.document.getElementById('iframe').src='/views/view.empty.black.html';
    }

});

When should I use nil and NULL in Objective-C?

You can use nil about anywhere you can use null. The main difference is that you can send messages to nil, so you can use it in some places where null cant work.

In general, just use nil.

Using git commit -a with vim

  1. In vim, you save a file with :wEnter while in the normal mode (you get to the normal mode by pressing Esc).
  2. You close your file with :q while in the normal mode.

You can combine both these actions and do Esc:wqEnter to save the commit and quit vim.

As an alternate to the above, you can also press ZZ while in the normal mode, which will save the file and exit vim. This is also easier for some people as it's the same key pressed twice.

Automatically size JPanel inside JFrame

As other posters have said, you need to change the LayoutManager being used. I always preferred using a GridLayout so your code would become:

MainPanel mainPanel = new MainPanel();
JFrame mainFrame = new JFrame();
mainFrame.setLayout(new GridLayout());
mainFrame.pack();
mainFrame.setVisible(true);

GridLayout seems more conceptually correct to me when you want your panel to take up the entire screen.

Split by comma and strip whitespace in Python

map(lambda s: s.strip(), mylist) would be a little better than explicitly looping.
Or for the whole thing at once:

map(lambda s:s.strip(), string.split(','))

That's basically everything you need.

Automatically set appsettings.json for dev and release environments in asp.net core?

This is version that works for me when using a console app without a web page:

var builder = new ConfigurationBuilder()
             .SetBasePath(Directory.GetCurrentDirectory())
             .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
             .AddJsonFile($"appsettings.{Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT")}.json", optional: true);

            IConfigurationRoot configuration = builder.Build();
            AppSettings appSettings = new AppSettings();
            configuration.GetSection("AppSettings").Bind(appSettings);

Android SQLite SELECT Query

Try trimming the string to make sure there is no extra white space:

Cursor c = db.rawQuery("SELECT * FROM tbl1 WHERE TRIM(name) = '"+name.trim()+"'", null);

Also use c.moveToFirst() like @thinksteep mentioned.


This is a complete code for select statements.

SQLiteDatabase db = this.getReadableDatabase();
Cursor c = db.rawQuery("SELECT column1,column2,column3 FROM table ", null);
if (c.moveToFirst()){
    do {
        // Passing values 
        String column1 = c.getString(0);
        String column2 = c.getString(1);
        String column3 = c.getString(2); 
        // Do something Here with values
    } while(c.moveToNext());
}
c.close();
db.close();

Difference between <input type='submit' /> and <button type='submit'>text</button>

Not sure where you get your legends from but:

Submit button with <button>

As with:

<button type="submit">(html content)</button>

IE6 will submit all text for this button between the tags, other browsers will only submit the value. Using <button> gives you more layout freedom over the design of the button. In all its intents and purposes, it seemed excellent at first, but various browser quirks make it hard to use at times.

In your example, IE6 will send text to the server, while most other browsers will send nothing. To make it cross-browser compatible, use <button type="submit" value="text">text</button>. Better yet: don't use the value, because if you add HTML it becomes rather tricky what is received on server side. Instead, if you must send an extra value, use a hidden field.

Button with <input>

As with:

<input type="button" />

By default, this does next to nothing. It will not even submit your form. You can only place text on the button and give it a size and a border by means of CSS. Its original (and current) intent was to execute a script without the need to submit the form to the server.

Normal submit button with <input>

As with:

<input type="submit" />

Like the former, but actually submits the surrounding form.

Image submit button with <input>

As with:

<input type="image" />

Like the former (submit), it will also submit a form, but you can use any image. This used to be the preferred way to use images as buttons when a form needed submitting. For more control, <button> is now used. This can also be used for server side image maps but that's a rarity these days. When you use the usemap-attribute and (with or without that attribute), the browser will send the mouse-pointer X/Y coordinates to the server (more precisely, the mouse-pointer location inside the button of the moment you click it). If you just ignore these extras, it is nothing more than a submit button disguised as an image.

There are some subtle differences between browsers, but all will submit the value-attribute, except for the <button> tag as explained above.

What are all the escape characters?

Java Escape Sequences:

\u{0000-FFFF}  /* Unicode [Basic Multilingual Plane only, see below] hex value 
                  does not handle unicode values higher than 0xFFFF (65535),
                  the high surrogate has to be separate: \uD852\uDF62
                  Four hex characters only (no variable width) */
\b             /* \u0008: backspace (BS) */
\t             /* \u0009: horizontal tab (HT) */
\n             /* \u000a: linefeed (LF) */
\f             /* \u000c: form feed (FF) */
\r             /* \u000d: carriage return (CR) */
\"             /* \u0022: double quote (") */
\'             /* \u0027: single quote (') */
\\             /* \u005c: backslash (\) */
\{0-377}       /* \u0000 to \u00ff: from octal value 
                  1 to 3 octal digits (variable width) */

The Basic Multilingual Plane is the unicode values from 0x0000 - 0xFFFF (0 - 65535). Additional planes can only be specified in Java by multiple characters: the egyptian heiroglyph A054 (laying down dude) is U+1303F / &#77887; and would have to be broken into "\uD80C\uDC3F" (UTF-16) for Java strings. Some other languages support higher planes with "\U0001303F".

Remove specific characters from a string in Python

Recursive split: s=string ; chars=chars to remove

def strip(s,chars):
if len(s)==1:
    return "" if s in chars else s
return strip(s[0:int(len(s)/2)],chars) +  strip(s[int(len(s)/2):len(s)],chars)

example:

print(strip("Hello!","lo"))    #He!

How to find elements by class

You can refine your search to only find those divs with a given class using BS3:

mydivs = soup.find_all("div", {"class": "stylelistrow"})

Insert value into a string at a certain position?

If you have a string and you know the index you want to put the two variables in the string you can use:

string temp = temp.Substring(0,index) + textbox1.Text + ":" + textbox2.Text +temp.Substring(index);

But if it is a simple line you can use it this way:

string temp = string.Format("your text goes here {0} rest of the text goes here : {1} , textBox1.Text , textBox2.Text ) ;"

jQuery: print_r() display equivalent?

You can also do

console.log("a = %o, b = %o", a, b);

where a and b are objects.

Populating a razor dropdownlist from a List<object> in MVC

   @{
        List<CategoryModel> CategoryList = CategoryModel.GetCategoryList(UserID);
        IEnumerable<SelectListItem> CategorySelectList = CategoryList.Select(x => new SelectListItem() { Text = x.CategoryName.Trim(), Value = x.CategoryID.Trim() });
    }
    <tr>
        <td>
            <B>Assigned Category:</B>
        </td>
        <td>
            @Html.DropDownList("CategoryList", CategorySelectList, "Select a Category (Optional)")
        </td>
    </tr>

How to force a UIViewController to Portrait orientation in iOS 6

I see the many answer but not get the particular idea and answer about the orientation but see the link good understand the orientation and remove the forcefully rotation for ios6.

http://www.disalvotech.com/blog/app-development/iphone/ios-6-rotation-solution/

I think it is help full.

How to remove the last character from a string?

How to make the char in the recursion at the end:

public static String  removeChar(String word, char charToRemove)
    {
        String char_toremove=Character.toString(charToRemove);
        for(int i = 0; i < word.length(); i++)
        {
            if(word.charAt(i) == charToRemove)
            {
                String newWord = word.substring(0, i) + word.substring(i + 1);
                return removeChar(newWord,charToRemove);
            }
        }
        System.out.println(word);
        return word;
    }

for exemple:

removeChar ("hello world, let's go!",'l') ? "heo word, et's go!llll"
removeChar("you should not go",'o') ? "yu shuld nt goooo"

Best C/C++ Network Library

Aggregated List of Libraries

Create Windows service from executable

Probably all your answers are better, but - just to be complete on the choice of options - I wanted to remind about old, similar method used for years:

SrvAny (installed by InstSrv)

as described here: https://docs.microsoft.com/en-us/troubleshoot/windows-client/deployment/create-user-defined-service

Preventing SQL injection in Node.js

The library has a section in the readme about escaping. It's Javascript-native, so I do not suggest switching to node-mysql-native. The documentation states these guidelines for escaping:

Edit: node-mysql-native is also a pure-Javascript solution.

  • Numbers are left untouched
  • Booleans are converted to true / false strings
  • Date objects are converted to YYYY-mm-dd HH:ii:ss strings
  • Buffers are converted to hex strings, e.g. X'0fa5'
  • Strings are safely escaped
  • Arrays are turned into list, e.g. ['a', 'b'] turns into 'a', 'b'
  • Nested arrays are turned into grouped lists (for bulk inserts), e.g. [['a', 'b'], ['c', 'd']] turns into ('a', 'b'), ('c', 'd')
  • Objects are turned into key = 'val' pairs. Nested objects are cast to strings.
  • undefined / null are converted to NULL
  • NaN / Infinity are left as-is. MySQL does not support these, and trying to insert them as values will trigger MySQL errors until they implement support.

This allows for you to do things like so:

var userId = 5;
var query = connection.query('SELECT * FROM users WHERE id = ?', [userId], function(err, results) {
  //query.sql returns SELECT * FROM users WHERE id = '5'
});

As well as this:

var post  = {id: 1, title: 'Hello MySQL'};
var query = connection.query('INSERT INTO posts SET ?', post, function(err, result) {
  //query.sql returns INSERT INTO posts SET `id` = 1, `title` = 'Hello MySQL'
});

Aside from those functions, you can also use the escape functions:

connection.escape(query);
mysql.escape(query);

To escape query identifiers:

mysql.escapeId(identifier);

And as a response to your comment on prepared statements:

From a usability perspective, the module is great, but it has not yet implemented something akin to PHP's Prepared Statements.

The prepared statements are on the todo list for this connector, but this module at least allows you to specify custom formats that can be very similar to prepared statements. Here's an example from the readme:

connection.config.queryFormat = function (query, values) {
  if (!values) return query;
  return query.replace(/\:(\w+)/g, function (txt, key) {
    if (values.hasOwnProperty(key)) {
      return this.escape(values[key]);
    }
    return txt;
  }.bind(this));
};

This changes the query format of the connection so you can use queries like this:

connection.query("UPDATE posts SET title = :title", { title: "Hello MySQL" });
//equivalent to
connection.query("UPDATE posts SET title = " + mysql.escape("Hello MySQL");

Moving Git repository content to another repository preserving history

I think the commands you are looking for are:

cd repo2
git checkout master
git remote add r1remote **url-of-repo1**
git fetch r1remote
git merge r1remote/master --allow-unrelated-histories
git remote rm r1remote

After that repo2/master will contain everything from repo2/master and repo1/master, and will also have the history of both of them.

Creating an index on a table variable

It should be understood that from a performance standpoint there are no differences between @temp tables and #temp tables that favor variables. They reside in the same place (tempdb) and are implemented the same way. All the differences appear in additional features. See this amazingly complete writeup: https://dba.stackexchange.com/questions/16385/whats-the-difference-between-a-temp-table-and-table-variable-in-sql-server/16386#16386

Although there are cases where a temp table can't be used such as in table or scalar functions, for most other cases prior to v2016 (where even filtered indexes can be added to a table variable) you can simply use a #temp table.

The drawback to using named indexes (or constraints) in tempdb is that the names can then clash. Not just theoretically with other procedures but often quite easily with other instances of the procedure itself which would try to put the same index on its copy of the #temp table.

To avoid name clashes, something like this usually works:

declare @cmd varchar(500)='CREATE NONCLUSTERED INDEX [ix_temp'+cast(newid() as varchar(40))+'] ON #temp (NonUniqueIndexNeeded);';
exec (@cmd);

This insures the name is always unique even between simultaneous executions of the same procedure.

Out-File -append in Powershell does not produce a new line and breaks string into characters

Add-Content is default ASCII and add new line however Add-Content brings locked files issues too.

How to enable CORS in ASP.NET Core

Got this working with .Net Core 3.1 as follows

1.Make sure you place the UseCors code between app.UseRouting(); and app.UseAuthentication();

        app.UseHttpsRedirection();

        app.UseRouting();
        app.UseCors("CorsApi");

        app.UseAuthentication();
        app.UseAuthorization();

        app.UseEndpoints(endpoints => {
            endpoints.MapControllers();
        });

2.Then place this code in the ConfigureServices method

services.AddCors(options =>
        {
            options.AddPolicy("CorsApi",
                builder => builder.WithOrigins("http://localhost:4200", "http://mywebsite.com")
            .AllowAnyHeader()
            .AllowAnyMethod());
        });

3.And above the base controller I placed this

[EnableCors("CorsApi")]
[Route("api/[controller]")]
[ApiController]
public class BaseController : ControllerBase

Now all my controllers will inherit from the BaseController and will have CORS enabled

How can I make visible an invisible control with jquery? (hide and show not work)

Here's some code I use to deal with this.

First we show the element, which will typically set the display type to "block" via .show() function, and then set the CSS rule to "visible":

jQuery( '.element' ).show().css( 'visibility', 'visible' );

Or, assuming that the class that is hiding the element is called hidden, such as in Twitter Bootstrap, toggleClass() can be useful:

jQuery( '.element' ).toggleClass( 'hidden' );

Lastly, if you want to chain functions, perhaps with fancy with a fading effect, you can do it like so:

jQuery( '.element' ).css( 'visibility', 'visible' ).fadeIn( 5000 );

MySQL Update Column +1?

You can do:

UPDATE categories SET posts = posts + 1 WHERE category_id = 42;

Jquery Ajax Loading image

Its a bit late but if you don't want to use a div specifically, I usually do it like this...

var ajax_image = "<img src='/images/Loading.gif' alt='Loading...' />";
$('#ReplaceDiv').html(ajax_image);

ReplaceDiv is the div that the Ajax inserts too. So when it arrives, the image is replaced.

Send POST request with JSON data using Volley

JsonObjectRequest actually accepts JSONObject as body.

From this blog article,

final String url = "some/url";
final JSONObject jsonBody = new JSONObject("{\"type\":\"example\"}");

new JsonObjectRequest(url, jsonBody, new Response.Listener<JSONObject>() { ... });

Here is the source code and JavaDoc (@param jsonRequest):

/**
 * Creates a new request.
 * @param method the HTTP method to use
 * @param url URL to fetch the JSON from
 * @param jsonRequest A {@link JSONObject} to post with the request. Null is allowed and
 *   indicates no parameters will be posted along with request.
 * @param listener Listener to receive the JSON response
 * @param errorListener Error listener, or null to ignore errors.
 */
public JsonObjectRequest(int method, String url, JSONObject jsonRequest,
        Listener<JSONObject> listener, ErrorListener errorListener) {
    super(method, url, (jsonRequest == null) ? null : jsonRequest.toString(), listener,
                errorListener);
}

How to calculate Average Waiting Time and average Turn-around time in SJF Scheduling?

it is wrong. correct will be

P3 P2 P4 P5 P1 0 3 4 6 10 as the correct difference are these

Waiting Time (0+3+4+6+10)/5 = 4.6

Ref: http://www.it.uu.se/edu/course/homepage/oskomp/vt07/lectures/scheduling_algorithms/handout.pdf

How to run JUnit tests with Gradle?

If you want to add a sourceSet for testing in addition to all the existing ones, within a module regardless of the active flavor:

sourceSets {
    test {
        java.srcDirs += [
                'src/customDir/test/kotlin'
        ]
        print(java.srcDirs)   // Clean
    }
}

Pay attention to the operator += and if you want to run integration tests change test to androidTest.

GL

PHP cURL not working - WAMP on Windows 7 64 bit

This is what worked for me

Answered by Soren from another SO thread - CURL for WAMP

"There seems to be a bug somewhere. If you are experiencing this on Win 7 64 bit then try installing apache addon version 2.2.9 and php addon version 5.3.1 and switching to those in WAMP and then activating the CURL extension. That worked for me."

build maven project with propriatery libraries included

You could either add the jar to your project and mess around with the maven-assembly-plugin, or add the jar to your local repository:

mvn install:install-file -Dfile=<path-to-file> -DgroupId=<group-id> -DartifactId=<artifact-id> -Dversion=<version> -Dpackaging=<packaging> -DgeneratePom=true

Where: <path-to-file>  the path to the file to load
       <group-id>      the group that the file should be registered under
       <artifact-id>   the artifact name for the file
       <version>       the version of the file
       <packaging>     the packaging of the file e.g. jar

javax.el.PropertyNotFoundException: Property 'foo' not found on type com.example.Bean

EL interprets ${class.name} as described - the name becomes getName() on the assumption you are using explicit or implicit methods of generating getter/setters

You can override this behavior by explicitly identifying the name as a function: ${class.name()} This calls the function name() directly without modification.

How do I insert multiple checkbox values into a table?

You need to declare the array in the HTML via

<input type="checkbox" name="Days[]" value="Daily">

Also you can insert multiple items with one query like this

$query = "INSERT INTO example (orange) VALUES ";
for ($i=0; $i<count($checkBox); $i++)
    $query .= "('" . $checkBox[$i] . "'),";
$query = rtrim($query,',');
mysql_query($query) or die (mysql_error() );

Also keep in mind that mysql_* functions are officially deprecated and hence should not be used in new code. You can use PDO or MySQLi instead. See this answer on SO for more information.

Add 10 seconds to a Date

Try this way.

Date.prototype.addSeconds = function(seconds) {
  var copiedDate = new Date(this.getTime());
  return new Date(copiedDate.getTime() + seconds * 1000);
}

Just call and assign new Date().addSeconds(10)

Switch between two frames in tkinter

One way is to stack the frames on top of each other, then you can simply raise one above the other in the stacking order. The one on top will be the one that is visible. This works best if all the frames are the same size, but with a little work you can get it to work with any sized frames.

Note: for this to work, all of the widgets for a page must have that page (ie: self) or a descendant as a parent (or master, depending on the terminology you prefer).

Here's a bit of a contrived example to show you the general concept:

try:
    import tkinter as tk                # python 3
    from tkinter import font as tkfont  # python 3
except ImportError:
    import Tkinter as tk     # python 2
    import tkFont as tkfont  # python 2

class SampleApp(tk.Tk):

    def __init__(self, *args, **kwargs):
        tk.Tk.__init__(self, *args, **kwargs)

        self.title_font = tkfont.Font(family='Helvetica', size=18, weight="bold", slant="italic")

        # the container is where we'll stack a bunch of frames
        # on top of each other, then the one we want visible
        # will be raised above the others
        container = tk.Frame(self)
        container.pack(side="top", fill="both", expand=True)
        container.grid_rowconfigure(0, weight=1)
        container.grid_columnconfigure(0, weight=1)

        self.frames = {}
        for F in (StartPage, PageOne, PageTwo):
            page_name = F.__name__
            frame = F(parent=container, controller=self)
            self.frames[page_name] = frame

            # put all of the pages in the same location;
            # the one on the top of the stacking order
            # will be the one that is visible.
            frame.grid(row=0, column=0, sticky="nsew")

        self.show_frame("StartPage")

    def show_frame(self, page_name):
        '''Show a frame for the given page name'''
        frame = self.frames[page_name]
        frame.tkraise()


class StartPage(tk.Frame):

    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        self.controller = controller
        label = tk.Label(self, text="This is the start page", font=controller.title_font)
        label.pack(side="top", fill="x", pady=10)

        button1 = tk.Button(self, text="Go to Page One",
                            command=lambda: controller.show_frame("PageOne"))
        button2 = tk.Button(self, text="Go to Page Two",
                            command=lambda: controller.show_frame("PageTwo"))
        button1.pack()
        button2.pack()


class PageOne(tk.Frame):

    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        self.controller = controller
        label = tk.Label(self, text="This is page 1", font=controller.title_font)
        label.pack(side="top", fill="x", pady=10)
        button = tk.Button(self, text="Go to the start page",
                           command=lambda: controller.show_frame("StartPage"))
        button.pack()


class PageTwo(tk.Frame):

    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        self.controller = controller
        label = tk.Label(self, text="This is page 2", font=controller.title_font)
        label.pack(side="top", fill="x", pady=10)
        button = tk.Button(self, text="Go to the start page",
                           command=lambda: controller.show_frame("StartPage"))
        button.pack()


if __name__ == "__main__":
    app = SampleApp()
    app.mainloop()

start page page 1 page 2

If you find the concept of creating instance in a class confusing, or if different pages need different arguments during construction, you can explicitly call each class separately. The loop serves mainly to illustrate the point that each class is identical.

For example, to create the classes individually you can remove the loop (for F in (StartPage, ...) with this:

self.frames["StartPage"] = StartPage(parent=container, controller=self)
self.frames["PageOne"] = PageOne(parent=container, controller=self)
self.frames["PageTwo"] = PageTwo(parent=container, controller=self)

self.frames["StartPage"].grid(row=0, column=0, sticky="nsew")
self.frames["PageOne"].grid(row=0, column=0, sticky="nsew")
self.frames["PageTwo"].grid(row=0, column=0, sticky="nsew")

Over time people have asked other questions using this code (or an online tutorial that copied this code) as a starting point. You might want to read the answers to these questions:

What is the equivalent of Java's final in C#?

What everyone here is missing is Java's guarantee of definite assignment for final member variables.

For a class C with final member variable V, every possible execution path through every constructor of C must assign V exactly once - failing to assign V or assigning V two or more times will result in an error.

C#'s readonly keyword has no such guarantee - the compiler is more than happy to leave readonly members unassigned or allow you to assign them multiple times within a constructor.

So, final and readonly (at least with respect to member variables) are definitely not equivalent - final is much more strict.

What requests do browsers' "F5" and "Ctrl + F5" refreshes generate?

Generally speaking:

F5 may give you the same page even if the content is changed, because it may load the page from cache. But Ctrl-F5 forces a cache refresh, and will guarantee that if the content is changed, you will get the new content.

How to detect incoming calls, in an Android device?

Just to update Gabe Sechan's answer. If your manifest asks for permissions to READ_CALL_LOG and READ_PHONE_STATE, onReceive will called TWICE. One of which has EXTRA_INCOMING_NUMBER in it and the other doesn't. You have to test which has it and it can occur in any order.

https://developer.android.com/reference/android/telephony/TelephonyManager.html#ACTION_PHONE_STATE_CHANGED

How do I add indices to MySQL tables?

ALTER TABLE `table` ADD INDEX `product_id_index` (`product_id`)

Never compare integer to strings in MySQL. If id is int, remove the quotes.

How to get week number of the month from the date in sql server 2008

No built-in function. It depends what you mean by week of month. You might mean whether it's in the first 7 days (week 1), the second 7 days (week 2), etc. In that case it would just be

(DATEPART(day,@Date)-1)/7 + 1

If you want to use the same week numbering as is used with DATEPART(week,), you could use the difference between the week numbers of the first of the month and the date in question (+1):

(DATEPART(week,@Date)- DATEPART(week,DATEADD(m, DATEDIFF(m, 0, @Date), 0))) + 1

Or, you might need something else, depending on what you mean by the week number.

What's the best/easiest GUI Library for Ruby?

I've had some very good experience with Qt, so I would definitely recommend it.

You should be ware of the licensing model though. If you're developing an open source application, you can use the open-source licensed version free of charge. If you're developing a commercial application, you'll have to pay license fees. And you can't develop in the open source one and then switch the license to commercial before you start selling.

P.S. I just had a quick look at shoes. I really like the declarative definitions of the UI elements, so that's definitely worth investigating...

Addition for BigDecimal

Using Java8 lambdas

List<BigDecimal> items = Arrays.asList(a, b, c, .....);

items.stream().filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);

This covers cases where the some or all of the objects in the list is null.

Calling one Activity from another in Android

As we don't know what are the names of your activities classes, let's call your current activity Activity1, and the one you wish to open - Activity2 (these are the names of the classes)

First you need to define an intent that will be sent to Activity2:

Intent launchActivity2 = new Intent(Activity1.this, Activity2.class);

Then, you can simply launch the activity by running:
startActivity(launchActivity2 );

ini_set("memory_limit") in PHP 5.3.3 is not working at all

Works for me, has nothing to do with PHP 5.3. Just like many such options it cannot be overriden via ini_set() when safe_mode is enabled. Check your updated php.ini (and better yet: change the memory_limit there too).

Linux cmd to search for a class file among jars irrespective of jar path

   locate *.jar | grep Hello.class.jar

The locate command to search the all path of the particular file and display full path of the file.

example

locate *.jar | grep classic.jar

/opt/ltsp/i386/usr/share/firefox/chrome/classic.jar

/opt/ltsp/i386/usr/share/thunderbird/chrome/classic.jar

/root/.wine/drive_c/windows/gecko/0.1.0/wine_gecko/chrome/classic.jar

/usr/lib/firefox-3.0.14/chrome/classic.jar

/usr/lib/firefox-3.5.2/chrome/classic.jar

/usr/lib/xulrunner-1.9.1.2/chrome/classic.jar

/usr/share/firefox/chrome/classic.jar

/usr/share/thunderbird/chrome/classic.jar

What is a provisioning profile used for when developing iPhone applications?

A Quote from : iPhone Developer Program (~8MB PDF)

A provisioning profile is a collection of digital entities that uniquely ties developers and devices to an authorized iPhone Development Team and enables a device to be used for testing. A Development Provisioning Profile must be installed on each device on which you wish to run your application code. Each Development Provisioning Profile will contain a set of iPhone Development Certificates, Unique Device Identifiers and an App ID. Devices specified within the provisioning profile can be used for testing only by those individuals whose iPhone Development Certificates are included in the profile. A single device can contain multiple provisioning profiles.

Joining two table entities in Spring Data JPA

For a typical example of employees owning one or more phones, see this wikibook section.

For your specific example, if you want to do a one-to-one relationship, you should change the next code in ReleaseDateType model:

@Column(nullable = true) 
private Integer media_Id;

for:

@OneToOne(fetch = FetchType.LAZY)
@JoinColumn(name="CACHE_MEDIA_ID", nullable=true)
private CacheMedia cacheMedia ;

and in CacheMedia model you need to add:

@OneToOne(cascade=ALL, mappedBy="ReleaseDateType")
private ReleaseDateType releaseDateType;

then in your repository you should replace:

@Query("Select * from A a  left join B b on a.id=b.id")
public List<ReleaseDateType> FindAllWithDescriptionQuery();

by:

//In this case a query annotation is not need since spring constructs the query from the method name
public List<ReleaseDateType> findByCacheMedia_Id(Integer id); 

or by:

@Query("FROM ReleaseDateType AS rdt WHERE cm.rdt.cacheMedia.id = ?1")    //This is using a named query method
public List<ReleaseDateType> FindAllWithDescriptionQuery(Integer id);

Or if you prefer to do a @OneToMany and @ManyToOne relation, you should change the next code in ReleaseDateType model:

@Column(nullable = true) 
private Integer media_Id;

for:

@OneToMany(cascade=ALL, mappedBy="ReleaseDateType")
private List<CacheMedia> cacheMedias ;

and in CacheMedia model you need to add:

@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name="RELEASE_DATE_TYPE_ID", nullable=true)
private ReleaseDateType releaseDateType;

then in your repository you should replace:

@Query("Select * from A a  left join B b on a.id=b.id")
public List<ReleaseDateType> FindAllWithDescriptionQuery();

by:

//In this case a query annotation is not need since spring constructs the query from the method name
public List<ReleaseDateType> findByCacheMedias_Id(Integer id); 

or by:

@Query("FROM ReleaseDateType AS rdt LEFT JOIN rdt.cacheMedias AS cm WHERE cm.id = ?1")    //This is using a named query method
public List<ReleaseDateType> FindAllWithDescriptionQuery(Integer id);

What's the difference between SCSS and Sass?

Difference between SASS and SCSS article explains the difference in details. Don’t be confused by the SASS and SCSS options, although I also was initially, .scss is Sassy CSS and is the next generation of .sass.

If that didn’t make sense you can see the difference in code below.

/* SCSS */
$blue: #3bbfce;
$margin: 16px;

.content-navigation {
  border-color: $blue;
  color: darken($blue, 9%);
}

.border {
  padding: $margin / 2; margin: $margin / 2; border-color: $blue;
}

In the code above we use ; to separate the declarations. I’ve even added all the declarations for .border onto a single line to illustrate this point further. In contrast, the SASS code below must be on different lines with indentation and there is no use of the ;.

/* SASS */
$blue: #3bbfce
$margin: 16px

.content-navigation
  border-color: $blue
  color: darken($blue, 9%)

.border
  padding: $margin / 2
  margin: $margin / 2
  border-color: $blue

You can see from the CSS below that the SCSS style is a lot more similar to regular CSS than the older SASS approach.

/* CSS */
.content-navigation {
  border-color: #3bbfce;
  color: #2b9eab;
}

.border {
  padding: 8px;
  margin: 8px;
  border-color: #3bbfce;
}

I think most of the time these days if someone mentions that they are working with Sass they are referring to authoring in .scss rather than the traditional .sass way.

How to extract elements from a list using indices in Python?

Use Numpy direct array indexing, as in MATLAB, Julia, ...

a = [10, 11, 12, 13, 14, 15];
s = [1, 2, 5] ;

import numpy as np
list(np.array(a)[s])
# [11, 12, 15]

Better yet, just stay with Numpy arrays

a = np.array([10, 11, 12, 13, 14, 15])
a[s]
#array([11, 12, 15])

change pgsql port

You can also change the port when starting up:

$ pg_ctl -o "-F -p 5433" start

Or

$ postgres -p 5433

More about this in the manual.

Crontab Day of the Week syntax

0 and 7 both stand for Sunday, you can use the one you want, so writing 0-6 or 1-7 has the same result.

Also, as suggested by @Henrik, it is possible to replace numbers by shortened name of days, such as MON, THU, etc:

0 - Sun      Sunday
1 - Mon      Monday
2 - Tue      Tuesday
3 - Wed      Wednesday
4 - Thu      Thursday
5 - Fri      Friday
6 - Sat      Saturday
7 - Sun      Sunday

Graphically:

 +---------- minute (0 - 59)
 ¦ +-------- hour (0 - 23)
 ¦ ¦ +------ day of month (1 - 31)
 ¦ ¦ ¦ +---- month (1 - 12)
 ¦ ¦ ¦ ¦ +-- day of week (0 - 6 => Sunday - Saturday, or
 ¦ ¦ ¦ ¦ ¦                1 - 7 => Monday - Sunday)
 ? ? ? ? ?
 * * * * * command to be executed

Finally, if you want to specify day by day, you can separate days with commas, for example SUN,MON,THU will exectute the command only on sundays, mondays on thursdays.

You can read further details in Wikipedia's article about Cron.

fatal error: mpi.h: No such file or directory #include <mpi.h>

On my system, I was just missing the Linux package.

sudo apt install libopenmpi-dev
pip install mpi4py

(example of something that uses it that is a good instant test to see if it succeeded)

Succeded.

Delete worksheet in Excel using VBA

Try this code:

For Each aSheet In Worksheets

    Select Case aSheet.Name

        Case "ID Sheet", "Summary"
            Application.DisplayAlerts = False
            aSheet.Delete
            Application.DisplayAlerts = True

    End Select

Next aSheet

VBA module that runs other modules

As long as the macros in question are in the same workbook and you verify the names exist, you can call those macros from any other module by name, not by module.

So if in Module1 you had two macros Macro1 and Macro2 and in Module2 you had Macro3 and Macro 4, then in another macro you could call them all:

Sub MasterMacro()
    Call Macro1
    Call Macro2
    Call Macro3
    Call Macro4
End Sub

Convert INT to DATETIME (SQL)

you need to convert to char first because converting to int adds those days to 1900-01-01

select CONVERT (datetime,convert(char(8),rnwl_efctv_dt ))

here are some examples

select CONVERT (datetime,5)

1900-01-06 00:00:00.000

select CONVERT (datetime,20100101)

blows up, because you can't add 20100101 days to 1900-01-01..you go above the limit

convert to char first

declare @i int
select @i = 20100101
select CONVERT (datetime,convert(char(8),@i))

Compare two date formats in javascript/jquery

try with new Date(obj).getTime()

if( new Date(fit_start_time).getTime() > new Date(fit_end_time).getTime() )
{
    alert(fit_start_time + " is greater."); // your code
}
else if( new Date(fit_start_time).getTime() < new Date(fit_end_time).getTime() )
{
    alert(fit_end_time + " is greater."); // your code
}
else
{
    alert("both are same!"); // your code
}

Sprintf equivalent in Java

// Store the formatted string in 'result'
String result = String.format("%4d", i * j);

// Write the result to standard output
System.out.println( result );

See format and its syntax

how to use substr() function in jquery?

If you want to extract from a tag then

$('.dep_buttons').text().substr(0,25)

With the mouseover event,

$(this).text($(this).text().substr(0, 25));

The above will extract the text of a tag, then extract again assign it back.

Horizontal scroll on overflow of table

   .search-table-outter {border:2px solid red; overflow-x:scroll;}
   .search-table{table-layout: fixed; margin:40px auto 0px auto;   }
   .search-table, td, th{border-collapse:collapse; border:1px solid #777;}
   th{padding:20px 7px; font-size:15px; color:#444; background:#66C2E0;}
   td{padding:5px 10px; height:35px;}

You should provide scroll in div.

How can I configure my makefile for debug and release builds?

This question has appeared often when searching for a similar problem, so I feel a fully implemented solution is warranted. Especially since I (and I would assume others) have struggled piecing all the various answers together.

Below is a sample Makefile which supports multiple build types in separate directories. The example illustrated shows debug and release builds.

Supports ...

  • separate project directories for specific builds
  • easy selection of a default target build
  • silent prep target to create directories needed for building the project
  • build-specific compiler configuration flags
  • GNU Make's natural method of determining if project requires a rebuild
  • pattern rules rather than the obsolete suffix rules

#
# Compiler flags
#
CC     = gcc
CFLAGS = -Wall -Werror -Wextra

#
# Project files
#
SRCS = file1.c file2.c file3.c file4.c
OBJS = $(SRCS:.c=.o)
EXE  = exefile

#
# Debug build settings
#
DBGDIR = debug
DBGEXE = $(DBGDIR)/$(EXE)
DBGOBJS = $(addprefix $(DBGDIR)/, $(OBJS))
DBGCFLAGS = -g -O0 -DDEBUG

#
# Release build settings
#
RELDIR = release
RELEXE = $(RELDIR)/$(EXE)
RELOBJS = $(addprefix $(RELDIR)/, $(OBJS))
RELCFLAGS = -O3 -DNDEBUG

.PHONY: all clean debug prep release remake

# Default build
all: prep release

#
# Debug rules
#
debug: $(DBGEXE)

$(DBGEXE): $(DBGOBJS)
    $(CC) $(CFLAGS) $(DBGCFLAGS) -o $(DBGEXE) $^

$(DBGDIR)/%.o: %.c
    $(CC) -c $(CFLAGS) $(DBGCFLAGS) -o $@ $<

#
# Release rules
#
release: $(RELEXE)

$(RELEXE): $(RELOBJS)
    $(CC) $(CFLAGS) $(RELCFLAGS) -o $(RELEXE) $^

$(RELDIR)/%.o: %.c
    $(CC) -c $(CFLAGS) $(RELCFLAGS) -o $@ $<

#
# Other rules
#
prep:
    @mkdir -p $(DBGDIR) $(RELDIR)

remake: clean all

clean:
    rm -f $(RELEXE) $(RELOBJS) $(DBGEXE) $(DBGOBJS)

Extract time from moment js object

You can do something like this

var now = moment();
var time = now.hour() + ':' + now.minutes() + ':' + now.seconds();
time = time + ((now.hour()) >= 12 ? ' PM' : ' AM');

How to get the full path of running process?

 using System.Diagnostics;
 var process = Process.GetCurrentProcess(); // Or whatever method you are using
 string fullPath = process.MainModule.FileName;
 //fullPath has the path to exe.

There is one catch with this API, if you are running this code in 32 bit application, you'll not be able to access 64-bit application paths, so you'd have to compile and run you app as 64-bit application (Project Properties ? Build ? Platform Target ? x64).

Put current changes in a new Git branch

You can simply check out a new branch, and then commit:

git checkout -b my_new_branch
git commit

Checking out the new branch will not discard your changes.

What is the most efficient/elegant way to parse a flat table into a tree?

Well given the choice, I'd be using objects. I'd create an object for each record where each object has a children collection and store them all in an assoc array (/hashtable) where the Id is the key. And blitz through the collection once, adding the children to the relevant children fields. Simple.

But because you're being no fun by restricting use of some good OOP, I'd probably iterate based on:

function PrintLine(int pID, int level)
    foreach record where ParentID == pID
        print level*tabs + record-data
        PrintLine(record.ID, level + 1)

PrintLine(0, 0)

Edit: this is similar to a couple of other entries, but I think it's slightly cleaner. One thing I'll add: this is extremely SQL-intensive. It's nasty. If you have the choice, go the OOP route.

PHP - syntax error, unexpected T_CONSTANT_ENCAPSED_STRING

Wrong quoting: (and missing option closing tag xd)

$out.='<option value="'.$key.'">'.$value["name"].'</option>';

Handling errors in Promise.all

Have you considered Promise.prototype.finally()?

It seems to be designed to do exactly what you want - execute a function once all the promises have settled (resolved/rejected), regardless of some of the promises being rejected.

From the MDN documentation:

The finally() method can be useful if you want to do some processing or cleanup once the promise is settled, regardless of its outcome.

The finally() method is very similar to calling .then(onFinally, onFinally) however there are couple of differences:

When creating a function inline, you can pass it once, instead of being forced to either declare it twice, or create a variable for it.

A finally callback will not receive any argument, since there's no reliable means of determining if the promise was fulfilled or rejected. This use case is for precisely when you do not care about the rejection reason, or the fulfillment value, and so there's no need to provide it.

Unlike Promise.resolve(2).then(() => {}, () => {}) (which will be resolved with undefined), Promise.resolve(2).finally(() => {}) will be resolved with 2. Similarly, unlike Promise.reject(3).then(() => {}, () => {}) (which will be fulfilled with undefined), Promise.reject(3).finally(() => {}) will be rejected with 3.

== Fallback ==

If your version of JavaScript doesn't support Promise.prototype.finally() you can use this workaround from Jake Archibald: Promise.all(promises.map(p => p.catch(() => undefined)));

Change label text using JavaScript

Because a label element is not loaded when a script is executed. Swap the label and script elements, and it will work:

<label id="lbltipAddedComment"></label>
<script>
    document.getElementById('lbltipAddedComment').innerHTML = 'Your tip has been submitted!';
</script>

Rails - controller action name to string

In the specific case of a Rails action (as opposed to the general case of getting the current method name) you can use params[:action]

Alternatively you might want to look into customising the Rails log format so that the action/method name is included by the format rather than it being in your log message.

Capture event onclose browser

Men, use this:

if(myWindow.closed){
    callback();
    return;
}

What characters are valid in a URL?

All the gory details can be found in the current RFC on the topic: RFC 3986 (Uniform Resource Identifier (URI): Generic Syntax)

Based on this related answer, you are looking at a list that looks like: A-Z, a-z, 0-9, -, ., _, ~, :, /, ?, #, [, ], @, !, $, &, ', (, ), *, +, ,, ;, %, and =. Everything else must be url-encoded. Also, some of these characters can only exist in very specific spots in a URI and outside of those spots must be url-encoded (e.g. % can only be used in conjunction with url encoding as in %20), the RFC has all of these specifics.

How to get just the date part of getdate()?

SELECT CONVERT(date, GETDATE())

What is the easiest way to ignore a JPA field during persistence?

This answer comes a little late, but it completes the response.

In order to avoid a field from an entity to be persisted in DB one can use one of the two mechanisms:

@Transient - the JPA annotation marking a field as not persistable

transient keyword in java. Beware - using this keyword, will prevent the field to be used with any serialization mechanism from java. So, if the field must be serialized you'd better use just the @Transient annotation.

In Python How can I declare a Dynamic Array

In Python, a list is a dynamic array. You can create one like this:

lst = [] # Declares an empty list named lst

Or you can fill it with items:

lst = [1,2,3]

You can add items using "append":

lst.append('a')

You can iterate over elements of the list using the for loop:

for item in lst:
    # Do something with item

Or, if you'd like to keep track of the current index:

for idx, item in enumerate(lst):
    # idx is the current idx, while item is lst[idx]

To remove elements, you can use the del command or the remove function as in:

del lst[0] # Deletes the first item
lst.remove(x) # Removes the first occurence of x in the list

Note, though, that one cannot iterate over the list and modify it at the same time; to do that, you should instead iterate over a slice of the list (which is basically a copy of the list). As in:

 for item in lst[:]: # Notice the [:] which makes a slice
       # Now we can modify lst, since we are iterating over a copy of it

File being used by another process after using File.Create()

FileStream fs= File.Create(ConfigurationManager.AppSettings["file"]);
fs.Close();

jquery $(window).width() and $(window).height() return different values when viewport has not been resized

I was having a very similar problem. I was getting inconsistent height() values when I refreshed my page. (It wasn't my variable causing the problem, it was the actual height value.)

I noticed that in the head of my page I called my scripts first, then my css file. I switched so that the css file is linked first, then the script files and that seems to have fixed the problem so far.

Hope that helps.

Setting action for back button in navigation controller

By using the target and action variables that you are currently leaving 'nil', you should be able to wire your save-dialogs in so that they are called when the button is "selected". Watch out, this may get triggered at strange moments.

I agree mostly with Amagrammer, but I don't think it would be that hard to make the button with the arrow custom. I would just rename the back button, take a screen shot, photoshop the button size needed, and have that be the image on the top of your button.

C function that counts lines in file

I don't see anything immediately obvious as to what would cause a segmentation fault. My only suspicion is that your code expects to get a filename as a parameter when you run it, but if you don't pass it, it will attempt to reference one, anyway.

Accessing argv[1] when it doesn't exist would cause a segmentation fault. It's generally good practice to check the number of arguments before trying to reference them. You can do this by using the following function prototype for main(), and checking that argc is greater than 1 (simply, it will indicate the number entries in argv).

int main(int argc, char** argv)

The best way to figure out what causes a segfault in general is to use a debugger. If you're in Visual Studio, put a breakpoint at the top of your main function and then choose Run with debugging instead of "Run without debugging" when you start the program. It will stop execution at the top, and let you step line-by-line until you see a problem.

If you're in Linux, you can just grab the core file (it will have "core" in the name) and load that with gdb (GNU Debugger). It can give you a stack dump which will point you straight to the line that caused the segmentation fault to occur.

EDIT: I see you changed your question and code. So this answer probably isn't useful anymore, but I'll leave it as it's good advice anyway, and see if I can address the modified question, shortly).

Java 8 Iterable.forEach() vs foreach loop

One of most upleasing functional forEach's limitations is lack of checked exceptions support.

One possible workaround is to replace terminal forEach with plain old foreach loop:

    Stream<String> stream = Stream.of("", "1", "2", "3").filter(s -> !s.isEmpty());
    Iterable<String> iterable = stream::iterator;
    for (String s : iterable) {
        fileWriter.append(s);
    }

Here is list of most popular questions with other workarounds on checked exception handling within lambdas and streams:

Java 8 Lambda function that throws exception?

Java 8: Lambda-Streams, Filter by Method with Exception

How can I throw CHECKED exceptions from inside Java 8 streams?

Java 8: Mandatory checked exceptions handling in lambda expressions. Why mandatory, not optional?

Entity Framework : How do you refresh the model when the db changes?

I just had to update an .edmx model. The model/Run Custom Tool option was not refreshing the fields for me, but once I had the graphical designer open, I was able to manually rename the fields.

Histogram with Logarithmic Scale and custom breaks

Dirk's answer is a great one. If you want an appearance like what hist produces, you can also try this:

buckets <- c(0,1,2,3,4,5,25)
mydata_hist <- hist(mydata$V3, breaks=buckets, plot=FALSE)
bp <- barplot(mydata_hist$count, log="y", col="white", names.arg=buckets)
text(bp, mydata_hist$counts, labels=mydata_hist$counts, pos=1)

The last line is optional, it adds value labels just under the top of each bar. This can be useful for log scale graphs, but can also be omitted.

I also pass main, xlab, and ylab parameters to provide a plot title, x-axis label, and y-axis label.

Using 'sudo apt-get install build-essentials'

Drop the 's' off of the package name.

You want sudo apt-get install build-essential

You may also need to run sudo apt-get update to make sure that your package index is up to date.

For anyone wondering why this package may be needed as part of another install, it contains the essential tools for building most other packages from source (C/C++ compiler, libc, and make).

Iterate a certain number of times without storing the iteration number anywhere

The idiom (shared by quite a few other languages) for an unused variable is a single underscore _. Code analysers typically won't complain about _ being unused, and programmers will instantly know it's a shortcut for i_dont_care_wtf_you_put_here. There is no way to iterate without having an item variable - as the Zen of Python puts it, "special cases aren't special enough to break the rules".

Selecting multiple classes with jQuery

Have you tried this?

$('.myClass, .myOtherClass').removeClass('theclass');

How to fill the whole canvas with specific color?

_x000D_
_x000D_
let canvas = document.getElementById('canvas');_x000D_
canvas.setAttribute('width', window.innerWidth);_x000D_
canvas.setAttribute('height', window.innerHeight);_x000D_
let ctx = canvas.getContext('2d');_x000D_
_x000D_
//Draw Canvas Fill mode_x000D_
ctx.fillStyle = 'blue';_x000D_
ctx.fillRect(0,0,canvas.width, canvas.height);
_x000D_
* { margin: 0; padding: 0; box-sizing: border-box; }_x000D_
body { overflow: hidden; }
_x000D_
<canvas id='canvas'></canvas>
_x000D_
_x000D_
_x000D_

What is the difference between substr and substring?

substring (MDN) takes parameters as (from, to).
substr (MDN) takes parameters as (from, length).

Update: MDN considers substr legacy.

alert("abc".substr(1,2)); // returns "bc"
alert("abc".substring(1,2)); // returns "b"

You can remember substring (with an i) takes indices, as does yet another string extraction method, slice (with an i).

When starting from 0 you can use either method.

How do I tokenize a string in C++?

A solution using regex_token_iterators:

#include <iostream>
#include <regex>
#include <string>

using namespace std;

int main()
{
    string str("The quick brown fox");

    regex reg("\\s+");

    sregex_token_iterator iter(str.begin(), str.end(), reg, -1);
    sregex_token_iterator end;

    vector<string> vec(iter, end);

    for (auto a : vec)
    {
        cout << a << endl;
    }
}

How do you open a file in C++?

To open and read a text file line per line, you could use the following:

// define your file name
string file_name = "data.txt";

// attach an input stream to the wanted file
ifstream input_stream(file_name);

// check stream status
if (!input_stream) cerr << "Can't open input file!";

// file contents  
vector<string> text;

// one line
string line;

// extract all the text from the input file
while (getline(input_stream, line)) {

    // store each line in the vector
    text.push_back(line);
}

To open and read a binary file you need to explicitly declare the reading format in your input stream to be binary, and read memory that has no explicit interpretation using stream member function read():

// define your file name
string file_name = "binary_data.bin";

// attach an input stream to the wanted file
ifstream input_stream(file_name, ios::binary);

// check stream status
if (!input_stream) cerr << "Can't open input file!";

// use function that explicitly specifies the amount of block memory read 
int memory_size = 10;

// allocate 10 bytes of memory on heap
char* dynamic_buffer = new char[memory_size];

// read 10 bytes and store in dynamic_buffer
file_name.read(dynamic_buffer, memory_size);

When doing this you'll need to #include the header : <iostream>

PostgreSQL database default location on Linux

On Centos 6.5/PostgreSQL 9.3:

Change the value of "PGDATA=/var/lib/pgsql/data" to whatever location you want in the initial script file /etc/init.d/postgresql.

Remember to chmod 700 and chown postgres:postgres to the new location and you're the boss.

How to create a temporary directory?

Use mktemp -d. It creates a temporary directory with a random name and makes sure that file doesn't already exist. You need to remember to delete the directory after using it though.

jQuery - on change input text

This worked for me

var change_temp = "";
$('#url_key').bind('keydown keyup',function(e){
    if(e.type == "keydown"){
        change_temp = $(this).val();
        return;
    }
    if($(this).val() != change_temp){
        // add the code to on change here 
    }

});

Preventing twitter bootstrap carousel from auto sliding on page load

Actually, the problem is now solved. I added the 'pause' argument to the method 'carousel' like below:

$(document).ready(function() {      
   $('.carousel').carousel('pause');
});

Anyway, thanks so much @Yohn for your tips toward this solution.

How to define unidirectional OneToMany relationship in JPA

My bible for JPA work is the Java Persistence wikibook. It has a section on unidirectional OneToMany which explains how to do this with a @JoinColumn annotation. In your case, i think you would want:

@OneToMany
@JoinColumn(name="TXTHEAD_CODE")
private Set<Text> text;

I've used a Set rather than a List, because the data itself is not ordered.

The above is using a defaulted referencedColumnName, unlike the example in the wikibook. If that doesn't work, try an explicit one:

@OneToMany
@JoinColumn(name="TXTHEAD_CODE", referencedColumnName="DATREG_META_CODE")
private Set<Text> text;

Hidden Features of Xcode

Not much of a keyboard shortcut but the TODO comments in the source show up in the method/function dropdown at the top of the editor.

So for example:

// TODO: Some task that needs to be done.

shows up in the drop down list of methods and functions so you can jump to it directly.

Most Java IDEs show a marker for these task tags in the scrollbar, which is nicer, but this also works.

Difference between decimal, float and double in .NET?

float 7 digits of precision

double has about 15 digits of precision

decimal has about 28 digits of precision

If you need better accuracy, use double instead of float. In modern CPUs both data types have almost the same performance. The only benifit of using float is they take up less space. Practically matters only if you have got many of them.

I found this is interesting. What Every Computer Scientist Should Know About Floating-Point Arithmetic

Linux : Search for a Particular word in a List of files under a directory

This is a very frequent task in linux. I use grep -rn '' . all the time to do this. -r for recursive (folder and subfolders) -n so it gives the line numbers, the dot stands for the current directory.

grep -rn '<word or regex>' <location>

do a

man grep 

for more options

How to compile a Perl script to a Windows executable with Strawberry Perl?

  :: short answer :
  :: perl -MCPAN -e "install PAR::Packer" 
  pp -o <<DesiredExeName>>.exe <<MyFancyPerlScript>> 

  :: long answer - create the following cmd , adjust vars to your taste ...
  :: next_line_is_templatized
  :: file:compile-morphus.1.2.3.dev.ysg.cmd v1.0.0
  :: disable the echo
  @echo off

  :: this is part of the name of the file - not used
  set _Action=run

  :: the name of the Product next_line_is_templatized
  set _ProductName=morphus

  :: the version of the current Product next_line_is_templatized
  set _ProductVersion=1.2.3

  :: could be dev , test , dev , prod next_line_is_templatized
  set _ProductType=dev

  :: who owns this Product / environment next_line_is_templatized
  set _ProductOwner=ysg

  :: identifies an instance of the tool ( new instance for this version could be created by simply changing the owner )   
  set _EnvironmentName=%_ProductName%.%_ProductVersion%.%_ProductType%.%_ProductOwner%

  :: go the run dir
  cd %~dp0

  :: do 4 times going up
  for /L %%i in (1,1,5) do pushd ..

  :: The BaseDir is 4 dirs up than the run dir
  set _ProductBaseDir=%CD%
  :: debug echo BEFORE _ProductBaseDir is %_ProductBaseDir%
  :: remove the trailing \

  IF %_ProductBaseDir:~-1%==\ SET _ProductBaseDir=%_ProductBaseDir:~0,-1%
  :: debug echo AFTER _ProductBaseDir is %_ProductBaseDir%
  :: debug pause


  :: The version directory of the Product 
  set _ProductVersionDir=%_ProductBaseDir%\%_ProductName%\%_EnvironmentName%

  :: the dir under which all the perl scripts are placed
  set _ProductVersionPerlDir=%_ProductVersionDir%\sfw\perl

  :: The Perl script performing all the tasks
  set _PerlScript=%_ProductVersionPerlDir%\%_Action%_%_ProductName%.pl

  :: where the log events are stored 
  set _RunLog=%_ProductVersionDir%\data\log\compile-%_ProductName%.cmd.log

  :: define a favorite editor 
  set _MyEditor=textpad

  ECHO Check the variables 
  set _
  :: debug PAUSE
  :: truncate the run log
  echo date is %date% time is %time% > %_RunLog%


  :: uncomment this to debug all the vars 
  :: debug set  >> %_RunLog%

  :: for each perl pm and or pl file to check syntax and with output to logs
  for /f %%i in ('dir %_ProductVersionPerlDir%\*.pl /s /b /a-d' ) do echo %%i >> %_RunLog%&perl -wc %%i | tee -a  %_RunLog% 2>&1


  :: for each perl pm and or pl file to check syntax and with output to logs
  for /f %%i in ('dir %_ProductVersionPerlDir%\*.pm /s /b /a-d' ) do echo %%i >> %_RunLog%&perl -wc %%i | tee -a  %_RunLog% 2>&1

  :: now open the run log
  cmd /c start /max %_MyEditor% %_RunLog%


  :: this is the call without debugging
  :: old 
  echo CFPoint1  OK The run cmd script %0 is executed >> %_RunLog%
  echo CFPoint2  OK  compile the exe file  STDOUT and STDERR  to a single _RunLog file >> %_RunLog%
  cd %_ProductVersionPerlDir%

  pp -o %_Action%_%_ProductName%.exe %_PerlScript% | tee -a %_RunLog% 2>&1 

  :: open the run log
  cmd /c start /max %_MyEditor% %_RunLog%

  :: uncomment this line to wait for 5 seconds
  :: ping localhost -n 5

  :: uncomment this line to see what is happening 
  :: PAUSE

  ::
  :::::::
  :: Purpose: 
  :: To compile every *.pl file into *.exe file under a folder 
  :::::::
  :: Requirements : 
  :: perl , pp , win gnu utils tee 
  :: perl -MCPAN -e "install PAR::Packer" 
  :: text editor supporting <<textEditor>> <<FileNameToOpen>> cmd call syntax
  :::::::
  :: VersionHistory
  :: 1.0.0 --- 2012-06-23 12:05:45 --- ysg --- Initial creation from run_morphus.cmd
  :::::::
  :: eof file:compile-morphus.1.2.3.dev.ysg.cmd v1.0.0

CSS horizontal centering of a fixed div?

It is possible to horisontally center the div this way:

html:

<div class="container">
    <div class="inner">content</div>
</div>

css:

.container {
    left: 0;
    right: 0;
    bottom: 0; /* or top: 0, or any needed value */
    position: fixed;
    z-index: 1000; /* or even higher to prevent guarantee overlapping */
}

.inner {
    max-width: 600px; /* just for example */
    margin: 0 auto;
}

Using this way you will have always your inner block centered, in addition it can be easily turned to true responsive (in the example it will be just fluid on smaller screens), therefore no limitation in as in the question example and in the chosen answer.

How to insert tab character when expandtab option is on in Vim

You can use <CTRL-V><Tab> in "insert mode". In insert mode, <CTRL-V> inserts a literal copy of your next character.

If you need to do this often, @Dee`Kej suggested (in the comments) setting Shift+Tab to insert a real tab with this mapping:

:inoremap <S-Tab> <C-V><Tab>

Also, as noted by @feedbackloop, on Windows you may need to press <CTRL-Q> rather than <CTRL-V>.

How does the Java 'for each' loop work?

As many of other answers correctly state, the for each loop is just syntactic sugar over the same old for loop and the compiler translates it to the same old for loop.

javac (open jdk) has a switch -XD-printflat, which generates a java file with all the syntactic sugar removed. the complete command looks like this

javac -XD-printflat -d src/ MyFile.java

//-d is used to specify the directory for output java file

So Lets remove the syntactical sugar

To answer this question, I created a file and wrote two version of for each, one with array and another with a list. my java file looked like this.

import java.util.*;
public class Temp{

    private static void forEachArray(){
        int[] arr = new int[]{1,2,3,4,5};
        for(int i: arr){
            System.out.print(i);
        }
    }

    private static void forEachList(){
        List<Integer> list = Arrays.asList(1,2,3,4,5);
        for(Integer i: list){
            System.out.print(i);
        }
    }
}

When I compiled this file with above switch, I got the following output.

import java.util.*;

public class Temp {

    public Temp() {
        super();
    }

    private static void forEachArray() {
        int[] arr = new int[]{1, 2, 3, 4, 5};
        for (/*synthetic*/ int[] arr$ = arr, len$ = arr$.length, i$ = 0; i$ < len$; ++i$) {
            int i = arr$[i$];
            {
                System.out.print(i);
            }
        }
    }

    private static void forEachList() {
        List list = Arrays.asList(new Integer[]{Integer.valueOf(1), Integer.valueOf(2), Integer.valueOf(3), Integer.valueOf(4), Integer.valueOf(5)});
        for (/*synthetic*/ Iterator i$ = list.iterator(); i$.hasNext(); ) {
            Integer i = (Integer)i$.next();
            {
                System.out.print(i);
            }
        }
    }
}

You can see that along with the other syntactic sugar (Autoboxing) for each loops got changed to simple loops.

Mosaic Grid gallery with dynamic sized images

I think you can try "Google Grid Gallery", it based on aforementioned Masonry with some additions, like styles and viewer.

Better techniques for trimming leading zeros in SQL Server?

The following will return '0' if the string consists entirely of zeros:

CASE WHEN SUBSTRING(str_col, PATINDEX('%[^0]%', str_col+'.'), LEN(str_col)) = '' THEN '0' ELSE SUBSTRING(str_col, PATINDEX('%[^0]%', str_col+'.'), LEN(str_col)) END AS str_col

REST response code for invalid data

If the request could not be correctly parsed (including the request entity/body) the appropriate response is 400 Bad Request [1].

RFC 4918 states that 422 Unprocessable Entity is applicable when the request entity is syntactically well-formed, but semantically erroneous. So if the request entity is garbled (like a bad email format) use 400; but if it just doesn't make sense (like @example.com) use 422.

If the issue is that, as stated in the question, user name/email already exists, you could use 409 Conflict [2] with a description of the conflict, and a hint about how to fix it (in this case, "pick a different user name/email"). However in the spec as written, 403 Forbidden [3] can also be used in this case, arguments about HTTP Authorization notwithstanding.

412 Precondition Failed [4] is used when a precondition request header (e.g. If-Match) that was supplied by the client evaluates to false. That is, the client requested something and supplied preconditions, knowing full well that those preconditions might fail. 412 should never be sprung on the client out of the blue, and shouldn't be related to the request entity per se.

How to push objects in AngularJS between ngRepeat arrays

You'd be much better off using the same array with both lists, and creating angular filters to achieve your goal.

http://docs.angularjs.org/guide/dev_guide.templates.filters.creating_filters

Rough, untested code follows:

appModule.filter('checked', function() {
    return function(input, checked) {
        if(!input)return input;
        var output = []
        for (i in input){
            var item = input[i];
            if(item.checked == checked)output.push(item);
        }
        return output
    }
});

and the view (i added an "uncheck" button too)

<div id="AddItem">
     <h3>Add Item</h3>

    <input value="1" type="number" placeholder="1" ng-model="itemAmount">
    <input value="" type="text" placeholder="Name of Item" ng-model="itemName">
    <br/>
    <button ng-click="addItem()">Add to list</button>
</div>
<!-- begin: LIST OF CHECKED ITEMS -->
<div id="CheckedList">
     <h3>Checked Items: {{getTotalCheckedItems()}}</h3>

     <h4>Checked:</h4>

    <table>
        <tr ng-repeat="item in items | checked:true" class="item-checked">
            <td><b>amount:</b> {{item.amount}} -</td>
            <td><b>name:</b> {{item.name}} -</td>
            <td> 
               <i>this item is checked!</i>
               <button ng-click="item.checked = false">uncheck item</button>

            </td>
        </tr>
    </table>
</div>
<!-- end: LIST OF CHECKED ITEMS -->
<!-- begin: LIST OF UNCHECKED ITEMS -->
<div id="UncheckedList">
     <h3>Unchecked Items: {{getTotalItems()}}</h3>

     <h4>Unchecked:</h4>

    <table>
        <tr ng-repeat="item in items | checked:false" class="item-unchecked">
            <td><b>amount:</b> {{item.amount}} -</td>
            <td><b>name:</b> {{item.name}} -</td>
            <td>
                <button ng-click="item.checked = true">check item</button>
            </td>
        </tr>
    </table>
</div>
<!-- end: LIST OF ITEMS -->

Then you dont need the toggle methods etc in your controller

How to write a foreach in SQL Server?

I made a procedure that execute a FOREACH with CURSOR for any table.

Example of use:

CREATE TABLE #A (I INT, J INT)
INSERT INTO #A VALUES (1, 2), (2, 3)
EXEC PRC_FOREACH
    #A --Table we want to do the FOREACH
    , 'SELECT @I, @J' --The execute command, each column becomes a variable in the same type, so DON'T USE SPACES IN NAMES
   --The third variable is the database, it's optional because a table in TEMPB or the DB of the proc will be discovered in code

The result is 2 selects for each row. The syntax of UPDATE and break the FOREACH are written in the hints.

This is the proc code:

CREATE PROC [dbo].[PRC_FOREACH] (@TBL VARCHAR(100) = NULL, @EXECUTE NVARCHAR(MAX)=NULL, @DB VARCHAR(100) = NULL) AS BEGIN

    --LOOP BETWEEN EACH TABLE LINE            

IF @TBL + @EXECUTE IS NULL BEGIN
    PRINT '@TBL: A TABLE TO MAKE OUT EACH LINE'
    PRINT '@EXECUTE: COMMAND TO BE PERFORMED ON EACH FOREACH TRANSACTION'
    PRINT '@DB: BANK WHERE THIS TABLE IS (IF NOT INFORMED IT WILL BE DB_NAME () OR TEMPDB)' + CHAR(13)
    PRINT 'ROW COLUMNS WILL VARIABLE WITH THE SAME NAME (COL_A = @COL_A)'
    PRINT 'THEREFORE THE COLUMNS CANT CONTAIN SPACES!' + CHAR(13)
    PRINT 'SYNTAX UPDATE:

UPDATE TABLE
SET COL = NEW_VALUE
WHERE CURRENT OF MY_CURSOR

CLOSE CURSOR (BEFORE ALL LINES):

IF 1 = 1 GOTO FIM_CURSOR'
    RETURN
END
SET @DB = ISNULL(@DB, CASE WHEN LEFT(@TBL, 1) = '#' THEN 'TEMPDB' ELSE DB_NAME() END)

    --Identifies the columns for the variables (DECLARE and INTO (Next cursor line))

DECLARE @Q NVARCHAR(MAX)
SET @Q = '
WITH X AS (
    SELECT
        A = '', @'' + NAME
        , B = '' '' + type_name(system_type_id)
        , C = CASE
            WHEN type_name(system_type_id) IN (''VARCHAR'', ''CHAR'', ''NCHAR'', ''NVARCHAR'') THEN ''('' + REPLACE(CONVERT(VARCHAR(10), max_length), ''-1'', ''MAX'') + '')''
            WHEN type_name(system_type_id) IN (''DECIMAL'', ''NUMERIC'') THEN ''('' + CONVERT(VARCHAR(10), precision) + '', '' + CONVERT(VARCHAR(10), scale) + '')''
            ELSE ''''
        END
    FROM [' + @DB + '].SYS.COLUMNS C WITH(NOLOCK)
    WHERE OBJECT_ID = OBJECT_ID(''[' + @DB + '].DBO.[' + @TBL + ']'')
    )
SELECT
    @DECLARE = STUFF((SELECT A + B + C FROM X FOR XML PATH('''')), 1, 1, '''')
    , @INTO = ''--Read the next line
FETCH NEXT FROM MY_CURSOR INTO '' + STUFF((SELECT A + '''' FROM X FOR XML PATH('''')), 1, 1, '''')'

DECLARE @DECLARE NVARCHAR(MAX), @INTO NVARCHAR(MAX)
EXEC SP_EXECUTESQL @Q, N'@DECLARE NVARCHAR(MAX) OUTPUT, @INTO NVARCHAR(MAX) OUTPUT', @DECLARE OUTPUT, @INTO OUTPUT

    --PREPARE TO QUERY

SELECT
    @Q = '
DECLARE ' + @DECLARE + '
-- Cursor to scroll through object names
DECLARE MY_CURSOR CURSOR FOR
    SELECT *
    FROM [' + @DB + '].DBO.[' + @TBL + ']

-- Opening Cursor for Reading
OPEN MY_CURSOR
' + @INTO + '

-- Traversing Cursor Lines (While There)
WHILE @@FETCH_STATUS = 0
BEGIN
    ' + @EXECUTE + '
    -- Reading the next line
    ' + @INTO + '
END
FIM_CURSOR:
-- Closing Cursor for Reading
CLOSE MY_CURSOR

DEALLOCATE MY_CURSOR'

EXEC SP_EXECUTESQL @Q --MAGIA
END

How to reload current page in ReactJS?

This is my code .This works for me

componentDidMount(){
        axios.get('http://localhost:5000/supplier').then(
            response => {
                console.log(response)
                this.setState({suppliers:response.data.data})
            }
        )
        .catch(error => {
            console.log(error)
        })
        
    }

componentDidUpdate(){
        this.componentDidMount();
}

window.location.reload(); I think this thing is not good for react js

Java reading a file into an ArrayList?

To share some analysis info. With a simple test how long it takes to read ~1180 lines of values.

If you need to read the data very fast, use the good old BufferedReader FileReader example. It took me ~8ms

The Scanner is much slower. Took me ~138ms

The nice Java 8 Files.lines(...) is the slowest version. Took me ~388ms.

List all files in one directory PHP

Check this out : readdir()

This bit of code should list all entries in a certain directory:

if ($handle = opendir('.')) {

    while (false !== ($entry = readdir($handle))) {

        if ($entry != "." && $entry != "..") {

            echo "$entry\n";
        }
    }

    closedir($handle);
}

Edit: miah's solution is much more elegant than mine, you should use his solution instead.

Remove all child nodes from a parent?

A other users suggested,

.empty()

is good enought, because it removes all descendant nodes (both tag-nodes and text-nodes) AND all kind of data stored inside those nodes. See the JQuery's API empty documentation.

If you wish to keep data, like event handlers for example, you should use

.detach()

as described on the JQuery's API detach documentation.

The method .remove() could be usefull for similar purposes.

How to display image from URL on Android

You can try with Picasso, it's really nice and easy. Don't forget to add the permissions in the manifest.

Picasso.with(context)
                     .load("http://ImageURL")
                     .resize(width,height)
                     .into(imageView );

You can also take a look at a tutorial here : Youtube / Github

How can I split a text file using PowerShell?

Do this:

FILE 1

There's also this quick (and somewhat dirty) one-liner:

    $linecount=0; $i=0; 
    Get-Content .\BIG_LOG_FILE.txt | %
    { 
      Add-Content OUT$i.log "$_"; 
      $linecount++; 
      if ($linecount -eq 3000) {$I++; $linecount=0 } 
    }

You can tweak the number of first lines per batch by changing the hard-coded 3000 value.

Get-Content C:\TEMP\DATA\split\splitme.txt | Select -First 5000 | out-File C:\temp\file1.txt -Encoding ASCII

FILE 2

Get-Content C:\TEMP\DATA\split\splitme.txt | Select -Skip 5000 | Select -First 5000 | out-File C:\temp\file2.txt -Encoding ASCII

FILE 3

Get-Content C:\TEMP\DATA\split\splitme.txt | Select -Skip 10000 | Select -First 5000 | out-File C:\temp\file3.txt -Encoding ASCII

etc…

Why when a constructor is annotated with @JsonCreator, its arguments must be annotated with @JsonProperty?

It is possible to avoid constructor annotations with jdk8 where optionally the compiler will introduce metadata with the names of the constructor parameters. Then with jackson-module-parameter-names module Jackson can use this constructor. You can see an example at post Jackson without annotations

.NET Out Of Memory Exception - Used 1.3GB but have 16GB installed

It looks like you have a 64bit arch, fine -- but a 32bit version of the .NET runtime and/or a 32bit version of Windows.

And as such, the address space available to your process is still the same, it has not changed from your previous setup.

Upgrade to both a 64bit OS and a 64bit .NET version ;)

Each for object?

A javascript Object does not have a standard .each function. jQuery provides a function. See http://api.jquery.com/jQuery.each/ The below should work

$.each(object, function(index, value) {
    console.log(value);
}); 

Another option would be to use vanilla Javascript using the Object.keys() and the Array .map() functions like this

Object.keys(object).map(function(objectKey, index) {
    var value = object[objectKey];
    console.log(value);
});

See https://developer.mozilla.org/nl/docs/Web/JavaScript/Reference/Global_Objects/Object/keys and https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map

These are usually better than using a vanilla Javascript for-loop, unless you really understand the implications of using a normal for-loop and see use for it's specific characteristics like looping over the property chain.

But usually, a for-loop doesn't work better than jQuery or Object.keys().map(). I'll go into two potential issues with using a plain for-loop below.


Right, so also pointed out in other answers, a plain Javascript alternative would be

for(var index in object) { 
    var attr = object[index]; 
}

There are two potential issues with this:

1 . You want to check whether the attribute that you are finding is from the object itself and not from up the prototype chain. This can be checked with the hasOwnProperty function like so

for(var index in object) { 
   if (object.hasOwnProperty(index)) {
       var attr = object[index];
   }
}

See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwnProperty for more information.

The jQuery.each and Object.keys functions take care of this automatically.

2 . Another potential issue with a plain for-loop is that of scope and non-closures. This is a bit complicated, but take for example the following code. We have a bunch of buttons with ids button0, button1, button2 etc, and we want to set an onclick on them and do a console.log like this:

<button id='button0'>click</button>
<button id='button1'>click</button>
<button id='button2'>click</button>

var messagesByButtonId = {"button0" : "clicked first!", "button1" : "clicked middle!", "button2" : "clicked last!"];
for(var buttonId in messagesByButtonId ) { 
   if (messagesByButtonId.hasOwnProperty(buttonId)) {
       $('#'+buttonId).click(function() {
           var message = messagesByButtonId[buttonId];
           console.log(message);
       });
   }
}

If, after some time, we click any of the buttons we will always get "clicked last!" in the console, and never "clicked first!" or "clicked middle!". Why? Because at the time that the onclick function is executed, it will display messagesByButtonId[buttonId] using the buttonId variable at that moment. And since the loop has finished at that moment, the buttonId variable will still be "button2" (the value it had during the last loop iteration), and so messagesByButtonId[buttonId] will be messagesByButtonId["button2"], i.e. "clicked last!".

See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures for more information on closures. Especially the last part of that page that covers our example.

Again, jQuery.each and Object.keys().map() solve this problem automatically for us, because it provides us with a function(index, value) (that has closure) so we are safe to use both index and value and rest assured that they have the value that we expect.

Angular 5 Button Submit On Enter Key Press

You could also use a dummy form arround it like:

<mat-card-footer>
<form (submit)="search(ref, id, forename, surname, postcode)" action="#">
  <button mat-raised-button type="submit" class="successButton" id="invSearch" title="Click to perform search." >Search</button>
</form>
</mat-card-footer>

the search function has to return false to make sure that the action doesn't get executed.
Just make sure the form is focused (should be when you have the input in the form) when you press enter.

How to close the command line window after running a batch file?

%Started Program or Command% | taskkill /F /IM cmd.exe

Example:

notepad.exe | taskkill /F /IM cmd.exe

Server unable to read htaccess file, denying access to be safe

I had the same problem on a rackspeed server after changing the php version in the cpanel. Turned out it also changed the permissions of the folder... I set the permission of the folder to 755 with

chmod 755 folder_name

javac error: Class names are only accepted if annotation processing is explicitly requested

If you compile multiple files in the same line, ensure that you use javac only once and not for every class file.

Incorrect: enter image description here

Correct: enter image description here

How do I set a Windows scheduled task to run in the background?

Assuming the application you are attempting to run in the background is CLI based, you can try calling the scheduled jobs using Hidden Start

Also see: http://www.howtogeek.com/howto/windows/hide-flashing-command-line-and-batch-file-windows-on-startup/

Opening a new tab to read a PDF file

Change the <a> tag like this:

<a href="newsletter_01.pdf" target="_blank">

You can find more about the target attribute here.

How do I add a newline to a TextView in Android?

Try this:

android:text="Lorem Ipsum \nDolor Ait Amet \nLorem Ipsum"

php multidimensional array get values

For people who searched for php multidimensional array get values and actually want to solve problem comes from getting one column value from a 2 dimensinal array (like me!), here's a much elegant way than using foreach, which is array_column

For example, if I only want to get hotel_name from the below array, and form to another array:

$hotels = [
    [
        'hotel_name' => 'Hotel A',
        'info' => 'Hotel A Info',
    ],
    [
        'hotel_name' => 'Hotel B',
        'info' => 'Hotel B Info',
    ]
];

I can do this using array_column:

$hotel_name = array_column($hotels, 'hotel_name');

print_r($hotel_name); // Which will give me ['Hotel A', 'Hotel B']

For the actual answer for this question, it can also be beautified by array_column and call_user_func_array('array_merge', $twoDimensionalArray);

Let's make the data in PHP:

$hotels = [
    [
        'hotel_name' => 'Hotel A',
        'info' => 'Hotel A Info',
        'rooms' => [
            [
                'room_name' => 'Luxury Room',
                'bed' => 2,
                'boards' => [
                    'board_id' => 1,
                    'price' => 200
                ]
            ],
            [
                'room_name' => 'Non Luxy Room',
                'bed' => 4,
                'boards' => [
                    'board_id' => 2,
                    'price' => 150
                ]
            ],
        ]
    ],
    [
        'hotel_name' => 'Hotel B',
        'info' => 'Hotel B Info',
        'rooms' => [
            [
                'room_name' => 'Luxury Room',
                'bed' => 2,
                'boards' => [
                    'board_id' => 3,
                    'price' => 900
                ]
            ],
            [
                'room_name' => 'Non Luxy Room',
                'bed' => 4,
                'boards' => [
                    'board_id' => 4,
                    'price' => 300
                ]
            ],
        ]
    ]
];

And here's the calculation:

$rooms = array_column($hotels, 'rooms');
$rooms = call_user_func_array('array_merge', $rooms);
$boards = array_column($rooms, 'boards');

foreach($boards as $board){
    $board_id = $board['board_id'];
    $price = $board['price'];
    echo "Board ID is: ".$board_id." and price is: ".$price . "<br/>";
}

Which will give you the following result:

Board ID is: 1 and price is: 200
Board ID is: 2 and price is: 150
Board ID is: 3 and price is: 900
Board ID is: 4 and price is: 300

Can I disable a CSS :hover effect via JavaScript?

Actually an other way to solve this could be, overwriting the CSS with insertRule.

It gives the ability to inject CSS rules to an existing/new stylesheet. In my concrete example it would look like this:

//creates a new `style` element in the document
var sheet = (function(){
  var style = document.createElement("style");
  // WebKit hack :(
  style.appendChild(document.createTextNode(""));
  // Add the <style> element to the page
  document.head.appendChild(style);
  return style.sheet;
})();

//add the actual rules to it
sheet.insertRule(
 "ul#mainFilter a:hover { color: #0000EE }" , 0
);

Demo with my 4 years old original example: http://jsfiddle.net/raPeX/21/

How do I implement a callback in PHP?

With PHP 5.3, you can now do this:

function doIt($callback) { $callback(); }

doIt(function() {
    // this will be done
});

Finally a nice way to do it. A great addition to PHP, because callbacks are awesome.

How do you access the element HTML from within an Angular attribute directive?

I suggest using Render, as the ElementRef API doc suggests:

... take a look at Renderer which provides API that can safely be used even when direct access to native elements is not supported. Relying on direct DOM access creates tight coupling between your application and rendering layers which will make it impossible to separate the two and deploy your application into a web worker or Universal.

Always use the Renderer for it will make you code (or library you right) be able to work when using Universal or WebWorkers.

import { Directive, ElementRef, HostListener, Input, Renderer } from '@angular/core';

export class HighlightDirective {
    constructor(el: ElementRef, renderer: Renderer) {
        renderer.setElementProperty(el.nativeElement, 'innerHTML', 'some new value');
    }
}

It doesn't look like Render has a getElementProperty() method though, so I guess we still need to use NativeElement for that part. Or (better) pass the content in as an input property to the directive.

java.lang.NoClassDefFoundError: org.slf4j.LoggerFactory

First, check the dependency hierarchy than to exclude all slf4j jars from other dependencies and add separate slf4j as dependencies.

Convert Object to JSON string

Convert JavaScript object to json data

$("form").submit(function(event){
  event.preventDefault();
  var formData = $("form").serializeArray(); // Create array of object
  var jsonConvertedData = JSON.stringify(formData);  // Convert to json
  consol.log(jsonConvertedData);
});

You can validate json data using http://jsonlint.com

Search and replace part of string in database

I was just faced with a similar problem. I exported the contents of the db into one sql file and used TextEdit to find and replace everything I needed. Simplicity ftw!

ReactJS Two components communicating

There is such possibility even if they are not Parent - Child relationship - and that's Flux. There is pretty good (for me personally) implementation for that called Alt.JS (with Alt-Container).

For example you can have Sidebar that is dependent on what is set in component Details. Component Sidebar is connected with SidebarActions and SidebarStore, while Details is DetailsActions and DetailsStore.

You could use then AltContainer like that

<AltContainer stores={{
                    SidebarStore: SidebarStore
                }}>
                    <Sidebar/>
</AltContainer>

{this.props.content}

Which would keep stores (well I could use "store" instead of "stores" prop). Now, {this.props.content} CAN BE Details depending on the route. Lets say that /Details redirect us to that view. Details would have for example a checkbox that would change Sidebar element from X to Y if it would be checked.

Technically there is no relationship between them and it would be hard to do without flux. BUT WITH THAT it is rather easy.

Now let's get to DetailsActions. We will create there

class SiteActions {
constructor() {
    this.generateActions(
        'setSiteComponentStore'
    );
}

setSiteComponent(value) {
    this.dispatch({value: value});
}
}

and DetailsStore

class SiteStore {
constructor() {
    this.siteComponents = {
        Prop: true
    };

    this.bindListeners({
        setSiteComponent: SidebarActions.COMPONENT_STATUS_CHANGED
    })
}

setSiteComponent(data) {
    this.siteComponents.Prop = data.value;
}
}

And now, this is the place where magic begin.

As You can see there is bindListener to SidebarActions.ComponentStatusChanged which will be used IF setSiteComponent will be used.

now in SidebarActions

    componentStatusChanged(value){
    this.dispatch({value: value});
}

We have such thing. It will dispatch that object on call. And it will be called if setSiteComponent in store will be used (that you can use in component for example during onChange on Button ot whatever)

Now in SidebarStore we will have

    constructor() {
    this.structures = [];

    this.bindListeners({
        componentStatusChanged: SidebarActions.COMPONENT_STATUS_CHANGED
    })
}

    componentStatusChanged(data) {
    this.waitFor(DetailsStore);

    _.findWhere(this.structures[0].elem, {title: 'Example'}).enabled = data.value;
}

Now here you can see, that it will wait for DetailsStore. What does it mean? more or less it means that this method need to wait for DetailsStoreto update before it can update itself.

tl;dr One Store is listening on methods in a store, and will trigger an action from component action, which will update its own store.

I hope it can help you somehow.

How to repair COMException error 80040154?

I had the same issue in a Windows Service. All keys where in the right place in the registry. The build of the service was done for x86 and I still got the exception. I found out about CorFlags.exe

Run this on your service.exe without flags to verify if you run under 32 bit. If not run it with the flag /32BIT+ /Force (Force only for signed assemblies)

If you have UAC turned you can get the following error: corflags : error CF001 : Could not open file for writing Give the user full control on the assemblies.

Console output

How to create Select List for Country and States/province in MVC

Designing You Model:

Public class ModelName
{
    ...// Properties
    public IEnumerable<SelectListItem> ListName { get; set; }
}

Prepare and bind List to Model in Controller :

    public ActionResult Index(ModelName model)
    {
        var items = // Your List of data
        model.ListName = items.Select(x=> new SelectListItem() {
                    Text = x.prop,
                    Value = x.prop2
               });
    }

In You View :

@Html.DropDownListFor(m => Model.prop2,Model.ListName)

Check if string ends with one of the strings from a list

another way which can return the list of matching strings is

sample = "alexis has the control"
matched_strings = filter(sample.endswith, ["trol", "ol", "troll"])
print matched_strings
['trol', 'ol']

Cannot read property length of undefined

The id of the input seems is not WallSearch. Maybe you're confusing that name and id. They are two different properties. name is used to define the name by which the value is posted, while id is the unique identification of the element inside the DOM.

Other possibility is that you have two elements with the same id. The browser will pick any of these (probably the last, maybe the first) and return an element that doesn't support the value property.

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

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

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

To open a Developer Command Prompt window

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

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

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

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

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

To run vcvarsall.bat

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

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

    vcvarsall x86
    

From the article, the possible arguments are the following:

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

Javascript: The prettiest way to compare one value against multiple values

You can use a switch:

switch (foobar) {
  case foo:
  case bar:
    // do something
}