Programs & Examples On #Nsindexpath

The NSIndexPath class represents the path to a specific node in a tree of nested array collections in Objective-C. This path is known as an index path.

How can I get a uitableViewCell by indexPath?

You can use the following code to get last cell.

UITableViewCell *cell = [tableView cellForRowAtIndexPath:lastIndexPath];

How to create NSIndexPath for TableView

For Swift 3 it's now: IndexPath(row: rowIndex, section: sectionIndex)

Refresh certain row of UITableView based on Int in Swift

For a soft impact animation solution:

Swift 3:

let indexPath = IndexPath(item: row, section: 0)
tableView.reloadRows(at: [indexPath], with: .fade)

Swift 2.x:

let indexPath = NSIndexPath(forRow: row, inSection: 0)
tableView.reloadRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)

This is another way to protect the app from crashing:

Swift 3:

let indexPath = IndexPath(item: row, section: 0)
if let visibleIndexPaths = tableView.indexPathsForVisibleRows?.index(of: indexPath as IndexPath) {
    if visibleIndexPaths != NSNotFound {
        tableView.reloadRows(at: [indexPath], with: .fade)

Swift 2.x:

let indexPath = NSIndexPath(forRow: row, inSection: 0)
if let visibleIndexPaths = tableView.indexPathsForVisibleRows?.indexOf(indexPath) {
   if visibleIndexPaths != NSNotFound {
      tableView.reloadRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)

Git pull command from different user

Your question is a little unclear, but if what you're doing is trying to get your friend's latest changes, then typically what your friend needs to do is to push those changes up to a remote repo (like one hosted on GitHub), and then you fetch or pull those changes from the remote:

  1. Your friend pushes his changes to GitHub:

    git push origin <branch>
  2. Clone the remote repository if you haven't already:

    git clone https://[email protected]/abc/theproject.git
  3. Fetch or pull your friend's changes (unnecessary if you just cloned in step #2 above):

    git fetch origin
    git merge origin/<branch>

    Note that git pull is the same as doing the two steps above:

    git pull origin <branch>

See Also

python catch exception and continue try block

one way you could handle this is with a generator. Instead of calling the function, yield it; then whatever is consuming the generator can send the result of calling it back into the generator, or a sentinel if the generator failed: The trampoline that accomplishes the above might look like so:

def consume_exceptions(gen):
    action = next(gen)
    while True:
            result = action()
        except Exception:
            # if the action fails, send a sentinel
            result = None

            action = gen.send(result)
        except StopIteration:
            # if the generator is all used up, result is the return value.
            return result

a generator that would be compatible with this would look like this:

def do_smth1():
    1 / 0

def do_smth2():
    print "YAY"

def do_many_things():
    a = yield do_smth1
    b = yield do_smth2
    yield "Done"
>>> consume_exceptions(do_many_things())

Note that do_many_things() does not call do_smth*, it just yields them, and consume_exceptions calls them on its behalf

On Duplicate Key Update same as insert

There is a MySQL specific extension to SQL that may be what you want - REPLACE INTO

However it does not work quite the same as 'ON DUPLICATE UPDATE'

  1. It deletes the old row that clashes with the new row and then inserts the new row. So long as you don't have a primary key on the table that would be fine, but if you do, then if any other table references that primary key

  2. You can't reference the values in the old rows so you can't do an equivalent of

    INSERT INTO mytable (id, a, b, c) values ( 1, 2, 3, 4) 
    id=1, a=2, b=3, c=c + 1;

I'd like to use the work around to get the ID to!

That should work — last_insert_id() should have the correct value so long as your primary key is auto-incrementing.

However as I said, if you actually use that primary key in other tables, REPLACE INTO probably won't be acceptable to you, as it deletes the old row that clashed via the unique key.

Someone else suggested before you can reduce some typing by doing:

INSERT INTO `tableName` (`a`,`b`,`c`) VALUES (1,2,3)

How to solve 'Redirect has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header'?

You can solve this temporarily by using the Firefox add-on, CORS Everywhere. Just open Firefox, press Ctrl+Shift+A , search the add-on and add it!

Casting string to enum

As an extra, you can take the Enum.Parse answers already provided and put them in an easy-to-use static method in a helper class.

public static T ParseEnum<T>(string value)
    return (T)Enum.Parse(typeof(T), value, ignoreCase: true);

And use it like so:

   Content = ParseEnum<ContentEnum>(fileContentMessage);

Especially helpful if you have lots of (different) Enums to parse.

How to use systemctl in Ubuntu 14.04

I just encountered this problem myself and found that Ubuntu 14.04 uses Upstart instead of Systemd, so systemctl commands will not work. This changed in 15.04, so one way around this would be to update your ubuntu install.

If this is not an option for you (it's not for me right now), you need to find the Upstart command that does what you need to do.

For enable, the generic looks to be the following:

update-rc.d <service> enable

Link to Ubuntu documentation:

How to launch Safari and open URL from iOS app

Try this:

NSString *URL = @"";
if([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:URL]])
     [[UIApplication sharedApplication] openURL:[NSURL URLWithString:URL]];

how to set default culture info for entire c# application

With 4.0, you will need to manage this yourself by setting the culture for each thread as Alexei describes. But with 4.5, you can define a culture for the appdomain and that is the preferred way to handle this. The relevant apis are CultureInfo.DefaultThreadCurrentCulture and CultureInfo.DefaultThreadCurrentUICulture.

Python Math - TypeError: 'NoneType' object is not subscriptable

lista = list.sort(lista)

This should be


The .sort() method is in-place, and returns None. If you want something not in-place, which returns a value, you could use

sorted_list = sorted(lista)

Aside #1: please don't call your lists list. That clobbers the builtin list type.

Aside #2: I'm not sure what this line is meant to do:

print str("value 1a")+str(" + ")+str("value 2")+str(" = ")+str("value 3a ")+str("value 4")+str("\n")

is it simply

print "value 1a + value 2 = value 3a value 4"

? In other words, I don't know why you're calling str on things which are already str.

Aside #3: sometimes you use print("something") (Python 3 syntax) and sometimes you use print "something" (Python 2). The latter would give you a SyntaxError in py3, so you must be running 2.*, in which case you probably don't want to get in the habit or you'll wind up printing tuples, with extra parentheses. I admit that it'll work well enough here, because if there's only one element in the parentheses it's not interpreted as a tuple, but it looks strange to the pythonic eye..

The exception TypeError: 'NoneType' object is not subscriptable happens because the value of lista is actually None. You can reproduce TypeError that you get in your code if you try this at the Python command line:


The reason that lista gets set to None is because the return value of list.sort() is None... it does not return a sorted copy of the original list. Instead, as the documentation points out, the list gets sorted in-place instead of a copy being made (this is for efficiency reasons).

If you do not want to alter the original version you can use

other_list = sorted(lista)

Create a one to many relationship using SQL Server

This is how I usually do it (sql server).

Create Table Master (
MasterID int identity(1,1) primary key,
Stuff varchar(10)
Create Table Detail (
DetailID int identity(1,1) primary key,
MasterID int references Master, --use 'references'
Stuff varchar(10))
Insert into Master values('value')
--(1 row(s) affected)
Insert into Detail values (1, 'Value1') -- Works
--(1 row(s) affected)
insert into Detail values (2, 'Value2') -- Fails
--Msg 547, Level 16, State 0, Line 2
--The INSERT statement conflicted with the FOREIGN KEY constraint "FK__Detail__MasterID__0C70CFB4". 
--The conflict occurred in database "Play", table "dbo.Master", column 'MasterID'.
--The statement has been terminated.

As you can see the second insert into the detail fails because of the foreign key. Here's a good weblink that shows various syntax for defining FK during table creation or after.

get dictionary value by key

          private void button2_Click(object sender, EventArgs e)
                Dictionary<string, string> Data_Array = new Dictionary<string, string>();
                Data_Array.Add("XML_File", "Settings.xml");

          static void XML_Array(Dictionary<string, string> Data_Array)
                String xmlfile = Data_Array["XML_File"];

sql select with column name like

Thank you @Blorgbeard for the genious idea.

By the way Blorgbeard's query was not working for me so I edited it:

DECLARE @Table_Name as VARCHAR(50) SET @Table_Name = 'MyTable'          -- put here you table name
DECLARE @Column_Like as VARCHAR(20) SET @Column_Like = '%something%'    -- put here you element
DECLARE @sql NVARCHAR(MAX) SET @sql = 'select '

SELECT @sql = @sql + '[' + + '],'
FROM sys.columns 
JOIN sys.tables ON sys.columns.object_id = tables.object_id
WHERE like @Column_Like
and = @Table_Name

SET @sql = left(@sql,len(@sql)-1) -- remove trailing comma
SET @sql = @sql + ' from ' + @Table_Name

EXEC sp_executesql @sql

What is an AssertionError? In which case should I throw it from my own code?

The meaning of an AssertionError is that something happened that the developer thought was impossible to happen.

So if an AssertionError is ever thrown, it is a clear sign of a programming error.

"ImportError: No module named" when trying to run Python script

I found yet another source of this discrepancy:

I have ipython installed both locally and in commonly in virtualenvs. My problem was that, inside a newly made virtualenv with ipython, the system ipython was picked up, which was a different version than the python and ipython in the virtualenv (a 2.7.x vs. a 3.5.x), and hilarity ensued.

I think the smart thing to do whenever installing something that will have a binary in yourvirtualenv/bin is to immediately run rehash or similar for whatever shell you are using so that the correct python/ipython gets picked up. (Gotta check if there are suitable pip post-install hooks...)

Warning: The method assertEquals from the type Assert is deprecated

this method also encounter a deprecate warning:

org.junit.Assert.assertEquals(float expected,float actual) //deprecated

It is because currently junit prefer a third parameter rather than just two float variables input.

The third parameter is delta:

public static void assertEquals(double expected,double actual,double delta) //replacement

this is mostly used to deal with inaccurate Floating point calculations

for more information, please refer this problem: Meaning of epsilon argument of assertEquals for double values

How do I fix PyDev "Undefined variable from import" errors?

I was having a similar problem with an Eclipse/PyDev project. In this project the root directory of the python code was a sub-directory of the project.

--> MyProject
 + --> src         Root of python code
   + --> module1     A module 
   + --> module2     Another module
 + --> docs
 + --> test

When the project was debugged or run everything was fine as the working directory was set to the correct place. However the PyDev code analysis was failing to find any imports from module1 or module2.

Solution was to edit the project properties -> PyDev - PYTHONPATH section and remove /MyProject from the source folders tab and add /MyProject/src to it instead.

Else clause on Python while statement

Else is executed if while loop did not break.

I kinda like to think of it with a 'runner' metaphor.

The "else" is like crossing the finish line, irrelevant of whether you started at the beginning or end of the track. "else" is only not executed if you break somewhere in between.

runner_at = 0 # or 10 makes no difference, if unlucky_sector is not 0-10
unlucky_sector = 6
while runner_at < 10:
    print("Runner at: ", runner_at)
    if runner_at == unlucky_sector:
        print("Runner fell and broke his foot. Will not reach finish.")
    runner_at += 1
    print("Runner has finished the race!") # Not executed if runner broke his foot.

Main use cases is using this breaking out of nested loops or if you want to run some statements only if loop didn't break somewhere (think of breaking being an unusual situation).

For example, the following is a mechanism on how to break out of an inner loop without using variables or try/catch:

for i in [1,2,3]:
    for j in ['a', 'unlucky', 'c']:
        print(i, j)
        if j == 'unlucky':
        continue  # Only executed if inner loop didn't break.
    break         # This is only reached if inner loop 'breaked' out since continue didn't run. 

# 1 a
# 1 b
# Finished

Validate phone number using angular js

Use ng-pattern, in this example you can validate a simple patern with 10 numbers, when the patern is not matched ,the message is show and the button is disabled.

 <form  name="phoneNumber">

        <label for="numCell" class="text-strong">Phone number</label>

        <input id="numCell" type="text" name="inputCelular"  ng-model="phoneNumber" 
            class="form-control" required  ng-pattern="/^[0-9]{10,10}$/"></input>
        <div class="alert-warning" ng-show="phoneNumber.inputCelular.$error.pattern">
            <p> write a phone number</p>

    <button id="button"  class="btn btn-success" click-once ng-disabled="!phoneNumber.$valid" ng-click="callDigitaliza()">Buscar</button>

Also you can use another complex patern like

^+?\d{1,3}?[- .]?(?(?:\d{2,3}))?[- .]?\d\d\d[- .]?\d\d\d\d$

, for more complex phone numbers

Get exit code of a background process

Another solution is to monitor processes via the proc filesystem (safer than ps/grep combo); when you start a process it has a corresponding folder in /proc/$pid, so the solution could be

doSomething &
local pid=$!
while [ -d /proc/$pid ]; do # While directory exists, the process is running
else # when directory is removed from /proc, process has ended
    wait $pid
    local exit_status=$?

Now you can use the $exit_status variable however you like.

Change icons of checked and unchecked for Checkbox for Android

One alternative would be to use a drawable/textview instead of a checkbox and manipulate it accordingly. I have used this method to have my own checked and unchecked images for a task application.

FIFO class in Java

You can use LinkedBlockingQueue I use it in my projects. It's part of standard java and quite easy to use

Invariant Violation: Could not find "store" in either the context or props of "Connect(SportsDatabase)"

in my case just

const myReducers = combineReducers({
  user: UserReducer

const store: any = createStore(

shallow(<Login />, { context: { store } });

Using PHP Replace SPACES in URLS with %20

I think you must use rawurlencode() instead urlencode() for your purpose.


$image = 'some images.jpg';
$url   = ''

With urlencode($str) will result

echo $url.urlencode($image); //

its not change to %20 at all

but with rawurlencode($image) will produce

echo $url.rawurlencode(basename($image)); //

iPhone is not available. Please reconnect the device

Follow these steps:

  1. Check your iOS Version from (Settings ? General ? About ? Software Version) and get the device support file from the link below:

  2. Next, unzip the files and place them at the following location:

    Applications ? Xcode ? right click ? Show Package Contents ? Contents ? Developer ? Platforms ? iPhoneOS.platform ? DeviceSupport

  3. Restart Xcode

How to verify static void method has been called with power mockito

If you are mocking the behavior (with something like doNothing()) there should really be no need to call to verify*(). That said, here's my stab at re-writing your test method:

public class InternalServiceTest { //Note the renaming of the test class.
   public void testProcessOrder() {
        InternalService is = new InternalService();
        Order order = mock(Order.class);

        //Mock Behavior
        doNothing().when(InternalUtils.class); //This is the preferred way
                                               //to mock static void methods.
        InternalUtils.sendEmail(anyString(), anyString(), anyString(), anyString());


        verifyStatic(InternalUtils.class); //Similar to how you mock static methods
                                           //this is how you verify them.
        InternalUtils.sendEmail(anyString(), anyString(), anyString(), anyString());

I grouped into four sections to better highlight what is going on:

1. Variables

I choose to declare any instance variables / method arguments / mock collaborators here. If it is something used in multiple tests, consider making it an instance variable of the test class.

2. Mock Behavior

This is where you define the behavior of all of your mocks. You're setting up return values and expectations here, prior to executing the code under test. Generally speaking, if you set the mock behavior here you wouldn't need to verify the behavior later.

3. Execute

Nothing fancy here; this just kicks off the code being tested. I like to give it its own section to call attention to it.

4. Verify

This is when you call any method starting with verify or assert. After the test is over, you check that the things you wanted to have happen actually did happen. That is the biggest mistake I see with your test method; you attempted to verify the method call before it was ever given a chance to run. Second to that is you never specified which static method you wanted to verify.

Additional Notes

This is mostly personal preference on my part. There is a certain order you need to do things in but within each grouping there is a little wiggle room. This helps me quickly separate out what is happening where.

I also highly recommend going through the examples at the following sites as they are very robust and can help with the majority of the cases you'll need:

Does Python have a toString() equivalent, and can I convert a db.Model element to String?

You should define the __unicode__ method on your model, and the template will call it automatically when you reference the instance.

Reminder - \r\n or \n\r?

From Wikipedia (you can read which is correct for your OS at that article):

Systems based on ASCII or a compatible character set use either LF (Line feed, '\n', 0x0A, 10 in decimal) or CR (Carriage return, '\r', 0x0D, 13 in decimal) individually, or CR followed by LF (CR+LF, '\r\n', 0x0D0A).

UITableView - change section header color

If anyone needs swift, keeps title:

override func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
    let view = UIView(frame: CGRect(x: 0,y: 0,width: self.tableView.frame.width, height: 30))
    view.backgroundColor = UIColor.redColor()
    let label = UILabel(frame: CGRect(x: 15,y: 5,width: 200,height: 25))
    label.text = self.tableView(tableView, titleForHeaderInSection: section)
    return view

Best way to save a trained model in PyTorch?

A common PyTorch convention is to save models using either a .pt or .pth file extension.

Save/Load Entire Model Save:

path = "username/directory/lstmmodelgpu.pth", path)


Model class must be defined somewhere

model = torch.load(PATH)

imagecreatefromjpeg and similar functions are not working in PHP

As mentioned before, you might need GD library installed.

On a shell, check your php version first:
php -v

Then install accordingly. In my system (Linux-Ubuntu) it's php version 7.0:
sudo apt-get install php7.0-gd

Restart your webserver:
systemctl restart apache2

You should now have GD library installed and enabled.

What are the differences between .gitignore and .gitkeep?

.gitkeep isn’t documented, because it’s not a feature of Git.

Git cannot add a completely empty directory. People who want to track empty directories in Git have created the convention of putting files called .gitkeep in these directories. The file could be called anything; Git assigns no special significance to this name.

There is a competing convention of adding a .gitignore file to the empty directories to get them tracked, but some people see this as confusing since the goal is to keep the empty directories, not ignore them; .gitignore is also used to list files that should be ignored by Git when looking for untracked files.

Removing time from a Date object?

What you want is impossible.

A Date object represents an "absolute" moment in time. You cannot "remove the time part" from it. When you print a Date object directly with System.out.println(date), it will always be formatted in a default format that includes the time. There is nothing you can do to change that.

Instead of somehow trying to use class Date for something that it was not designed for, you should look for another solution. For example, use SimpleDateFormat to format the date in whatever format you want.

The Java date and calendar APIs are unfortunately not the most well-designed classes of the standard Java API. There's a library called Joda-Time which has a much better and more powerful API.

Joda-Time has a number of special classes to support dates, times, periods, durations, etc. If you want to work with just a date without a time, then Joda-Time's LocalDate class would be what you'd use.

How to list all installed packages and their versions in Python?

My take:

#!/usr/bin/env python3

import pkg_resources

dists = [str(d).replace(" ","==") for d in pkg_resources.working_set]
for i in dists:

How to remove the default arrow icon from a dropdown list (select element)?

As I answered in Remove Select arrow on IE

In case you want to use the class and pseudo-class:

.simple-control is your css class

:disabled is pseudo class

         /*For FireFox*/
        -webkit-appearance: none;
        /*For Chrome*/
        -moz-appearance: none;

/*For IE10+*/
select:disabled.simple-control::-ms-expand {
        display: none;

Android add placeholder text to EditText

This how to make input password that has hint which not converted to * !!.

On XML :

android:hint="Input Password !."

thanks to : mango and rjrjr for the insight :D.

How can I link to a specific glibc version?

You are correct in that glibc uses symbol versioning. If you are curious, the symbol versioning implementation introduced in glibc 2.1 is described here and is an extension of Sun's symbol versioning scheme described here.

One option is to statically link your binary. This is probably the easiest option.

You could also build your binary in a chroot build environment, or using a glibc-new => glibc-old cross-compiler.

According to the blog post Linking to Older Versioned Symbols (glibc), it is possible to to force any symbol to be linked against an older one so long as it is valid by using the same .symver pseudo-op that is used for defining versioned symbols in the first place. The following example is excerpted from the blog post.

The following example makes use of glibc’s realpath, but makes sure it is linked against an older 2.2.5 version.

#include <limits.h>
#include <stdlib.h>
#include <stdio.h>

__asm__(".symver realpath,realpath@GLIBC_2.2.5");
int main()
    const char* unresolved = "/lib64";
    char resolved[PATH_MAX+1];

    if(!realpath(unresolved, resolved))
        { return 1; }

    printf("%s\n", resolved);

    return 0;

Best way to convert an ArrayList to a string

If you don't want the last \t after the last element, you have to use the index to check, but remember that this only "works" (i.e. is O(n)) when lists implements the RandomAccess.

List<String> list = new ArrayList<String>();

StringBuilder sb = new StringBuilder(list.size() * apprAvg); // every apprAvg > 1 is better than none
for (int i = 0; i < list.size(); i++) {
    if (i < list.size() - 1) {

SQLException: No suitable driver found for jdbc:derby://localhost:1527

If your using embedded Derby you need Derby.jar in your classpath.

Is there an online application that automatically draws tree structures for phrases/sentences?

In short, yes. I assume you're looking to parse English: for that you can use the Link Parser from Carnegie Mellon.

It is important to remember that there are many theories of syntax, that can give completely different-looking phrase structure trees; further, the trees are different for each language, and tools may not exist for those languages.

As a note for the future: if you need a sentence parsed out and tag it as linguistics (and syntax or whatnot, if that's available), someone can probably parse it out for you and guide you through it.

Why do we check up to the square root of a prime number to determine if it is prime?

Yes, as it was properly explained above, it's enough to iterate up to Math.floor of a number's square root to check its primality (because sqrt covers all possible cases of division; and Math.floor, because any integer above sqrt will already be beyond its range).

Here is a runnable JavaScript code snippet that represents a simple implementation of this approach – and its "runtime-friendliness" is good enough for handling pretty big numbers (I tried checking both prime and not prime numbers up to 10**12, i.e. 1 trillion, compared results with the online database of prime numbers and encountered no errors or lags even on my cheap phone):

function isPrime(num) {
  if (num % 2 === 0 || num < 3 || !Number.isInteger(num)) {
    return num === 2;
  } else {
    const sqrt = Math.floor(Math.sqrt(num));
    for (let i = 3; i <= sqrt; i += 2) {
      if (num % i === 0) {
        return false;
    return true;
<label for="inp">Enter a number and click "Check!":</label><br>
<input type="number" id="inp"></input>
<button onclick="alert(isPrime(+document.getElementById('inp').value) ? 'Prime' : 'Not prime')" type="button">Check!</button>

Cannot find control with name: formControlName in angular reactive form

you're missing group nested controls with formGroupName directive

<div class="panel-body" formGroupName="address">
  <div class="form-group">
    <label for="address" class="col-sm-3 control-label">Business Address</label>
    <div class="col-sm-8">
      <input type="text" class="form-control" formControlName="street" placeholder="Business Address">
  <div class="form-group">
    <label for="website" class="col-sm-3 control-label">Website</label>
    <div class="col-sm-8">
      <input type="text" class="form-control" formControlName="website" placeholder="website">
  <div class="form-group">
    <label for="telephone" class="col-sm-3 control-label">Telephone</label>
    <div class="col-sm-8">
      <input type="text" class="form-control" formControlName="mobile" placeholder="telephone">
  <div class="form-group">
    <label for="email" class="col-sm-3 control-label">Email</label>
    <div class="col-sm-8">
      <input type="text" class="form-control" formControlName="email" placeholder="email">
  <div class="form-group">
    <label for="page id" class="col-sm-3 control-label">Facebook Page ID</label>
    <div class="col-sm-8">
      <input type="text" class="form-control" formControlName="pageId" placeholder="facebook page id">
  <div class="form-group">
    <label for="about" class="col-sm-3  control-label"></label>
    <div class="col-sm-3">
      <!--span class="btn btn-success form-control" (click)="openGeneralPanel()">Back</span-->
    <label for="about" class="col-sm-2  control-label"></label>
    <div class="col-sm-3">
      <button class="btn btn-success form-control" [disabled]="companyCreatForm.invalid" (click)="openContactInfo()">Continue</button>

How do you attach and detach from Docker's process?

If you just want to make some modification to files or inspect processes, here's one another solution you probably want.

You could run the following command to execute a new process from the existing container:

sudo docker exec -ti [CONTAINER-ID] bash

will start a new process with bash shell, and you could escape from it by Ctrl+C directly, it won't affect the original process.

Change the color of a checked menu item in a navigation drawer

Step 1: Build a checked/unchecked selector:


<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="">
    <item android:color="@color/yellow" android:state_checked="true" />
    <item android:color="@color/white" android:state_checked="false" />

Step 2: use the xml attribute app:itemTextColor within NavigationView widget for selecting the text color.

    app:menu="@menu/navigation_menu" />

Step 3:
For some reason when you hit an item from the NavigationView menu, it doesn't consider this as a button check. So you need to manually get the selected item checked and clear the previously selected item. Use below listener to do that

public boolean onNavigationItemSelected(@NonNull MenuItem item) {

    int id = item.getItemId();

    // remove all colors of the items to the `unchecked` state of the selector

    // check the selected item to change its color set by the `checked` state of the selector

    switch (item.getItemId()) {

    return true;

private void removeColor(NavigationView view) {
    for (int i = 0; i < view.getMenu().size(); i++) {
        MenuItem item = view.getMenu().getItem(i);

Step 4:
To change icon color, use the app:iconTint attribute in the NavigationView menu items, and set to the same selector.

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android=""
        android:title="My Account"
        app:iconTint="@drawable/selector" />
        app:iconTint="@drawable/selector" />

        android:title="Log Out"
        app:iconTint="@drawable/selector" />


Remove all special characters with RegExp

why dont you do something like:

re = /^[a-z0-9 ]$/i;
var isValid = re.test(yourInput);

to check if your input contain any special char

How can I get a List from some class properties with Java 8 Stream?

You can use map :

List<String> names =


In order to combine the Lists of friend names, you need to use flatMap :

List<String> friendNames =

Java verify void method calls n times with Mockito

The necessary method is Mockito#verify:

public static <T> T verify(T mock,
                           VerificationMode mode)

mock is your mocked object and mode is the VerificationMode that describes how the mock should be verified. Possible modes are:

verify(mock, times(5)).someMethod("was called five times");
verify(mock, never()).someMethod("was never called");
verify(mock, atLeastOnce()).someMethod("was called at least once");
verify(mock, atLeast(2)).someMethod("was called at least twice");
verify(mock, atMost(3)).someMethod("was called at most 3 times");
verify(mock, atLeast(0)).someMethod("was called any number of times"); // useful with captors
verify(mock, only()).someMethod("no other method has been called on the mock");

You'll need these static imports from the Mockito class in order to use the verify method and these verification modes:

import static org.mockito.Mockito.atLeast;
import static org.mockito.Mockito.atLeastOnce;
import static org.mockito.Mockito.atMost;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.only;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;

So in your case the correct syntax will be:

Mockito.verify(mock, times(4)).send()

This verifies that the method send was called 4 times on the mocked object. It will fail if it was called less or more than 4 times.

If you just want to check, if the method has been called once, then you don't need to pass a VerificationMode. A simple

verify(mock).someMethod("was called once");

would be enough. It internally uses verify(mock, times(1)).someMethod("was called once");.

It is possible to have multiple verification calls on the same mock to achieve a "between" verification. Mockito doesn't support something like this verify(mock, between(4,6)).someMethod("was called between 4 and 6 times");, but we can write

verify(mock, atLeast(4)).someMethod("was called at least four times ...");
verify(mock, atMost(6)).someMethod("... and not more than six times");

instead, to get the same behaviour. The bounds are included, so the test case is green when the method was called 4, 5 or 6 times.

How do I append text to a file?

Other possible way is:

echo "text" | tee -a filename >/dev/null

The -a will append at the end of the file.

If needing sudo, use:

echo "text" | sudo tee -a filename >/dev/null

How to check if keras tensorflow backend is GPU or CPU version?

Also you can check using Keras backend function:

from keras import backend as K

I test this on Keras (2.1.1)

Convert Decimal to Varchar

I think CAST(ROUND(yourColumn,2) as varchar) should do the job.

But why do you want to do this presentational formatting in T-SQL?

How can I use SUM() OVER()

Query would be like this:

SELECT ID, AccountID, Quantity, 
       SUM(Quantity) OVER (PARTITION BY AccountID ) AS TopBorcT 

       FROM #Empl ORDER BY AccountID

Partition by works like group by. Here we are grouping by AccountID so sum would be corresponding to AccountID.

First first case, AccountID = 1 , then sum(quantity) = 10 + 5 + 2 => 17 & For AccountID = 2, then sum(Quantity) = 7+3 => 10

so result would appear like attached snapshot.

Does a valid XML file require an XML declaration?

It is only required if you aren't using the default values for version and encoding (which you are in that example).

How to use RANK() in SQL Server

SELECT contendernum,totals, RANK() OVER (ORDER BY totals ASC) AS xRank FROM
SELECT ContenderNum ,SUM(Criteria1+Criteria2+Criteria3+Criteria4) AS totals
FROM dbo.Cat1GroupImpersonation
 GROUP BY ContenderNum
) AS a

Cause of a process being a deadlock victim

The answers here are worth a try, but you should also review your code. Specifically have a read of Polyfun's answer here: How to get rid of deadlock in a SQL Server 2005 and C# application?

It explains the concurrency issue, and how the usage of "with (updlock)" in your queries might correct your deadlock situation - depending really on exactly what your code is doing. If your code does follow this pattern, this is likely a better fix to make, before resorting to dirty reads, etc.

How can we redirect a Java program console output to multiple files?

You can set the output of System.out programmatically by doing:

System.setOut(new PrintStream(new BufferedOutputStream(new FileOutputStream("/location/to/console.out")), true));


Due to the fact that this solution is based on a PrintStream, we can enable autoFlush, but according to the docs:

autoFlush - A boolean; if true, the output buffer will be flushed whenever a byte array is written, one of the println methods is invoked, or a newline character or byte ('\n') is written

So if a new line isn't written, remember to System.out.flush() manually.

(Thanks Robert Tupelo-Schneck)

How to restart counting from 1 after erasing table in MS Access?

In addition to all the concerns expressed about why you give a rat's ass what the ID value is (all are correct that you shouldn't), let me add this to the mix:

If you've deleted all the records from the table, compacting the database will reset the seed value back to its original value.

For a table where there are still records, and you've inserted a value into the Autonumber field that is lower than the highest value, you have to use @Remou's method to reset the seed value. This also applies if you want to reset to the Max+1 in a table where records have been deleted, e.g., 300 records, last ID of 300, delete 201-300, compact won't reset the counter (you have to use @Remou's method -- this was not the case in earlier versions of Jet, and, indeed, in early versions of Jet 4, the first Jet version that allowed manipulating the seed value programatically).

AngularJS documentation?

Here's the calling order:

  1. app.config()
  3. directive's compile functions (if they are found in the dom)
  4. app.controller()
  5. directive's link functions (again, if found)

Here's a simple demo where you can watch each one executing (and experiment if you'd like).

From Angular's module docs:

Run blocks - get executed after the injector is created and are used to kickstart the application. Only instances and constants can be injected into run blocks. This is to prevent further system configuration during application run time.

Run blocks are the closest thing in Angular to the main method. A run block is the code which needs to run to kickstart the application. It is executed after all of the services have been configured and the injector has been created. Run blocks typically contain code which is hard to unit-test, and for this reason should be declared in isolated modules, so that they can be ignored in the unit-tests.

One situation where run blocks are used is during authentications.

Create a branch in Git from another branch

Git 2.23 introduces git switch and git restore to split the responsibilities of git checkout

Creating a new branch from an existing branch as of git 2.23:

git switch -c my-new-branch

Switched to a new branch 'my-new-branch'

  • -c is short for --create and replaces the well-known git checkout -b

Take a look at this Github blog post explaining the changes in greater detail:

Git 2.23 brings a new pair of experimental commands to the suite of existing ones: git switch and git restore. These two are meant to eventually provide a better interface for the well-known git checkout. The new commands intend to each have a clear separation, neatly divvying up what the many responsibilities of git checkout

How to get just the parent directory name of a specific file

For Kotlin :

 fun getFolderName() {
            val uri: Uri
            val cursor: Cursor?
            uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI
            val projection = arrayOf(MediaStore.Audio.AudioColumns.DATA)
            cursor = requireActivity().contentResolver.query(uri, projection, null, null, null)
            if (cursor != null) {
                column_index_data = cursor.getColumnIndexOrThrow(MediaStore.Audio.AudioColumns.DATA)
            while (cursor!!.moveToNext()) {
                absolutePathOfImage = cursor.getString(column_index_data)
                val fileName: String = File(absolutePathOfImage)

pip install access denied on Windows

  1. Open Command Prompt as Administrator.

  2. To Install any Python Package use this command including --user.

pip install --ignore-installed --upgrade --user <packagename>

Django - Reverse for '' not found. '' is not a valid view function or pattern name

Add store name to template like {% url 'app_name:url_name' %}

App_name = store

In, path('search', views.searched, name="searched"),

<form action="{% url 'store:searched' %}" method="POST">

browser.msie error after update to jQuery 1.9.1

Using this:

if (navigator.userAgent.match("MSIE")) {}

How to parse the AndroidManifest.xml file inside an .apk package

@Mathieu Kotlin version follows:

fun main(args : Array<String>) {
    val fileName = "app.apk"
    ZipFile(fileName).use { zip ->
        zip.entries().asSequence().forEach { entry ->
            if( == "AndroidManifest.xml") {
                zip.getInputStream(entry).use { input ->
                    val xml = decompressXML(input.readBytes())
                    //TODO: parse the XML


     * Binary XML doc ending Tag
    var endDocTag = 0x00100101

     * Binary XML start Tag
    var startTag = 0x00100102

     * Binary XML end Tag
    var endTag = 0x00100103

     * Reference var for spacing
     * Used in prtIndent()
    var spaces = "                                             "

     * Parse the 'compressed' binary form of Android XML docs
     * such as for AndroidManifest.xml in .apk files
     * Source:
     * @param xml Encoded XML content to decompress
    fun decompressXML(xml: ByteArray): String {

        val resultXml = StringBuilder()

        // Compressed XML file/bytes starts with 24x bytes of data,
        // 9 32 bit words in little endian order (LSB first):
        //   0th word is 03 00 08 00
        //   3rd word SEEMS TO BE:  Offset at then of StringTable
        //   4th word is: Number of strings in string table
        // WARNING: Sometime I indiscriminently display or refer to word in
        //   little endian storage format, or in integer format (ie MSB first).
        val numbStrings = LEW(xml, 4 * 4)

        // StringIndexTable starts at offset 24x, an array of 32 bit LE offsets
        // of the length/string data in the StringTable.
        val sitOff = 0x24  // Offset of start of StringIndexTable

        // StringTable, each string is represented with a 16 bit little endian
        // character count, followed by that number of 16 bit (LE) (Unicode) chars.
        val stOff = sitOff + numbStrings * 4  // StringTable follows StrIndexTable

        // XMLTags, The XML tag tree starts after some unknown content after the
        // StringTable.  There is some unknown data after the StringTable, scan
        // forward from this point to the flag for the start of an XML start tag.
        var xmlTagOff = LEW(xml, 3 * 4)  // Start from the offset in the 3rd word.
        // Scan forward until we find the bytes: 0x02011000(x00100102 in normal int)
        run {
            var ii = xmlTagOff
            while (ii < xml.size - 4) {
                if (LEW(xml, ii) == startTag) {
                    xmlTagOff = ii
                ii += 4
        } // end of hack, scanning for start of first start tag

        // XML tags and attributes:
        // Every XML start and end tag consists of 6 32 bit words:
        //   0th word: 02011000 for startTag and 03011000 for endTag
        //   1st word: a flag?, like 38000000
        //   2nd word: Line of where this tag appeared in the original source file
        //   3rd word: FFFFFFFF ??
        //   4th word: StringIndex of NameSpace name, or FFFFFFFF for default NS
        //   5th word: StringIndex of Element Name
        //   (Note: 01011000 in 0th word means end of XML document, endDocTag)

        // Start tags (not end tags) contain 3 more words:
        //   6th word: 14001400 meaning??
        //   7th word: Number of Attributes that follow this tag(follow word 8th)
        //   8th word: 00000000 meaning??

        // Attributes consist of 5 words:
        //   0th word: StringIndex of Attribute Name's Namespace, or FFFFFFFF
        //   1st word: StringIndex of Attribute Name
        //   2nd word: StringIndex of Attribute Value, or FFFFFFF if ResourceId used
        //   3rd word: Flags?
        //   4th word: str ind of attr value again, or ResourceId of value

        // TMP, dump string table to tr for debugging
        //tr.addSelect("strings", null);
        //for (int ii=0; ii<numbStrings; ii++) {
        //  // Length of string starts at StringTable plus offset in StrIndTable
        //  String str = compXmlString(xml, sitOff, stOff, ii);
        //  tr.add(String.valueOf(ii), str);

        // Step through the XML tree element tags and attributes
        var off = xmlTagOff
        var indent = 0
        var startTagLineNo = -2
        while (off < xml.size) {
            val tag0 = LEW(xml, off)
            //int tag1 = LEW(xml, off+1*4);
            val lineNo = LEW(xml, off + 2 * 4)
            //int tag3 = LEW(xml, off+3*4);
            val nameNsSi = LEW(xml, off + 4 * 4)
            val nameSi = LEW(xml, off + 5 * 4)

            if (tag0 == startTag) { // XML START TAG
                val tag6 = LEW(xml, off + 6 * 4)  // Expected to be 14001400
                val numbAttrs = LEW(xml, off + 7 * 4)  // Number of Attributes to follow
                //int tag8 = LEW(xml, off+8*4);  // Expected to be 00000000
                off += 9 * 4  // Skip over 6+3 words of startTag data
                val name = compXmlString(xml, sitOff, stOff, nameSi)
                //tr.addSelect(name, null);
                startTagLineNo = lineNo

                // Look for the Attributes
                val sb = StringBuffer()
                for (ii in 0 until numbAttrs) {
                    val attrNameNsSi = LEW(xml, off)  // AttrName Namespace Str Ind, or FFFFFFFF
                    val attrNameSi = LEW(xml, off + 1 * 4)  // AttrName String Index
                    val attrValueSi = LEW(xml, off + 2 * 4) // AttrValue Str Ind, or FFFFFFFF
                    val attrFlags = LEW(xml, off + 3 * 4)
                    val attrResId = LEW(xml, off + 4 * 4)  // AttrValue ResourceId or dup AttrValue StrInd
                    off += 5 * 4  // Skip over the 5 words of an attribute

                    val attrName = compXmlString(xml, sitOff, stOff, attrNameSi)
                    val attrValue = if (attrValueSi != -1)
                        compXmlString(xml, sitOff, stOff, attrValueSi)
                        "resourceID 0x" + Integer.toHexString(attrResId)
                    sb.append(" $attrName=\"$attrValue\"")
                    //tr.add(attrName, attrValue);
                resultXml.append(prtIndent(indent, "<$name$sb>"))

            } else if (tag0 == endTag) { // XML END TAG
                off += 6 * 4  // Skip over 6 words of endTag data
                val name = compXmlString(xml, sitOff, stOff, nameSi)
                resultXml.append(prtIndent(indent, "</$name>  (line $startTagLineNo-$lineNo)"))
                //tr.parent();  // Step back up the NobTree

            } else if (tag0 == endDocTag) {  // END OF XML DOC TAG

            } else {
                        println("  Unrecognized tag code '" + Integer.toHexString(tag0)
                            + "' at offset " + off
        } // end of while loop scanning tags and attributes of XML tree
        println("    end at offset $off")

        return resultXml.toString()
    } // end of decompressXML

     * Tool Method for decompressXML();
     * Compute binary XML to its string format
     * Source: Source:
     * @param xml Binary-formatted XML
     * @param sitOff
     * @param stOff
     * @param strInd
     * @return String-formatted XML
    fun compXmlString(xml: ByteArray, sitOff: Int, stOff: Int, strInd: Int): String? {
        if (strInd < 0) return null
        val strOff = stOff + LEW(xml, sitOff + strInd * 4)
        return compXmlStringAt(xml, strOff)

     * Tool Method for decompressXML();
     * Apply indentation
     * @param indent Indentation level
     * @param str String to indent
     * @return Indented string
    fun prtIndent(indent: Int, str: String): String {

        return spaces.substring(0, Math.min(indent * 2, spaces.length)) + str

     * Tool method for decompressXML()
     * Return the string stored in StringTable format at
     * offset strOff.  This offset points to the 16 bit string length, which
     * is followed by that number of 16 bit (Unicode) chars.
     * @param arr StringTable array
     * @param strOff Offset to get string from
     * @return String from StringTable at offset strOff
    fun compXmlStringAt(arr: ByteArray, strOff: Int): String {
        val strLen = (arr[strOff + 1] shl (8 and 0xff00)) or (arr[strOff].toInt() and 0xff)
        val chars = ByteArray(strLen)
        for (ii in 0 until strLen) {
            chars[ii] = arr[strOff + 2 + ii * 2]
        return String(chars)  // Hack, just use 8 byte chars
    } // end of compXmlStringAt

     * Return value of a Little Endian 32 bit word from the byte array
     * at offset off.
     * @param arr Byte array with 32 bit word
     * @param off Offset to get word from
     * @return Value of Little Endian 32 bit word specified
    fun LEW(arr: ByteArray, off: Int): Int {
        return (arr[off + 3] shl 24 and -0x1000000 or ((arr[off + 2] shl 16) and 0xff0000)
                or (arr[off + 1] shl 8 and 0xff00) or (arr[off].toInt() and 0xFF))
    } // end of LEW

    private infix fun Byte.shl(i: Int): Int = (this.toInt() shl i)
    private infix fun Int.shl(i: Int): Int = (this shl i)

This is a kotlin version of the answer above.

How to make IPython notebook matplotlib plot inline

I did the anaconda install but matplotlib is not plotting

It starts plotting when i did this

import matplotlib
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline  

How to easily map c++ enums to strings

If you want the enum names themselves as strings, see this post. Otherwise, a std::map<MyEnum, char const*> will work nicely. (No point in copying your string literals to std::strings in the map)

For extra syntactic sugar, here's how to write a map_init class. The goal is to allow

std::map<MyEnum, const char*> MyMap;
    (eValue1, "A")
    (eValue2, "B")
    (eValue3, "C")

The function template <typename T> map_init(T&) returns a map_init_helper<T>. map_init_helper<T> stores a T&, and defines the trivial map_init_helper& operator()(typename T::key_type const&, typename T::value_type const&). (Returning *this from operator() allows the chaining of operator(), like operator<< on std::ostreams)

template<typename T> struct map_init_helper
    T& data;
    map_init_helper(T& d) : data(d) {}
    map_init_helper& operator() (typename T::key_type const& key, typename T::mapped_type const& value)
        data[key] = value;
        return *this;

template<typename T> map_init_helper<T> map_init(T& item)
    return map_init_helper<T>(item);

Since the function and helper class are templated, you can use them for any map, or map-like structure. I.e. it can also add entries to std::unordered_map

If you don't like writing these helpers, boost::assign offers the same functionality out of the box.

How to make an embedded Youtube video automatically start playing?

Add &autoplay=1 to your syntax, like this

<iframe title="YouTube video player" width="480" height="390" src=";autoplay=1" frameborder="0" allowfullscreen></iframe>

SQL-Server: Error - Exclusive access could not be obtained because the database is in use

I experienced this issue when trying to restore a database on MS SQL Server 2012.

Here's what worked for me:

I had to first run the RESTORE FILELISTONLY command below on the backup file to list the logical file names:

    FROM DISK = 'C:\Program Files\Microsoft SQL Server\MSSQL12.MSSQLSERVER\MSSQL\Backup\my_db_backup.bak'

This displayed the LogicalName and the corresponding PhysicalName of the Data and Log files for the database respectively:

LogicalName      PhysicalName               
com.my_db        C:\Program Files\Microsoft SQL Server\MSSQL12.MSSQLSERVER\MSSQL\DATA\com.my_db.mdf
com.my_db_log    C:\Program Files\Microsoft SQL Server\MSSQL12.MSSQLSERVER\MSSQL\DATA\com.my_db_log.ldf

All I had to do was to simply replace the LogicalName and the corresponding PhysicalName of the Data and Log files for the database respectively in my database restore script:

USE master;


    FROM DISK = 'C:\Program Files\Microsoft SQL Server\MSSQL12.MSSQLSERVER\MSSQL\Backup\my_db_backup.bak'
    MOVE 'com.my_db' TO 'C:\Program Files\Microsoft SQL Server\MSSQL12.MSSQLSERVER\MSSQL\DATA\com.my_db.mdf',
    MOVE 'com.my_db_log' TO 'C:\Program Files\Microsoft SQL Server\MSSQL12.MSSQLSERVER\MSSQL\DATA\com.my_db_log.ldf'

And the Database Restore task ran successfully:

That's all.

I hope this helps

mysql-python install error: Cannot open include file 'config-win.h'

For me, it worked when I selected the correct bit of my Python version, NOT the one of my computer version.

Mine is 32bit, and my computer is 64bit. That was the problem and the 32bit version of fixed it.

to be exact, here is the one that worked for me: mysqlclient-1.3.13-cp37-cp37m-win32.whl

Multi-gradient shapes

Have you tried to overlay one gradient with a nearly-transparent opacity for the highlight on top of another image with an opaque opacity for the green gradient?

Apache Name Virtual Host with SSL

First you need NameVirtualHost ip:443 in you config file! You probably have one with 80 at the end, but you will also need one with 443.

Second you need a *.domain certificate (wildcard) (it is possible to make one)

Third you can make only something.domain webs in one ip (because of the certificate)

How to insert data using wpdb

$wpdb->query("insert into ".$table_name." (name, email, country, country, course, message, datesent) values ('$name','$email', '$phone', '$country', '$course', '$message', )");

Importing json file in TypeScript

Another way to go

const data: {[key: string]: any} = require('./data.json');

This was you still can define json type is you want and don't have to use wildcard.

For example, custom type json.

interface User {
  firstName: string;
  lastName: string;
  birthday: Date;
const user: User = require('./user.json');

How do I concatenate two text files in PowerShell?

To keep encoding and line endings:

Get-Content files.* -Raw | Set-Content newfile.file -NoNewline

Note: AFAIR, whose parameters aren't supported by old Powershells (<3? <4?)

pandas: to_numeric for multiple columns

If you are looking for a range of columns, you can try this:

df.iloc[7:] = df.iloc[7:].astype(float)

The examples above will convert type to be float, for all the columns begin with the 7th to the end. You of course can use different type or different range.

I think this is useful when you have a big range of columns to convert and a lot of rows. It doesn't make you go over each row by yourself - I believe numpy do it more efficiently.

This is useful only if you know that all the required columns contain numbers only - it will not change "bad values" (like string) to be NaN for you.

How to delete rows in tables that contain foreign keys to other tables

If you have multiply rows to delete and you don't want to alter the structure of your tables you can use cursor. 1-You first need to select rows to delete(in a cursor) 2-Then for each row in the cursor you delete the referencing rows and after that delete the row him self.


--id is primary key of MainTable
    declare @id int
    set @id = 1
    declare theMain cursor for select FK from MainTable where MainID = @id
    declare @fk_Id int
    open theMain
    fetch next from theMain into @fk_Id
    while @@fetch_status=0
        --fkid is the foreign key 
        --Must delete from Main Table first then child.
        delete from MainTable where fkid = @fk_Id
        delete from ReferencingTable where fkid = @fk_Id
        fetch next from theMain into @fk_Id
    close theMain
    deallocate theMain

hope is useful

Use of Custom Data Types in VBA

It looks like you want to define Truck as a Class with properties NumberOfAxles, AxleWeights & AxleSpacings.

This can be defined in a CLASS MODULE (here named clsTrucks)

Option Explicit

Private tID As String
Private tNumberOfAxles As Double
Private tAxleSpacings As Double

Public Property Get truckID() As String
    truckID = tID
End Property

Public Property Let truckID(value As String)
    tID = value
End Property

Public Property Get truckNumberOfAxles() As Double
    truckNumberOfAxles = tNumberOfAxles
End Property

Public Property Let truckNumberOfAxles(value As Double)
    tNumberOfAxles = value
End Property

Public Property Get truckAxleSpacings() As Double
    truckAxleSpacings = tAxleSpacings
End Property

Public Property Let truckAxleSpacings(value As Double)
    tAxleSpacings = value
End Property

then in a MODULE the following defines a new truck and it's properties and adds it to a collection of trucks and then retrieves the collection.

Option Explicit

Public TruckCollection As New Collection

Sub DefineNewTruck()
Dim tempTruck As clsTrucks
Dim i As Long

    'Add 5 trucks
    For i = 1 To 5
        Set tempTruck = New clsTrucks
        'Random data
        tempTruck.truckID = "Truck" & i
        tempTruck.truckAxleSpacings = 13.5 + i
        tempTruck.truckNumberOfAxles = 20.5 + i

        'tempTruck.truckID is the collection key
        TruckCollection.Add tempTruck, tempTruck.truckID
    Next i

    'retrieve 5 trucks
    For i = 1 To 5
        'retrieve by collection index
        Debug.Print TruckCollection(i).truckAxleSpacings
        'retrieve by key
        Debug.Print TruckCollection("Truck" & i).truckAxleSpacings

    Next i

End Sub

There are several ways of doing this so it really depends on how you intend to use the data as to whether an a class/collection is the best setup or arrays/dictionaries etc.

How do I output the difference between two specific revisions in Subversion?

See svn diff in the manual:

svn diff -r 8979:11390

CSS selector - element with a given child

Is it possible to select an element if it contains a specific child element?

Unfortunately not yet.

The CSS2 and CSS3 selector specifications do not allow for any sort of parent selection.

A Note About Specification Changes

This is a disclaimer about the accuracy of this post from this point onward. Parent selectors in CSS have been discussed for many years. As no consensus has been found, changes keep happening. I will attempt to keep this answer up-to-date, however be aware that there may be inaccuracies due to changes in the specifications.

An older "Selectors Level 4 Working Draft" described a feature which was the ability to specify the "subject" of a selector. This feature has been dropped and will not be available for CSS implementations.

The subject was going to be the element in the selector chain that would have styles applied to it.

Example HTML
<p><span>lorem</span> ipsum dolor sit amet</p>
<p>consecteture edipsing elit</p>

This selector would style the span element

p span {
    color: red;

This selector would style the p element

!p span {
    color: red;

A more recent "Selectors Level 4 Editor’s Draft" includes "The Relational Pseudo-class: :has()"

:has() would allow an author to select an element based on its contents. My understanding is it was chosen to provide compatibility with jQuery's custom :has() pseudo-selector*.

In any event, continuing the example from above, to select the p element that contains a span one could use:

p:has(span) {
    color: red;

* This makes me wonder if jQuery had implemented selector subjects whether subjects would have remained in the specification.

Create an empty object in JavaScript with {} or new Object()?

This is essentially the same thing. Use whatever you find more convenient.

What are named pipes?

Linux Pipes
First In First Out (FIFO) interproccess communication mechanism.

Unnamed Pipes
On the command line, represented by a "|" between two commands.

Named Pipes
A FIFO special file. Once created, you can use the pipe just like a normal file(open, close, write, read, etc).

To create a named pipe, called "myPipe", from the command line (man page):

mkfifo myPipe  

To create a named pipe from c, where "pathname" is the name you would like the pipe to have and "mode" contains the permissions you want the pipe to have (man page):

#include <sys/types.h>
#include <sys/stat.h>
int mkfifo(const char *pathname, mode_t mode);

port 8080 is already in use and no process using 8080 has been listed

If no other process is using the port 8080, Eventhough eclipse shows the port 8080 is used while starting the server in eclipse, first you have to stop the server by hitting the stop button in "Configure Tomcat"(which you can find in your start menu under tomcat folder), then try to start the server in eclipse then it will be started.

If any other process is using the port 8080 and as well as you no need to disturb it. then you can change the port.

Origin is not allowed by Access-Control-Allow-Origin

If you get this in Angular.js, then make sure you escape your port number like this:

var Project = $resource(
    'http://localhost\\:5648/api/...', {'a':'b'}, {
        update: { method: 'PUT' }

See here for more info on it.

Does Java support structs?

Yes, Java doesn't have struct/value type yet. But, in the upcoming version of Java, we are going to get inline class which is similar to struct in C# and will help us write allocation free code.

inline class point { 
  int x;
  int y;

Get a list of resources from classpath directory

Used a combination of Rob's response.

final String resourceDir = "resourceDirectory/";
List<String> files = IOUtils.readLines(Thread.currentThread().getClass().getClassLoader().getResourceAsStream(resourceDir), Charsets.UTF_8);

for(String f : files){
  String data= IOUtils.toString(Thread.currentThread().getClass().getClassLoader().getResourceAsStream(resourceDir + f));
  ....process data

How to watch for form changes in Angular

If you are using FormBuilder, see @dfsq's answer.

If you are not using FormBuilder, there are two ways to be notified of changes.

Method 1

As discussed in the comments on the question, use an event binding on each input element. Add to your template:

<input type="text" class="form-control" required [ngModel]="model.first_name"

Then in your component:

doSomething(newValue) {
  model.first_name = newValue;

The Forms page has some additional information about ngModel that is relevant here:

The ngModelChange is not an <input> element event. It is actually an event property of the NgModel directive. When Angular sees a binding target in the form [(x)], it expects the x directive to have an x input property and an xChange output property.

The other oddity is the template expression, = $event. We're used to seeing an $event object coming from a DOM event. The ngModelChange property doesn't produce a DOM event; it's an Angular EventEmitter property that returns the input box value when it fires..

We almost always prefer [(ngModel)]. We might split the binding if we had to do something special in the event handling such as debounce or throttle the key strokes.

In your case, I suppose you want to do something special.

Method 2

Define a local template variable and set it to ngForm.
Use ngControl on the input elements.
Get a reference to the form's NgForm directive using @ViewChild, then subscribe to the NgForm's ControlGroup for changes:

<form #myForm="ngForm" (ngSubmit)="onSubmit()">
  <input type="text" ngControl="firstName" class="form-control" 
   required [(ngModel)]="model.first_name">
  <input type="text" ngControl="lastName" class="form-control" 
   required [(ngModel)]="model.last_name">

class MyForm {
  @ViewChild('myForm') form;
  ngAfterViewInit() {
      .subscribe(values => this.doSomething(values));
  doSomething(values) {


For more information on Method 2, see Savkin's video.

See also @Thierry's answer for more information on what you can do with the valueChanges observable (such as debouncing/waiting a bit before processing changes).

Python mock multiple return values

You can assign an iterable to side_effect, and the mock will return the next value in the sequence each time it is called:

>>> from unittest.mock import Mock
>>> m = Mock()
>>> m.side_effect = ['foo', 'bar', 'baz']
>>> m()
>>> m()
>>> m()

Quoting the Mock() documentation:

If side_effect is an iterable then each call to the mock will return the next value from the iterable.

Return single column from a multi-dimensional array

very simple go for this

foreach ($arrays as $arr) {
$str .= $arr["tag_name"] . ",";
$str = trim($str, ',');//removes the final comma 

Installing Tomcat 7 as Service on Windows Server 2008

You can find the solution here!

Install the service named 'Tomcat7'

C:\>Tomcat\bin\service.bat install

There is a 2nd optional parameter that lets you specify the name of the service, as displayed in Windows services.

Install the service named 'MyTomcatService'

C:\>Tomcat\bin\service.bat install MyTomcatService

How to allow users to check for the latest app version from inside the app?

Here's how to find the current and latest available versions:

       try {
            String curVersion = getPackageManager().getPackageInfo(getPackageName(), 0).versionName;
            String newVersion = curVersion;
            newVersion = Jsoup.connect("" + getPackageName() + "&hl=en")
                    .userAgent("Mozilla/5.0 (Windows; U; WindowsNT 5.1; en-US; rv1.8.1.6) Gecko/20070725 Firefox/")
                    .select("div.hAyfc:nth-child(4) .IQ1z0d .htlgb")
            Log.d("Curr Version" , curVersion);
            Log.d("New Version" , newVersion);

        } catch (Exception e) {
            return false;

Forbidden :You don't have permission to access /phpmyadmin on this server

With the latest version of phpmyadmin 5.0.2+ at least

Check that the actual installation was completed correctly,

Mine had been copied over into a sub folder on a linux machine rather that being at the


Get value of multiselect box using jQuery or pure JS

var data=[];
var $el=$("#my-select");


I would be using laravel whereDoesntHave to achieve this.


Convert Java object to XML string

To convert an Object to XML in Java

package com;

import java.util.ArrayList;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

* @author ABsiddik

public class Customer {

int id;
String name;
int age;

String address;
ArrayList<String> mobileNo;

 public int getId() {
    return id;

public void setId(int id) { = id;

public String getName() {
    return name;

public void setName(String name) { = name;

public int getAge() {
    return age;

public void setAge(int age) {
    this.age = age;

public String getAddress() {
    return address;

public void setAddress(String address) {
    this.address = address;

public ArrayList<String> getMobileNo() {
    return mobileNo;

public void setMobileNo(ArrayList<String> mobileNo) {
    this.mobileNo = mobileNo;


package com;

import java.util.ArrayList;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;

* @author ABsiddik
public class ConvertObjToXML {

public static void main(String args[]) throws Exception
    ArrayList<String> numberList = new ArrayList<>();

    Customer c = new Customer();

    c.setName("Abu Bakar Siddik");
    c.setAddress("Dhaka, Bangladesh");

    File file = new File("C:\\Users\\NETIZEN-ONE\\Desktop \\customer.xml");
    JAXBContext jaxbContext = JAXBContext.newInstance(Customer.class);
    Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
    jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

    jaxbMarshaller.marshal(c, file);// this line create customer.xml file in specified path.

    StringWriter sw = new StringWriter();
    jaxbMarshaller.marshal(c, sw);
    String xmlString = sw.toString();



Try with this example..

How do you resize a form to fit its content automatically?

This technique solved my problem:

In parent form:

frmEmployee frm = new frmEmployee();
frm.MdiParent = this;
frm.Dock = DockStyle.Fill;

In the child form (Load event):

this.WindowState = FormWindowState.Maximized;

Git: How to remove remote origin from Git repo

first will change push remote url

git remote set-url --push origin https://newurl

second will change fetch remote url

git remote set-url origin https://newurl

What is Ad Hoc Query?

Ad hoc queries are those that are not already defined that are not needed on a regular basis, so they're not included in the typical set of reports or queries

How can I render a list select box (dropdown) with bootstrap?

Another option is to make the Bootstrap dropdown behave like a select using jQuery...

$(".dropdown-menu li a").click(function(){
  var selText = $(this).text();
  $(this).parents('.btn-group').find('.dropdown-toggle').html(selText+' <span class="caret"></span>');

Remove innerHTML from div

To remove all child elements from your div:


.removeData() and the corresponding .data() function are used to attach data behind an element, say if you wanted to note that a specific list element referred to user ID 25 in your database:

var $li = $('<li>Joe</li>').data('id', 25);

What does "Changes not staged for commit" mean

It's another way of Git telling you:

Hey, I see you made some changes, but keep in mind that when you write pages to my history, those changes won't be in these pages.

Changes to files are not staged if you do not explicitly git add them (and this makes sense).

So when you git commit, those changes won't be added since they are not staged. If you want to commit them, you have to stage them first (ie. git add).

Using the value in a cell as a cell reference in a formula?


=SUM(INDIRECT(<start cell here> & ":" & <end cell here>))

How to get the range of occupied cells in excel sheet

The only way I could get it to work in ALL scenarios (except Protected sheets) (based on Farham's Answer):

It supports:

  • Scanning Hidden Row / Columns

  • Ignores formatted cells with no data / formula


// Unhide All Cells and clear formats

// Detect Last used Row - Ignore cells that contains formulas that result in blank values
int lastRowIgnoreFormulas = sheet.Cells.Find(
// Detect Last Used Column  - Ignore cells that contains formulas that result in blank values
int lastColIgnoreFormulas = sheet.Cells.Find(

// Detect Last used Row / Column - Including cells that contains formulas that result in blank values
int lastColIncludeFormulas = sheet.UsedRange.Columns.Count;
int lastColIncludeFormulas = sheet.UsedRange.Rows.Count;

Best practices for styling HTML emails

I've fought the HTML email battle before. Here are some of my tips about styling for maximum compatibility between email clients.

  • Inline styles are you best friend. Absolutely don't link style sheets and do not use a <style> tag (GMail, for example, strips that tag and all it's contents).

  • Against your better judgement, use and abuse tables. <div>s just won't cut it (especially in Outlook).

  • Don't use background images, they're spotty and will annoy you.

  • Remember that some email clients will automatically transform typed out hyperlinks into links (if you don't anchor <a> them yourself). This can sometimes achieve negative effects (say if you're putting a style on each of the hyperlinks to appear a different color).

  • Be careful hyperlinking an actual link with something different. For example, don't type out and then link it to Some clients will flag the message as Spam or Junk.

  • Save your images in as few colors as possible to save on size.

  • If possible, embed your images in your email. The email won't have to reach out to an external web server to download them and they won't appear as attachments to the email.

And lastly, test, test, test! Each email client does things way differently than a browser would do.

Build error: You must add a reference to System.Runtime

I had this problem in some solutions on VS 2015 (not MVC though), and even in the same solution on one workstation but not on another. The errors started appeared after changing .NET version to 4.6 and referencing PCL.

The solution is simple: Close the solution and delete the hidden .vs folder in the same folder as the solution.

Adding the missing references as suggested in other answers also solves the problem, but the error remains solved even after you remove the references again.

As for TeamCity, I cannot say since my configuration never had a problem. But make sure that you reset the working catalog as a part of your debugging effort.

jQuery: serialize() form and other parameters

I fix the problem with under statement ; send data with url same GET methode

    url: 'includes/get_ajax_function.php?value=jack&id='+id,
    type: 'post',
    data: $('#b-info1').serializeArray(),

and get value with $_REQUEST['value'] OR $_GET['id']

How to install and run phpize

In Ubuntu 16.04, you can install phpize with the command

aptitude install php7.1-dev // for php 7.1

which is equivalent to

apt-get install php7.1-dev // for php 7.1

SQL use CASE statement in WHERE IN clause

I realize this has been answered, but there is a slight issue with the accepted solution. It will return false positives. Easy to fix:

SELECT * FROM Products P    
WHERE (@Status='published' and P.Status IN (1,3))
   or (@Status='standby' and P.Status IN  (2,5,9,6))
   or (@Status='deleted' and P.Status IN (4,5,8,10))
   or (@Status not in ('published','standby','deleted') and P.Status IN (1,2))

Parentheses aren't needed (although perhaps easier to read hence why I included them).

How to convert a Django QuerySet to a list

Try this values_list('column_name', flat=True).

answers = Answer.objects.filter(id__in=[ for answer in answer_set.answers.all()]).values_list('column_name', flat=True)

It will return you a list with specified column values

Archive the artifacts in Jenkins

Your understanding is correct, an artifact in the Jenkins sense is the result of a build - the intended output of the build process.

A common convention is to put the result of a build into a build, target or bin directory.

The Jenkins archiver can use globs (target/*.jar) to easily pick up the right file even if you have a unique name per build.

How to store custom objects in NSUserDefaults

Swift 3

class MyObject: NSObject, NSCoding  {
    let name : String
    let url : String
    let desc : String

    init(tuple : (String,String,String)){ = tuple.0
        self.url = tuple.1
        self.desc = tuple.2
    func getName() -> String {
        return name
    func getURL() -> String{
        return url
    func getDescription() -> String {
        return desc
    func getTuple() -> (String, String, String) {
        return (,self.url,self.desc)

    required init(coder aDecoder: NSCoder) { = aDecoder.decodeObject(forKey: "name") as? String ?? ""
        self.url = aDecoder.decodeObject(forKey: "url") as? String ?? ""
        self.desc = aDecoder.decodeObject(forKey: "desc") as? String ?? ""

    func encode(with aCoder: NSCoder) {
        aCoder.encode(, forKey: "name")
        aCoder.encode(self.url, forKey: "url")
        aCoder.encode(self.desc, forKey: "desc")

to store and retrieve:

func save() {
            let data  = NSKeyedArchiver.archivedData(withRootObject: object)
            UserDefaults.standard.set(data, forKey:"customData" )
        func get() -> MyObject? {
            guard let data = UserDefaults.standard.object(forKey: "customData") as? Data else { return nil }
            return NSKeyedUnarchiver.unarchiveObject(with: data) as? MyObject

Why does a base64 encoded string have an = sign at the end

= is a padding character. If the input stream has length that is not a multiple of 3, the padding character will be added. This is required by decoder: if no padding present, the last byte would have an incorrect number of zero bits.

Better and deeper explanation here:

Get latitude and longitude based on location name with Google Autocomplete API

I hope this can help someone in the future.

You can use the Google Geocoding API, as said before, I had to do some work with this recently, I hope this helps:

<!DOCTYPE html>
        <script src=""></script>
        <script type="text/javascript">
        function initialize() {
        var address = (document.getElementById('my-address'));
        var autocomplete = new google.maps.places.Autocomplete(address);
        google.maps.event.addListener(autocomplete, 'place_changed', function() {
            var place = autocomplete.getPlace();
            if (!place.geometry) {

        var address = '';
        if (place.address_components) {
            address = [
                (place.address_components[0] && place.address_components[0].short_name || ''),
                (place.address_components[1] && place.address_components[1].short_name || ''),
                (place.address_components[2] && place.address_components[2].short_name || '')
                ].join(' ');
function codeAddress() {
    geocoder = new google.maps.Geocoder();
    var address = document.getElementById("my-address").value;
    geocoder.geocode( { 'address': address}, function(results, status) {
      if (status == google.maps.GeocoderStatus.OK) {

      alert("Latitude: "+results[0];
      alert("Longitude: "+results[0].geometry.location.lng());

      else {
        alert("Geocode was not successful for the following reason: " + status);
google.maps.event.addDomListener(window, 'load', initialize);

        <input type="text" id="my-address">
        <button id="getCords" onClick="codeAddress();">getLat&Long</button>

Now this has also an autocomlpete function which you can see in the code, it fetches the address from the input and gets auto completed by the API while typing.

Once you have your address hit the button and you get your results via alert as required. Please also note this uses the latest API and it loads the 'places' library (when calling the API uses the 'libraries' parameter).

Hope this helps, and read the documentation for more information, cheers.

Edit #1: Fiddle

newline in <td title="">

If you're looking to put line breaks into the tooltip that appears on mouseover, there's no reliable crossbrowser way to do that. You'd have to fall back to one of the many Javascript tooltip code samples

I want to get the type of a variable at runtime

I think the question is incomplete. if you meant that you wish to get the type information of some typeclass then below:

If you wish to print as you have specified then:

scala>  def manOf[T: Manifest](t: T): Manifest[T] = manifest[T]
manOf: [T](t: T)(implicit evidence$1: Manifest[T])Manifest[T]

scala> val x = List(1,2,3)
x: List[Int] = List(1, 2, 3)

scala> println(manOf(x))

If you are in repl mode then

scala> :type List(1,2,3)

Or if you just wish to know what the class type then as @monkjack explains "string".getClass might solve the purpose

Is there a way to view past mysql queries with phpmyadmin?

Yes, you can log queries to a special phpMyAdmin DB table.

See SQL_history.

copy all files and folders from one drive to another drive using DOS (command prompt)

Use robocopy. Robocopy is shipped by default on Windows Vista and newer, and is considered the replacement for xcopy. (xcopy has some significant limitations, including the fact that it can't handle paths longer than 256 characters, even if the filesystem can).

robocopy c:\ d:\ /e /zb /copyall /purge /dcopy:dat

Note that using /purge on the root directory of the volume will cause Robocopy to apply the requested operation on files inside the System Volume Information directory. Run robocopy /? for help. Also note that you probably want to open the command prompt as an administrator to be able to copy system files. To speed things up, use /b instead of /zb.

Outlets cannot be connected to repeating content iOS

For collectionView :


From viewcontroller, kindly remove the IBoutlet of colllectionviewcell

. the issue mentions the invalid of your IBOutlet. so remove all subclass which has multi-outlet(invalids) and reconnect it.

The answer is already mentioned in another question for collectionviewcell

Exercises to improve my Java programming skills

I highly recommend reading the book 'Effective Java' from Joshua Bloch.

How to import and export components using React + ES6 + webpack?

To export a single component in ES6, you can use export default as follows:

class MyClass extends Component {

export default MyClass;

And now you use the following syntax to import that module:

import MyClass from './MyClass.react'

If you are looking to export multiple components from a single file the declaration would look something like this:

export class MyClass1 extends Component {

export class MyClass2 extends Component {

And now you can use the following syntax to import those files:

import {MyClass1, MyClass2} from './MyClass.react'

MacOSX homebrew mysql root password

Got this error after installing mysql via home brew.

So first remove the installation. Then Reinstall via Homebrew

brew update
brew doctor
brew install mysql

Then restart mysql service

 mysql.server restart

Then run this command to set your new root password.


Finally it will ask to reload the privileges. Say yes. Then login to mysql again. And use the new password you have set.

mysql -u root -p

javax.xml.bind.JAXBException: Class *** nor any of its super class is known to this context

This exception can be solved by specifying a full class path.


If you are using a class named ExceptionDetails

Wrong Way of passing arguments

JAXBContext jaxbContext = JAXBContext.newInstance(ExceptionDetails.class);

Right Way of passing arguments

JAXBContext jaxbContext = JAXBContext.newInstance(com.tibco.schemas.exception.ExceptionDetails.class);

Calculate rolling / moving average in C++

I use this quite often in hard realtime systems that have fairly insane update rates (50kilosamples/sec) As a result I typically precompute the scalars.

To compute a moving average of N samples: scalar1 = 1/N; scalar2 = 1 - scalar1; // or (1 - 1/N) then:

Average = currentSample*scalar1 + Average*scalar2;

Example: Sliding average of 10 elements

double scalar1 = 1.0/10.0;  // 0.1
double scalar2 = 1.0 - scalar1; // 0.9
bool first_sample = true;
double average=0.0;
   double newSample = getSample();
    // everybody forgets the initial condition *sigh*
      average = newSample;
      first_sample = false;
      average = (sample*scalar1) + (average*scalar2);

Note: this is just a practical implementation of the answer given by steveha above. Sometimes it's easier to understand a concrete example.

How can I view an old version of a file with Git?

Doing this by date looks like this if the commit happened within the last 90 days:

git show HEAD@{2013-02-25}:./fileInCurrentDirectory.txt

Note that HEAD@{2013-02-25} means "where HEAD was on 2013-02-25" in this repository (using the reflog), not "the last commit before 2013-02-25 in this branch in history".

This is important! It means that, by default, this method only works for history within the last 90 days. Otherwise, you need to do this:

git show $(git rev-list -1 --before="2013-02-26" HEAD):./fileInCurrentDirectory.txt

What does random.sample() method in python do?

According to documentation:

random.sample(population, k)

Return a k length list of unique elements chosen from the population sequence. Used for random sampling without replacement.

Basically, it picks k unique random elements, a sample, from a sequence:

>>> import random
>>> c = list(range(0, 15))
>>> c
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
>>> random.sample(c, 5)
[9, 2, 3, 14, 11]

random.sample works also directly from a range:

>>> c = range(0, 15)
>>> c
range(0, 15)
>>> random.sample(c, 5)
[12, 3, 6, 14, 10]

In addition to sequences, random.sample works with sets too:

>>> c = {1, 2, 4}
>>> random.sample(c, 2)
[4, 1]

However, random.sample doesn't work with arbitrary iterators:

>>> c = [1, 3]
>>> random.sample(iter(c), 5)
TypeError: Population must be a sequence or set.  For dicts, use list(d).

Two's Complement in Python

in case someone needs the inverse direction too:

def num_to_bin(num, wordsize):
    if num < 0:
        num = 2**wordsize+num
    base = bin(num)[2:]
    padding_size = wordsize - len(base)
    return '0' * padding_size + base

for i in range(7, -9, -1):
    print num_to_bin(i, 4)

should output this: 0111 0110 0101 0100 0011 0010 0001 0000 1111 1110 1101 1100 1011 1010 1001 1000

syntax error, unexpected T_ENCAPSED_AND_WHITESPACE, expecting T_STRING or T_VARIABLE or T_NUM_STRING

Might be a pasting problem, but as far as I can see from your code, you're missing the single quotes around the HTML part you're echo-ing.

If not, could you post the code correctly and tell us what line is causing the error?

How do I get an element to scroll into view, using jQuery?

My UI has a vertical scrolling list of thumbs within a thumbbar The goal was to make the current thumb right in the center of the thumbbar. I started from the approved answer, but found that there were a few tweaks to truly center the current thumb. hope this helps someone else.


<ul id='thumbbar'>
    <li id='thumbbar-123'></li>
    <li id='thumbbar-124'></li>
    <li id='thumbbar-125'></li>


// scroll the current thumb bar thumb into view
heightbar   = $('#thumbbar').height();
heightthumb = $('#thumbbar-' + pageid).height();
offsetbar   = $('#thumbbar').scrollTop();

    scrollTop: - heightbar / 2 - offsetbar - 20

Save file Javascript with file name

Use the filename property like this:

uriContent = "data:application/octet-stream;filename=filename.txt," + 
              encodeURIComponent(codeMirror.getValue());, 'filename.txt');


Apparently, there is no reliable way to do this. See: Is there any way to specify a suggested filename when using data: URI?

How to delete empty folders using windows command prompt?

A simpler way is to do xcopy to make a copy of the entire directory structure using /s switch. help for /s says Copies directories and subdirectories except empty ones.

xcopy dirA dirB /S

where dirA is source with Empty folders. DirB will be the copy without empty folders

Can inner classes access private variables?

Anything that is part of Outer should have access to all of Outer's members, public or private.

Edit: your compiler is correct, var is not a member of Inner. But if you have a reference or pointer to an instance of Outer, it could access that.

Unloading classes in java?

If you're live watching if unloading class worked in JConsole or something, try also adding java.lang.System.gc() at the end of your class unloading logic. It explicitly triggers Garbage Collector.

batch file to check 64bit or 32bit OS

I really do not understand some of the answers given here (sorry for that). The top-voted answer for example does not return the Windows architecture, instead it will give you the processor architecture. While running a 32-bits Windows build on a 64-bits CPU you will get the wrong result (it's a query on hardware being used).

The safest option is to query the BuildLabEx value from the registry.

Determine x86 (intel) or x86-64 (amd)

reg query "HKLM\Software\Microsoft\Windows NT\CurrentVersion" /v "BuildLabEx" | >nul find /i ".x86fre."   && set "_ARCH_=x86" || set "_ARCH_=x86-64"

Determine x86 (intel), x86-64 (amd) or arm

set "_ARCH_=unknown"
reg query "HKLM\Software\Microsoft\Windows NT\CurrentVersion" /v "BuildLabEx" | >nul find /i ".x86fre."   && set "_ARCH_=x86" 
reg query "HKLM\Software\Microsoft\Windows NT\CurrentVersion" /v "BuildLabEx" | >nul find /i ".amd64fre." && set "_ARCH_=x86-64" 
reg query "HKLM\Software\Microsoft\Windows NT\CurrentVersion" /v "BuildLabEx" | >nul find /i ".armfre."   && set "_ARCH_=arm" 

An alternative option (mentioned before)

if defined ProgramFiles(x86) ( set "_ARCH_=x86-64" ) else ( set "_ARCH_=x86" )

The problem with the latter is when you mess up your variables, you are not able to use this method. Checking for the folder's existence will cause problems too when there are leftovers from a previous install (or some user purposely created the folder).

How ViewBag in ASP.NET MVC works

ViewBag is of type dynamic but, is internally an System.Dynamic.ExpandoObject()

It is declared like this:

dynamic ViewBag = new System.Dynamic.ExpandoObject();

which is why you can do :

ViewBag.Foo = "Bar";

A Sample Expander Object Code:

public class ExpanderObject : DynamicObject, IDynamicMetaObjectProvider
    public Dictionary<string, object> objectDictionary;

    public ExpanderObject()
        objectDictionary = new Dictionary<string, object>();
    public override bool TryGetMember(GetMemberBinder binder, out object result)
        object val;
        if (objectDictionary.TryGetValue(binder.Name, out val))
            result = val;
            return true;
        result = null;
        return false;

    public override bool TrySetMember(SetMemberBinder binder, object value)
            objectDictionary[binder.Name] = value;
            return true;
        catch (Exception ex)
            return false;

Can a java lambda have more than 1 parameter?

For something with 2 parameters, you could use BiFunction. If you need more, you can define your own function interface, like so:

public interface FourParameterFunction<T, U, V, W, R> {
    public R apply(T t, U u, V v, W w);

If there is more than one parameter, you need to put parentheses around the argument list, like so:

FourParameterFunction<String, Integer, Double, Person, String> myLambda = (a, b, c, d) -> {
    // do something
    return "done something";

What is the cleanest way to disable CSS transition effects temporarily?

I'd have a class in your CSS like this:

.no-transition { 
  -webkit-transition: none;
  -moz-transition: none;
  -o-transition: none;
  -ms-transition: none;
  transition: none;

and then in your jQuery:

$('#elem').addClass('no-transition'); //will disable it
$('#elem').removeClass('no-transition'); //will enable it

Can't compare naive and aware <= challenge.datetime_end

Disable time zone. Use challenge.datetime_start.replace(tzinfo=None);

You can also use replace(tzinfo=None) for other datetime.

if challenge.datetime_start.replace(tzinfo=None) <= <= challenge.datetime_end.replace(tzinfo=None):

UIButton: how to center an image and a text using imageEdgeInsets and titleEdgeInsets?

I was struggling to get this done because I couldn't get image size and text width on my view's constructor. Two minor changes on Jesse's answer worked for me:

CGFloat spacing = 3;
self.titleEdgeInsets = UIEdgeInsetsMake(0.0, - image.size.width, - (image.size.height + spacing), 0.0);
CGSize titleSize = [name sizeWithAttributes:@{NSFontAttributeName:self.titleLabel.font}];
self.imageEdgeInsets = UIEdgeInsetsMake(- (titleSize.height + spacing), 0.0, 0.0, - titleSize.width);

The change are:

  • Using [NSString sizeWithAttributes] to get text width;
  • Get image size directly on the UIImage instead of UIImageView

how to instanceof List<MyType>?

if(!myList.isEmpty() && myList.get(0) instanceof MyType){
    // MyType object

How to change Hash values?

You may want to go a step further and do this on a nested hash. Certainly this happens a fair amount with Rails projects.

Here's some code to ensure a params hash is in UTF-8:

  def convert_hash hash
    hash.inject({}) do |h,(k,v)|
      if v.kind_of? String
        h[k] = to_utf8(v) 
        h[k] = convert_hash(v)

  # Iconv UTF-8 helper
  # Converts strings into valid UTF-8
  # @param [String] untrusted_string the string to convert to UTF-8
  # @return [String] your string in UTF-8
  def to_utf8 untrusted_string=""
    ic ='UTF-8//IGNORE', 'UTF-8')
    ic.iconv(untrusted_string + ' ')[0..-2]

How can I extract audio from video with ffmpeg?

ffmpeg -i sample.avi will give you the audio/video format info for your file. Make sure you have the proper libraries configured to parse the input streams. Also, make sure that the file isn't corrupt.

"The system cannot find the file specified"

I got this error when starting my ASP.NET application and in my case the problem was that the SQL Server service was not running. Starting that cleared it up.

Why does this iterative list-growing code give IndexError: list assignment index out of range?

I think the Python method insert is what you're looking for:

Inserts element x at position i. list.insert(i,x)

array = [1,2,3,4,5]



# prints [1,2,20,3,4,5]

How do I output an ISO 8601 formatted string in JavaScript?

I typically don't want to display a UTC date since customers don't like doing the conversion in their head. To display a local ISO date, I use the function:

function toLocalIsoString(date, includeSeconds) {
    function pad(n) { return n < 10 ? '0' + n : n }
    var localIsoString = date.getFullYear() + '-'
        + pad(date.getMonth() + 1) + '-'
        + pad(date.getDate()) + 'T'
        + pad(date.getHours()) + ':'
        + pad(date.getMinutes()) + ':'
        + pad(date.getSeconds());
    if(date.getTimezoneOffset() == 0) localIsoString += 'Z';
    return localIsoString;

The function above omits time zone offset information (except if local time happens to be UTC), so I use the function below to show the local offset in a single location. You can also append its output to results from the above function if you wish to show the offset in each and every time:

function getOffsetFromUTC() {
    var offset = new Date().getTimezoneOffset();
    return ((offset < 0 ? '+' : '-')
        + pad(Math.abs(offset / 60), 2)
        + ':'
        + pad(Math.abs(offset % 60), 2))

toLocalIsoString uses pad. If needed, it works like nearly any pad function, but for the sake of completeness this is what I use:

// Pad a number to length using padChar
function pad(number, length, padChar) {
    if (typeof length === 'undefined') length = 2;
    if (typeof padChar === 'undefined') padChar = '0';
    var str = "" + number;
    while (str.length < length) {
        str = padChar + str;
    return str;

System not declared in scope?

Chances are that you've not included the header file that declares system().

In order to be able to compile C++ code that uses functions which you don't (manually) declare yourself, you have to pull in the declarations. These declarations are normally stored in so-called header files that you pull into the current translation unit using the #include preprocessor directive. As the code does not #include the header file in which system() is declared, the compilation fails.

To fix this issue, find out which header file provides you with the declaration of system() and include that. As mentioned in several other answers, you most likely want to add #include <cstdlib>

Add numpy array as column to Pandas data frame

You can add and retrieve a numpy array from dataframe using this:

import numpy as np
import pandas as pd

df = pd.DataFrame({'b':range(10)}) # target dataframe
a = np.random.normal(size=(10,2)) # numpy array
df['a']=a.tolist() # save array
np.array(df['a'].tolist()) # retrieve array

This builds on the previous answer that confused me because of the sparse part and this works well for a non-sparse numpy arrray.

JavaScript string and number conversion

These questions come up all the time due to JavaScript's typing system. People think they are getting a number when they're getting the string of a number.

Here are some things you might see that take advantage of the way JavaScript deals with strings and numbers. Personally, I wish JavaScript had used some symbol other than + for string concatenation.

Step (1) Concatenate "1", "2", "3" into "123"

result = "1" + "2" + "3";

Step (2) Convert "123" into 123

result = +"123";

Step (3) Add 123 + 100 = 223

result = 123 + 100;

Step (4) Convert 223 into "223"

result = "" + 223;

If you know WHY these work, you're less likely to get into trouble with JavaScript expressions.

Exception : mockito wanted but not invoked, Actually there were zero interactions with this mock

@Jk1's answer is fine, but Mockito also allows for more succinct injection using annotations:

@InjectMocks MyClass myClass; //@InjectMocks automatically instantiates too
@Mock MyInterface myInterface

But regardless of which method you use, the annotations are not being processed (not even your @Mock) unless you somehow call the static MockitoAnnotation.initMocks() or annotate the class with @RunWith(MockitoJUnitRunner.class).

Why does checking a variable against multiple values with `OR` only check the first value?

If you want case-insensitive comparison, use lower or upper:

if name.lower() == "jesse":

CSS to hide INPUT BUTTON value text

The difference some of you are seeing in solutions that work or not in the different IEs may be due to having compatibility mode on or off. In IE8, text-indent works just fine unless compatibility mode is turned on. If compatibility mode is on, then font-size and line-height do the trick but can mess up Firefox's display.

So we can use a css hack to let firefox ignore our ie rule.. like so...

*font-size: 0px; line-height: 0;

is there a css hack for safari only NOT chrome?

There is a way to filter Safari 5+ from Chrome:

@media screen and (-webkit-min-device-pixel-ratio:0) { 
    /* Safari and Chrome */
    .myClass {

    /* Safari only override */
    ::i-block-chrome,.myClass {

Oracle "(+)" Operator

The (+) operator indicates an outer join. This means that Oracle will still return records from the other side of the join even when there is no match. For example if a and b are emp and dept and you can have employees unassigned to a department then the following statement will return details of all employees whether or not they've been assigned to a department.

select * from emp, dept where emp.dept_id=dept.dept_id(+)

So in short, removing the (+) may make a significance difference but you might not notice for a while depending on your data!

How to get the URL without any parameters in JavaScript?

You can use a regular expression: window.location.href.match(/^[^\#\?]+/)[0]

How do I determine if a port is open on a Windows server?

On Windows Server you can use

netstat -an | where{$_.Contains("Yourport")}

how we add or remove readonly attribute from textbox on clicking radion button in cakephp using jquery?

In your Case you can write the following jquery code:



     var rBtnVal = $(this).val();

     if(rBtnVal == "yes"){
         $("#no_of_staff").attr("readonly", false); 
         $("#no_of_staff").attr("readonly", true); 

Here is the Fiddle:

Unable to call the built in mb_internal_encoding method?

For OpenSUse (zypper package manager):

zypper install php5-mbstring


zyper install php7-mbstring

In the other hand, you can search them through YaST Software manager.

Note that, you must restart apache http server:

systemctl restart apache2.service

How can I delete a newline if it is the last character in a file?


ruby -ne 'print $stdin.eof ? $_.strip : $_'


ruby -ane 'q=p;p=$_;puts q if $.>1;END{print p.strip!}'

creating Hashmap from a JSON String

Parse the JSONObject and create HashMap

public static void jsonToMap(String t) throws JSONException {

        HashMap<String, String> map = new HashMap<String, String>();
        JSONObject jObject = new JSONObject(t);
        Iterator<?> keys = jObject.keys();

        while( keys.hasNext() ){
            String key = (String);
            String value = jObject.getString(key); 
            map.put(key, value);


        System.out.println("json : "+jObject);
        System.out.println("map : "+map);

Tested output:

json : {"phonetype":"N95","cat":"WP"}
map : {cat=WP, phonetype=N95}

Showing/Hiding Table Rows with Javascript - can do with ID - how to do with Class?

JQuery 10.1.2 has a nice show and hide functions that encapsulate the behavior you are talking about. This would save you having to write a new function or keep track of css classes.



w3cSchool link to JQuery show and hide

Decode UTF-8 with Javascript

This is what I found after a more specific Google search than just UTF-8 encode/decode. so for those who are looking for a converting library to convert between encodings, here you go.

var uint8array = new TextEncoder().encode(str);
var str = new TextDecoder(encoding).decode(uint8array);

Paste from repo readme

All encodings from the Encoding specification are supported:

utf-8 ibm866 iso-8859-2 iso-8859-3 iso-8859-4 iso-8859-5 iso-8859-6 iso-8859-7 iso-8859-8 iso-8859-8-i iso-8859-10 iso-8859-13 iso-8859-14 iso-8859-15 iso-8859-16 koi8-r koi8-u macintosh windows-874 windows-1250 windows-1251 windows-1252 windows-1253 windows-1254 windows-1255 windows-1256 windows-1257 windows-1258 x-mac-cyrillic gb18030 hz-gb-2312 big5 euc-jp iso-2022-jp shift_jis euc-kr replacement utf-16be utf-16le x-user-defined

(Some encodings may be supported under other names, e.g. ascii, iso-8859-1, etc. See Encoding for additional labels for each encoding.)

How to fix .pch file missing on build?

In case this is happening to you on a server build (AppCenter) and yo uaer using CocoaPods ensure that your Podfile is checked in.

AppCenter only runs the "pod install" command if it finds a Pofile and it DOES NOT find the PODS folder on the files.

I had the folder checked-in, but because git automatically ignores .pch files (check you .gitignore to veryfy this), my .pch weren'nt being checked in.

I sorted my issue by forcing the .pch files to check it, but Deleting the PODS folder should work too, since Appcenter will run the pod install command in that case.

Hoppefully this helps somebody.

find -mtime files older than 1 hour

What about -mmin?

find /var/www/html/audio -daystart -maxdepth 1 -mmin +59 -type f -name "*.mp3" \
    -exec rm -f {} \;

From man find:

-mmin n
        File's data was last modified n minutes ago.

Also, make sure to test this first!

... -exec echo rm -f '{}' \;
          ^^^^ Add the 'echo' so you just see the commands that are going to get
               run instead of actual trying them first.

C#: calling a button event handler method without actually clicking the button

Simply call:

btnTest_Click(null, null);

Just make sure you aren't trying to use either of those params in the function.

Spring boot Security Disable security

The only thing that worked for me:

    protected void configure(HttpSecurity http) throws Exception {



Could be that the properties part is redundant or can be done in code, but had no time to experiment. Anyway is temporary.

Add left/right horizontal padding to UILabel

If you want to add padding to UILabel but not want to subclass it you can put your label in a UIView and give paddings with autolayout like:

Padding with UIView and autolayout



How to correctly use Html.ActionLink with ASP.NET MVC 4 Areas

Below are some of the way by which you can create a link button in MVC.

@Html.ActionLink("Admin", "Index", "Home", new { area = "Admin" }, null)  
@Html.RouteLink("Admin", new { action = "Index", controller = "Home", area = "Admin" })  
@Html.Action("Action", "Controller", new { area = "AreaName" })  
@Url.Action("Action", "Controller", new { area = "AreaName" })  
<a class="ui-btn" data-val="abc" href="/Home/Edit/ANTON">Edit</a>  
<a data-ajax="true" data-ajax-method="GET" data-ajax-mode="replace" data-ajax-update="#CustomerList" href="/Home/Germany">Customer from Germany</a>  
<a data-ajax="true" data-ajax-method="GET" data-ajax-mode="replace" data-ajax-update="#CustomerList" href="/Home/Mexico">Customer from Mexico</a> 

Hope this will help you.

Numpy array dimensions

import numpy as np   
>>> np.shape(a)

Also works if the input is not a numpy array but a list of lists

>>> a = [[1,2],[1,2]]
>>> np.shape(a)

Or a tuple of tuples

>>> a = ((1,2),(1,2))
>>> np.shape(a)

How to order results with findBy() in Doctrine

$ens = $em->getRepository('AcmeBinBundle:Marks')
                 array('id' => 'ASC')

Converting Select results into Insert script - SQL Server

I think its also possible with adhoc queries you can export result to excel file and then import that file into your datatable object or use it as it is and then import the excel file into the second database have a look at this link this can help u alot.

You need to use a Theme.AppCompat theme (or descendant) with this activity

This is when you want a AlertDialog in a Fragment

            AlertDialog.Builder adb = new AlertDialog.Builder(getActivity());
            adb.setTitle("My alert Dialogue \n");
            adb.setPositiveButton("OK", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {

                  //some code

            } });
            adb.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {


                } });

Convert a string to a double - is this possible?

Just use floatval().


$var = '122.34343';
$float_value_of_var = floatval($var);
echo $float_value_of_var; // 122.34343

And in case you wonder doubleval() is just an alias for floatval().

And as the other say, in a financial application, float values are critical as these are not precise enough. E.g. adding two floats could result in something like 12.30000000001 and this error could propagate.

sendmail: how to configure sendmail on ubuntu?

When you typed in sudo sendmailconfig, you should have been prompted to configure sendmail.

For reference, the files that are updated during configuration are located at the following (in case you want to update them manually):


You can test sendmail to see if it is properly configured and setup by typing the following into the command line:

$ echo "My test email being sent from sendmail" | /usr/sbin/sendmail [email protected]

The following will allow you to add smtp relay to sendmail:

#Change to your mail config directory:
cd /etc/mail

#Make a auth subdirectory
mkdir auth
chmod 700 auth

#Create a file with your auth information to the smtp server
cd auth
touch client-info

#In the file, put the following, matching up to your smtp server: "U:root" "I:user" "P:password"

#Generate the Authentication database, make both files readable only by root
makemap hash client-info < client-info
chmod 600 client-info
cd ..

Add the following lines to, but before the MAILERDEFINITIONS. Make sure you update your smtp server.

FEATURE(`authinfo',`hash -o /etc/mail/auth/client-info.db')dnl

Invoke creation (alternatively run make -C /etc/mail):

m4 >

Restart the sendmail daemon:

service sendmail restart

How to get a pixel's x,y coordinate color from an image?

Building on Jeff's answer, your first step would be to create a canvas representation of your PNG. The following creates an off-screen canvas that is the same width and height as your image and has the image drawn on it.

var img = document.getElementById('my-image');
var canvas = document.createElement('canvas');
canvas.width = img.width;
canvas.height = img.height;
canvas.getContext('2d').drawImage(img, 0, 0, img.width, img.height);

After that, when a user clicks, use event.offsetX and event.offsetY to get the position. This can then be used to acquire the pixel:

var pixelData = canvas.getContext('2d').getImageData(event.offsetX, event.offsetY, 1, 1).data;

Because you are only grabbing one pixel, pixelData is a four entry array containing the pixel's R, G, B, and A values. For alpha, anything less than 255 represents some level of transparency with 0 being fully transparent.

Here is a jsFiddle example: I used jQuery for convenience in all of this, but it is by no means required.

Note: getImageData falls under the browser's same-origin policy to prevent data leaks, meaning this technique will fail if you dirty the canvas with an image from another domain or (I believe, but some browsers may have solved this) SVG from any domain. This protects against cases where a site serves up a custom image asset for a logged in user and an attacker wants to read the image to get information. You can solve the problem by either serving the image from the same server or implementing Cross-origin resource sharing.

jQuery function after .append

I have another variant which may be useful for someone:

$('<img src="">').load(function() {

Python send UDP packet

Here is a complete example that has been tested with Python 2.7.5 on CentOS 7.


import sys, socket

def main(args):
    ip = args[1]
    port = int(args[2])
    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    file = 'sample.csv'

    fp = open(file, 'r')
    for line in fp:
        sock.sendto(line.encode('utf-8'), (ip, port))


The program reads a file, sample.csv from the current directory and sends each line in a separate UDP packet. If the program it were saved in a file named send-udp then one could run it by doing something like:

$ python send-udp 30088

How do I disable the security certificate check in Python requests

Also can be done from the environment variable:

export CURL_CA_BUNDLE=""

Count all duplicates of each value

SELECT number, COUNT(*)
    FROM YourTable
    GROUP BY number
    ORDER BY number

Insertion sort vs Bubble Sort Algorithms

Number of swap in each iteration

  • Insertion-sort does at most 1 swap in each iteration.
  • Bubble-sort does 0 to n swaps in each iteration.

Accessing and changing sorted part

  • Insertion-sort accesses(and changes when needed) the sorted part to find the correct position of a number in consideration.
  • When optimized, Bubble-sort does not access what is already sorted.

Online or not

  • Insertion-sort is online. That means Insertion-sort takes one input at a time before it puts in appropriate position. It does not have to compare only adjacent-inputs.
  • Bubble-sort is not-online. It does not operate one input at a time. It handles a group of inputs(if not all) in each iteration. Bubble-sort only compare and swap adjacent-inputs in each iteration.

How to embed images in html email

You have to encode your email as multipart mime and then you can attach emails as attachments basically. You reference them by cid in the email.

Alternatively you could not attach them to the email and use URLs directly but most mail programs will block this as spammers use the trick to detect the liveness of email addresses.

You don't say what language but here is one example.

IIs Error: Application Codebehind=“Global.asax.cs” Inherits=“nadeem.MvcApplication”

Same issue i faced , when copy the project from another system. In my case i fixed this issue:

delete everythings from inside Bin folder. Clean & Rebuild the app again

Hope this will help.

How can I add the sqlite3 module to Python?

For Python version 3:

pip install pysqlite3 

Git: How to squash all commits on branch

Another simple way to do this: go on the origin branch and do a merge --squash. This command doesn't do the "squashed" commit. when you do it, all commit messages of yourBranch will be gathered.

$ git checkout master
$ git merge --squash yourBranch
$ git commit # all commit messages of yourBranch in one, really useful
 > [status 5007e77] Squashed commit of the following: ...

CSS div 100% height

Set the html tag, too. This way no weird position hacks are required.

html, body {height: 100%}

CSV with comma or semicolon?

best way will be to save it in a text file with csv extension:

Sub ExportToCSV()
Dim i, j As Integer
Dim Name  As String

Dim pathfile As String

Dim fs As Object
    Dim stream As Object

    Set fs = CreateObject("Scripting.FileSystemObject")
On Error GoTo fileexists

i = 15
Name = Format(Now(), "ddmmyyHHmmss")
pathfile = "D:\1\" & Name & ".csv"

Set stream = fs.CreateTextFile(pathfile, False, True)


If Err.Number = 58 Then
    MsgBox "File already Exists"
    'Your code here
End If
On Error GoTo 0

j = 1
Do Until IsEmpty(ThisWorkbook.ActiveSheet.Cells(i, 1).Value)

    stream.WriteLine (ThisWorkbook.Worksheets(1).Cells(i, 1).Value & ";" & Replace(ThisWorkbook.Worksheets(1).Cells(i, 6).Value, ".", ","))

    j = j + 1
    i = i + 1


End Sub

Count number of tables in Oracle

Select count(*) FROM all_tables where owner='schema_name'

How to find out which processes are using swap space in Linux?

The top command also contains a field to display the number of page faults for a process. The process with maximum page faults would be the process which is swapping most. For long running daemons it might be that they incur large number of page faults at the beginning and the number does not increase later on. So we need to observe whether the page faults is increasing.

How do I bottom-align grid elements in bootstrap fluid layout

Here's also an angularjs directive to implement this functionality

    pullDown: function() {
      return {
        restrict: 'A',
        link: function ($scope, iElement, iAttrs) {
          var $parent = iElement.parent();
          var $parentHeight = $parent.height();
          var height = iElement.height();

          iElement.css('margin-top', $parentHeight - height);

How to run a C# application at Windows startup?

If you could not set your application autostart you can try to paste this code to manifest

<requestedExecutionLevel  level="asInvoker" uiAccess="false" />

or delete manifest I had found it in my application

jQuery changing font family and font size

If you only want to change the font in the TEXTAREA then you only need to change the changeFont() function in the original code to:

function changeFont(_name) {
    document.getElementById("mytextarea").style.fontFamily = _name;

Then selecting a font will change on the font only in the TEXTAREA.

Trying Gradle build - "Task 'build' not found in root project"


gradle clean 

then try

gradle build 

it worked for me

Is it possible to use global variables in Rust?

Look at the const and static section of the Rust book.

You can use something as follows:

const N: i32 = 5; 


static N: i32 = 5;

in global space.

But these are not mutable. For mutability, you could use something like:

static mut N: i32 = 5;

Then reference them like:

unsafe {
    N += 1;

    println!("N: {}", N);

Warning: require_once(): http:// wrapper is disabled in the server configuration by allow_url_include=0

You have to put the path to the file. For example:


You cannot get the file to require it from internet (with http protocol) it's restricted. The files must be on the same server. With Possibility to see each others (rights)

Dir-1 -
         > Folder-1 -> a.php
Dir-2 -
         > Folder-2 -> b.php

To include a.php inside b.php => require_once('../../Dir-1/Folder-1/a.php');
To include b.php inside a.php => require_once('../../Dir-2/Folder-2/b.php');

How to find EOF through fscanf?

while (fscanf(input,"%s",arr) != EOF && count!=7) {

Why am I not getting a java.util.ConcurrentModificationException in this example?

I had that same problem but in case that I was adding en element into iterated list. I made it this way

public static void remove(Integer remove) {
    for(int i=0; i<integerList.size(); i++) {
        //here is maybe fine to deal with integerList.get(i)==null
        if(integerList.get(i).equals(remove)) {                

Now everything goes fine because you don't create any iterator over your list, you iterate over it "manually". And condition i < integerList.size() will never fool you because when you remove/add something into List size of the List decrement/increment..

Hope it helps, for me that was solution.

Difference between and logger.debug

This is a very old question, but i don't see my understanding here so I will add my 2 cents:

Every level corresponds/maps to a type of user:

  • debug : developer - manual debugging
  • trace : automated logging and step tracer - for 3rd level support
  • info : technician / support level 1 /2
  • warn : technician / user error : automated alert / support level 1
  • critical/fatal : depends on your setup - local IT

jQuery: Check if div with certain class name exists

Here are some ways:

1.  if($("div").hasClass("mydivclass")){
    //Your code

    //It returns true if any div has 'mydivclass' name. It is a based on the class name

2. if($("#myid1").hasClass("mydivclass")){
    //Your code

    //  It returns true if specific div(myid1) has this class "mydivclass" name. 
    //  It is a  based on the specific div id's.
3. if($("div[class='mydivclass']").length > 0){
    //Your code

   // It returns all the divs whose class name is "mydivclass"
   //  and it's length would be greater than one.

We can use any one of the abobe defined ways based on the requirement.