Programs & Examples On #Qbfc

The QuickBooks Foundation Classes (qbfc) are a COM Library for interoping with QuickBooks products from Intuit Software

How to split elements of a list?

Do not use list as variable name. You can take a look at the following code too:

clist = ['element1\t0238.94', 'element2\t2.3904', 'element3\t0139847', 'element5']
clist = [x[:x.index('\t')] if '\t' in x else x for x in clist]

Or in-place editing:

for i,x in enumerate(clist):
    if '\t' in x:
        clist[i] = x[:x.index('\t')]

How might I find the largest number contained in a JavaScript array?

_x000D_
_x000D_
var nums = [1,4,5,3,1,4,7,8,6,2,1,4];
nums.sort();
nums.reverse();
alert(nums[0]);
_x000D_
_x000D_
_x000D_

Simplest Way:

var nums = [1,4,5,3,1,4,7,8,6,2,1,4]; nums.sort(); nums.reverse(); alert(nums[0]);

What are some great online database modeling tools?

You may want to look at IBExpert Personal Edition. While not open source, this is a very good tool for designing, building, and administering Firebird and InterBase databases.

The Personal Edition is free, but some of the more advanced features are not available. Still, even without the slick extras, the free version is very powerful.

Xcode is not currently available from the Software Update server

I know this is an old post but I also ran into this problem today. I found out that when I executed sudo softwareupdate -l the Command Line Tools were listed as an update, so I installed them using sudo softwareupdate -i -a.

ExpressionChangedAfterItHasBeenCheckedError Explained

My issue was manifest when I added *ngIf but that wasn't the cause. The error was caused by changing the model in {{}} tags then trying to display the changed model in the *ngIf statement later on. Here's an example:

<div>{{changeMyModelValue()}}</div> <!--don't do this!  or you could get error: ExpressionChangedAfterItHasBeenCheckedError-->
....
<div *ngIf="true">{{myModel.value}}</div>

To fix the issue, I changed where I called changeMyModelValue() to a place that made more sense.

In my situation I wanted changeMyModelValue() called whenever a child component changed the data. This required I create and emit an event in the child component so the parent could handle it (by calling changeMyModelValue(). see https://angular.io/guide/component-interaction#parent-listens-for-child-event

Preventing twitter bootstrap carousel from auto sliding on page load

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

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

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

Create, read, and erase cookies with jQuery

Use jquery cookie plugin, the link as working today: https://github.com/js-cookie/js-cookie

login to remote using "mstsc /admin" with password

the command posted by Milad and Sandy did not work for me with mstsc. i had to add TERMSRV to the /generic switch. i found this information here: https://gist.github.com/jdforsythe/48a022ee22c8ec912b7e

cmdkey /generic:TERMSRV/<server> /user:<username> /pass:<password>

i could then use mstsc /v:<server> without getting prompted for the login.

How do I evenly add space between a label and the input field regardless of length of text?

This can be accomplished using the brand new CSS display: grid (browser support)

HTML:

<div class='container'>
  <label for="dummy1">title for dummy1:</label>
  <input id="dummy1" name="dummy1" value="dummy1">
  <label for="dummy2">longer title for dummy2:</label>
  <input id="dummy2" name="dummy2" value="dummy2">
  <label for="dummy3">even longer title for dummy3:</label>
  <input id="dummy3" name="dummy3" value="dummy3">
</div>

CSS:

.container {
  display: grid;
  grid-template-columns: 1fr 3fr;
}

When using css grid, by default elements are laid out column by column then row by row. The grid-template-columns rule creates two grid columns, one which takes up 1/4 of the total horizontal space and the other which takes up 3/4 of the horizontal space. This creates the desired effect.

grid

JS-FIDDLE

How to make an installer for my C# application?

Generally speaking, it's recommended to use MSI-based installations on Windows. Thus, if you're ready to invest a fair bit of time, WiX is the way to go.

If you want something which is much more simpler, go with InnoSetup.

What's the C# equivalent to the With statement in VB?

Not really, you have to assign a variable. So

    var bar = Stuff.Elements.Foo;
    bar.Name = "Bob Dylan";
    bar.Age = 68;
    bar.Location = "On Tour";
    bar.IsCool = True;

Or in C# 3.0:

    var bar = Stuff.Elements.Foo
    {
        Name = "Bob Dylan",
        Age = 68,
        Location = "On Tour",
        IsCool = True
    };

Check if one date is between two dates

Try this

var gdate='01-05-2014';
        date =Date.parse(gdate.split('-')[1]+'-'+gdate.split('-')[0]+'-'+gdate.split('-')[2]);
        if(parseInt(date) < parseInt(Date.now()))
        {
            alert('small');
        }else{
            alert('big');
        }

Fiddle

StringBuilder vs String concatenation in toString() in Java

There seems to be some debate whether using StringBuilder is still needed with current compilers. So I thought I'll give my 2 cents of experience.

I have a JDBC result set of 10k records (yes, I need all of them in one batch.) Using the + operator takes about 5 minutes on my machine with Java 1.8. Using stringBuilder.append("") takes less than a second for the same query.

So the difference is huge. Inside a loop StringBuilder is much faster.

app-release-unsigned.apk is not signed

signingConfigs should be before buildTypes

signingConfigs {
        debug {
            storeFile file("debug.keystore")
        }

        myConfig {
            storeFile file("other.keystore")
            storePassword "android"
            keyAlias "androidotherkey"
            keyPassword "android"
        }
    }

    buildTypes {
        bar {
            debuggable true
            jniDebugBuild true
            signingConfig signingConfigs.debug
        }
        foo {
            debuggable false
            jniDebugBuild false
            signingConfig signingConfigs.myConfig
        }
    }

SQL Server: the maximum number of rows in table

These are some of the Maximum Capacity Specifications for SQL Server 2008 R2

  • Database size: 524,272 terabytes
  • Databases per instance of SQL Server: 32,767
  • Filegroups per database: 32,767
  • Files per database: 32,767
  • File size (data): 16 terabytes
  • File size (log): 2 terabytes
  • Rows per table: Limited by available storage
  • Tables per database: Limited by number of objects in a database

How do I add a Maven dependency in Eclipse?

In fact when you open the pom.xml, you should see 5 tabs in the bottom. Click the pom.xml, and you can type whatever dependencies you want.

enter image description here

Detect all changes to a <input type="text"> (immediately) using JQuery

This is the fastest& clean way to do that :

I'm using Jquery-->

$('selector').on('change', function () {
    console.log(this.id+": "+ this.value);
});

It is working pretty fine for me.

Checking out Git tag leads to "detached HEAD state"

Okay, first a few terms slightly oversimplified.

In git, a tag (like many other things) is what's called a treeish. It's a way of referring to a point in in the history of the project. Treeishes can be a tag, a commit, a date specifier, an ordinal specifier or many other things.

Now a branch is just like a tag but is movable. When you are "on" a branch and make a commit, the branch is moved to the new commit you made indicating it's current position.

Your HEAD is pointer to a branch which is considered "current". Usually when you clone a repository, HEAD will point to master which in turn will point to a commit. When you then do something like git checkout experimental, you switch the HEAD to point to the experimental branch which might point to a different commit.

Now the explanation.

When you do a git checkout v2.0, you are switching to a commit that is not pointed to by a branch. The HEAD is now "detached" and not pointing to a branch. If you decide to make a commit now (as you may), there's no branch pointer to update to track this commit. Switching back to another commit will make you lose this new commit you've made. That's what the message is telling you.

Usually, what you can do is to say git checkout -b v2.0-fixes v2.0. This will create a new branch pointer at the commit pointed to by the treeish v2.0 (a tag in this case) and then shift your HEAD to point to that. Now, if you make commits, it will be possible to track them (using the v2.0-fixes branch) and you can work like you usually would. There's nothing "wrong" with what you've done especially if you just want to take a look at the v2.0 code. If however, you want to make any alterations there which you want to track, you'll need a branch.

You should spend some time understanding the whole DAG model of git. It's surprisingly simple and makes all the commands quite clear.

Capture keyboardinterrupt in Python without try-except

If someone is in search for a quick minimal solution,

import signal

# The code which crashes program on interruption

signal.signal(signal.SIGINT, call_this_function_if_interrupted)

# The code skipped if interrupted

Reading rows from a CSV file in Python

#  This program reads columns in a csv file
import csv
ifile = open('years.csv', "r")
reader = csv.reader(ifile)

# initialization and declaration of variables
rownum = 0
year = 0
dec = 0
jan = 0
total_years = 0`

for row in reader:
    if rownum == 0:
        header = row  #work with header row if you like
    else:
    colnum = 0
    for col in row:
        if colnum == 0:
            year = float(col)
        if colnum == 1:
            dec = float(col)
        if colnum == 2:
            jan = float(col)
        colnum += 1
    # end of if structure

# now we can process results
if rownum != 0:
    print(year, dec, jan)
    total_years = total_years + year
    print(total_years)

# time to go after the next row/bar
rownum += 1

ifile.close()

A bit late but nonetheless... You need to create and identify the csv file named "years.csv":

Year Dec Jan 1 50 60 2 25 50 3 30 30 4 40 20 5 10 10

What is a mutex?

Mutexes are useful in situations where you need to enforce exclusive access to a resource accross multiple processes, where a regular lock won't help since it only works accross threads.

Pass values of checkBox to controller action in asp.net mvc4

None of the previous solutions worked for me. Finally I found that the action should be coded as:

public ActionResult Index(string MyCheck = null)

and then, when checked the passed value was "on", not "true". Else, it is always null.

Hope it helps somebody!

How to add buttons like refresh and search in ToolBar in Android?

Add this line at the top:

"xmlns:app="http://schemas.android.com/apk/res-auto"

and then use:

app:showasaction="ifroom"

Flask Value error view function did not return a response

You are not returning a response object from your view my_form_post. The function ends with implicit return None, which Flask does not like.

Make the function my_form_post return an explicit response, for example

return 'OK'

at the end of the function.

Java regex email

You can checking if emails is valid or no by using this libreries, and of course you can add array for this folowing project.

import org.apache.commons.validator.routines.EmailValidator;

public class Email{
    public static void main(String[] args){
        EmailValidator email = EmailVlidator.getInstance();
        boolean val = email.isValid("[email protected]");
        System.out.println("Mail is: "+val);
        val = email.isValid("hans.riguer.hotmsil.com");
        System.out.print("Mail is: "+val");
    }
}

output :

Mail is: true

Mail is : false

Use of "this" keyword in C++

Yes. unless, there is an ambiguity.

Why is my power operator (^) not working?

Instead of using ^, use 'pow' function which is a predefined function which performs the Power operation and it can be used by including math.h header file.

^ This symbol performs BIT-WISE XOR operation in C, C++.

Replace a^i with pow(a,i).

How can I loop over entries in JSON?

Actually, to query the team_name, just add it in brackets to the last line. Apart from that, it seems to work on Python 2.7.3 on command line.

from urllib2 import urlopen
import json

url = 'http://openligadb-json.heroku.com/api/teams_by_league_saison?league_saison=2012&league_shortcut=bl1'
response = urlopen(url)
json_obj = json.load(response)

for i in json_obj['team']:
    print i['team_name']

Binding ConverterParameter

No, unfortunately this will not be possible because ConverterParameter is not a DependencyProperty so you won't be able to use bindings

But perhaps you could cheat and use a MultiBinding with IMultiValueConverter to pass in the 2 Tag properties.

Pandas merge two dataframes with different columns

I think in this case concat is what you want:

In [12]:

pd.concat([df,df1], axis=0, ignore_index=True)
Out[12]:
   attr_1  attr_2  attr_3  id  quantity
0       0       1     NaN   1        20
1       1       1     NaN   2        23
2       1       1     NaN   3        19
3       0       0     NaN   4        19
4       1     NaN       0   5         8
5       0     NaN       1   6        13
6       1     NaN       1   7        20
7       1     NaN       1   8        25

by passing axis=0 here you are stacking the df's on top of each other which I believe is what you want then producing NaN value where they are absent from their respective dfs.

How can I merge two commits into one if I already started rebase?

Assuming you were in your own topic branch. If you want to merge the last 2 commits into one and look like a hero, branch off the commit just before you made the last two commits (specified with the relative commit name HEAD~2).

git checkout -b temp_branch HEAD~2

Then squash commit the other branch in this new branch:

git merge branch_with_two_commits --squash

That will bring in the changes but not commit them. So just commit them and you're done.

git commit -m "my message"

Now you can merge this new topic branch back into your main branch.

how to convert JSONArray to List of Object using camel-jackson

I also faced the similar problem with JSON output format. This code worked for me with the above JSON format.

package com.test.ameba;

import java.util.List;

public class OutputRanges {
    public List<Range> OutputRanges;
    public String Message;
    public String Entity;

    /**
     * @return the outputRanges
     */
    public List<Range> getOutputRanges() {
        return OutputRanges;
    }

    /**
     * @param outputRanges the outputRanges to set
     */
    public void setOutputRanges(List<Range> outputRanges) {
        OutputRanges = outputRanges;
    }

    /**
     * @return the message
     */
    public String getMessage() {
        return Message;
    }

    /**
     * @param message the message to set
     */
    public void setMessage(String message) {
        Message = message;
    }

    /**
     * @return the entity
     */
    public String getEntity() {
        return Entity;
    }

    /**
     * @param entity the entity to set
     */
    public void setEntity(String entity) {
        Entity = entity;
    }
}

package com.test;


public class Range {
    public String Name;
    /**
     * @return the name
     */
    public String getName() {
        return Name;
    }
    /**
     * @param name the name to set
     */
    public void setName(String name) {
        Name = name;
    }

    public Object[] Value;
    /**
     * @return the value
     */
    public Object[] getValue() {
        return Value;
    }
    /**
     * @param value the value to set
     */
    public void setValue(Object[] value) {
        Value = value;
    }

}

package com.test.ameba;

import java.io.IOException;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;

public class JSONTest {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        String jsonString ="{\"OutputRanges\":[{\"Name\":\"ABF_MEDICAL_RELATIVITY\",\"Value\":[[1.3628407124839714]]},{\"Name\":\" ABF_RX_RELATIVITY\",\"Value\":[[\"CPD\",\"SL Limit\",\"Concat\",1,1.5,2,2.5,3]]},{\"Name\":\" ABF_Unique_ID_ERR\",\"Value\":[[\"CPD\",\"SL Limit\",\"Concat\",1,1.5,2,2.5,3]]},{\"Name\":\" ABF_FIRST_ERR\",\"Value\":[[\"CPD\",\"SL Limit\",\"Concat\",1,1.5,2,2.5,3]]},{\"Name\":\" ABF_AMEBA_ERR\",\"Value\":[[\"CPD\",\"SL Limit\",\"Concat\",1,1.5,2,2.5,3]]},{\"Name\":\" ABF_Effective_Date_ERR\",\"Value\":[[\"CPD\",\"SL Limit\",\"Concat\",1,1.5,2,2.5,3]]},{\"Name\":\" ABF_AMEBA_MODEL\",\"Value\":[[\"CPD\",\"SL Limit\",\"Concat\",1,1.5,2,2.5,3]]},{\"Name\":\" ABF_UC_ER_COPAY_ERR\",\"Value\":[[\"CPD\",\"SL Limit\",\"Concat\",1,1.5,2,2.5,3]]},{\"Name\":\" ABF_INN_OON_DED_ERR\",\"Value\":[[\"CPD\",\"SL Limit\",\"Concat\",1,1.5,2,2.5,3]]},{\"Name\":\" ABF_COINSURANCE_ERR\",\"Value\":[[\"CPD\",\"SL Limit\",\"Concat\",1,1.5,2,2.5,3]]},{\"Name\":\" ABF_PCP_SPEC_COPAY_ERR\",\"Value\":[[\"CPD\",\"SL Limit\",\"Concat\",1,1.5,2,2.5,3]]},{\"Name\":\" ABF_INN_OON_OOP_MAX_ERR\",\"Value\":[[\"CPD\",\"SL Limit\",\"Concat\",1,1.5,2,2.5,3]]},{\"Name\":\" ABF_IP_OP_COPAY_ERR\",\"Value\":[[\"CPD\",\"SL Limit\",\"Concat\",1,1.5,2,2.5,3]]},{\"Name\":\" ABF_PHARMACY_ERR\",\"Value\":[[\"CPD\",\"SL Limit\",\"Concat\",1,1.5,2,2.5,3]]},{\"Name\":\" ABF_PLAN_ADMIN_ERR\",\"Value\":[[\"CPD\",\"SL Limit\",\"Concat\",1,1.5,2,2.5,3]]}],\"Message\":\"\",\"Entity\":null}";
        ObjectMapper mapper = new ObjectMapper();
        OutputRanges OutputRanges=null;
        try {
            OutputRanges = mapper.readValue(jsonString, OutputRanges.class);
        } catch (JsonParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (JsonMappingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        System.out.println("OutputRanges :: "+OutputRanges);;
        System.out.println("OutputRanges.getOutputRanges() :: "+OutputRanges.getOutputRanges());;
        for (Range r : OutputRanges.getOutputRanges()) {
            System.out.println(r.getName());
        }
    }

}

"Couldn't read dependencies" error with npm

I got this error when I had a space in my "name" within the packagae.json file.

"NPM Project" rather than "NPMProject"

How to stretch in width a WPF user control to its window?

The Canvas in WPF doesn't provide much automatic layout support. I try to steer clear of them for this reason (HorizontalAlignment and VerticalAlignment don't work as expected), but I got your code to work with these minor modifications (binding the Width and Height of the control to the canvas's ActualWidth/ActualHeight).

<Window x:Class="TCI.Indexer.UI.Operacao"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:tci="clr-namespace:TCI.Indexer.UI.Controles"
Title=" " MinHeight="550" MinWidth="675" Loaded="Load" 
ResizeMode="NoResize" WindowStyle="None" WindowStartupLocation="CenterScreen" 
WindowState="Maximized" Focusable="True" x:Name="windowOperacao">

<Canvas x:Name="canv">
    <Grid>
        <tci:Status x:Name="ucStatus" Width="{Binding ElementName=canv
                                                    , Path=ActualWidth}" 
                                      Height="{Binding ElementName=canv
                                                    , Path=ActualHeight}"/> 
        <!-- the control which I want to stretch in width -->
    </Grid>
</Canvas>

The Canvas is the problem here. If you're not actually utilizing the features the canvas offers in terms of layout or Z-Order "squashing" (think of the flatten command in PhotoShop), I would consider using a control like a Grid instead so you don't end up having to learn the quirks of a control that works differently than you have come to expect with WPF.

Check if a value exists in pandas dataframe index

This should do the trick

'g' in df.index

How to replace plain URLs with links?

Reg Ex: /(\b((https?|ftp|file):\/\/|(www))[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|]*)/ig

function UriphiMe(text) {
      var exp = /(\b((https?|ftp|file):\/\/|(www))[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|]*)/ig; 
      return text.replace(exp,"<a href='$1'>$1</a>");
}

Below are some tested string:

  1. Find me on to www.google.com
  2. www
  3. Find me on to www.http://www.com
  4. Follow me on : http://www.nishantwork.wordpress.com
  5. http://www.nishantwork.wordpress.com
  6. Follow me on : http://www.nishantwork.wordpress.com
  7. https://stackoverflow.com/users/430803/nishant

Note: If you don't want to pass www as valid one just use below reg ex: /(\b((https?|ftp|file):\/\/|(www))[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig

Refresh Part of Page (div)

Let's assume that you have 2 divs inside of your html file.

<div id="div1">some text</div>
<div id="div2">some other text</div>

The java program itself can't update the content of the html file because the html is related to the client, meanwhile java is related to the back-end.

You can, however, communicate between the server (the back-end) and the client.

What we're talking about is AJAX, which you achieve using JavaScript, I recommend using jQuery which is a common JavaScript library.

Let's assume you want to refresh the page every constant interval, then you can use the interval function to repeat the same action every x time.

setInterval(function()
{
    alert("hi");
}, 30000);

You could also do it like this:

setTimeout(foo, 30000);

Whereea foo is a function.

Instead of the alert("hi") you can perform the AJAX request, which sends a request to the server and receives some information (for example the new text) which you can use to load into the div.

A classic AJAX looks like this:

var fetch = true;
var url = 'someurl.java';
$.ajax(
{
    // Post the variable fetch to url.
    type : 'post',
    url : url,
    dataType : 'json', // expected returned data format.
    data : 
    {
        'fetch' : fetch // You might want to indicate what you're requesting.
    },
    success : function(data)
    {
        // This happens AFTER the backend has returned an JSON array (or other object type)
        var res1, res2;

        for(var i = 0; i < data.length; i++)
        {
            // Parse through the JSON array which was returned.
            // A proper error handling should be added here (check if
            // everything went successful or not)

            res1 = data[i].res1;
            res2 = data[i].res2;

            // Do something with the returned data
            $('#div1').html(res1);
        }
    },
    complete : function(data)
    {
        // do something, not critical.
    }
});

Wherea the backend is able to receive POST'ed data and is able to return a data object of information, for example (and very preferrable) JSON, there are many tutorials out there with how to do so, GSON from Google is something that I used a while back, you could take a look into it.

I'm not professional with Java POST receiving and JSON returning of that sort so I'm not going to give you an example with that but I hope this is a decent start.

Laravel check if collection is empty

You can always count the collection. For example $mentor->intern->count() will return how many intern does a mentor have.

https://laravel.com/docs/5.2/collections#method-count

In your code you can do something like this

foreach($mentors as $mentor)
    @if($mentor->intern->count() > 0)
    @foreach($mentor->intern as $intern)
        <tr class="table-row-link" data-href="/werknemer/{!! $intern->employee->EmployeeId !!}">
            <td>{{ $intern->employee->FirstName }}</td>
            <td>{{  $intern->employee->LastName }}</td>
        </tr>
    @endforeach
    @else
        Mentor don't have any intern
    @endif
@endforeach

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

To compare entire revisions, it's simply:

svn diff -r 8979:11390


If you want to compare the last committed state against your currently saved working files, you can use convenience keywords:

svn diff -r PREV:HEAD

(Note, without anything specified afterwards, all files in the specified revisions are compared.)


You can compare a specific file if you add the file path afterwards:

svn diff -r 8979:HEAD /path/to/my/file.php

PostgreSQL DISTINCT ON with different ORDER BY

It can also be solved using the following query along with other answers.

WITH purchase_data AS (
        SELECT address_id, purchased_at, product_id,
                row_number() OVER (PARTITION BY address_id ORDER BY purchased_at DESC) AS row_number
        FROM purchases
        WHERE product_id = 1)
SELECT address_id, purchased_at, product_id
FROM purchase_data where row_number = 1

LINQ - Full Outer Join

Full outer join for two or more tables: First extract the column that you want to join on.

var DatesA = from A in db.T1 select A.Date; 
var DatesB = from B in db.T2 select B.Date; 
var DatesC = from C in db.T3 select C.Date;            

var Dates = DatesA.Union(DatesB).Union(DatesC); 

Then use left outer join between the extracted column and main tables.

var Full_Outer_Join =

(from A in Dates
join B in db.T1
on A equals B.Date into AB 

from ab in AB.DefaultIfEmpty()
join C in db.T2
on A equals C.Date into ABC 

from abc in ABC.DefaultIfEmpty()
join D in db.T3
on A equals D.Date into ABCD

from abcd in ABCD.DefaultIfEmpty() 
select new { A, ab, abc, abcd })
.AsEnumerable();

Find the similarity metric between two strings

Fuzzy Wuzzy is a package that implements Levenshtein distance in python, with some helper functions to help in certain situations where you may want two distinct strings to be considered identical. For example:

>>> fuzz.ratio("fuzzy wuzzy was a bear", "wuzzy fuzzy was a bear")
    91
>>> fuzz.token_sort_ratio("fuzzy wuzzy was a bear", "wuzzy fuzzy was a bear")
    100

How do I convert uint to int in C#?

Take note of the checked and unchecked keywords.

It matters if you want the result truncated to the int or an exception raised if the result doesnt fit in signed 32 bits. The default is unchecked.

Change tab bar item selected color in a storyboard

In Swift, using xcode 7 (and later), you can add the following to your AppDelegate.swift file:

UITabBar.appearance().tintColor = UIColor(red: 255/255.0, green: 255/255.0, blue: 255/255.0, alpha: 1.0)

This is the what the complete method looks like:

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {

    // I added this line
    UITabBar.appearance().tintColor = UIColor(red: 255/255.0, green: 255/255.0, blue: 255/255.0, alpha: 1.0)

    return true
}

In the example above my item will be white. The "/255.0" is needed because it expects a value from 0 to 1. For white, I could have just used 1. But for other color you'll probably be using RGB values.

How to get the jQuery $.ajax error response text?

This will allow you to see the whole response not just the "responseText" value

error: function(xhr, status, error) {
    var acc = []
    $.each(xhr, function(index, value) {
        acc.push(index + ': ' + value);
    });
    alert(JSON.stringify(acc));
}

How to deselect a selected UITableView cell?

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    tableView.deselectRow(at: indexPath, animated: true)
}

How to Round to the nearest whole number in C#

Use Math.Round:

double roundedValue = Math.Round(value, 0)

How do I check if the Java JDK is installed on Mac?

You can leverage the java_home helper binary on OS X for what you're looking for.

To list all versions of installed JDK:

$ /usr/libexec/java_home -V
Matching Java Virtual Machines (2):
    1.8.0_51, x86_64:   "Java SE 8" /Library/Java/JavaVirtualMachines/jdk1.8.0_51.jdk/Contents/Home
    1.7.0_79, x86_64:   "Java SE 7" /Library/Java/JavaVirtualMachines/jdk1.7.0_79.jdk/Contents/Home

To request the JAVA_HOME path of a specific JDK version, you can do:

$ /usr/libexec/java_home -v 1.7
/Library/Java/JavaVirtualMachines/jdk1.7.0_79.jdk/Contents/Home

$ /usr/libexec/java_home -v 1.8
/Library/Java/JavaVirtualMachines/jdk1.8.0_51.jdk/Contents/Home

You could take advantage of the above commands in your script like this:

REQUESTED_JAVA_VERSION="1.7"
if POSSIBLE_JAVA_HOME="$(/usr/libexec/java_home -v $REQUESTED_JAVA_VERSION 2>/dev/null)"; then
    # Do this if you want to export JAVA_HOME
    export JAVA_HOME="$POSSIBLE_JAVA_HOME"
    echo "Java SDK is installed"
else
    echo "Did not find any installed JDK for version $REQUESTED_JAVA_VERSION"
fi

You might be able to do if-else and check for multiple different versions of java as well.

If you prefer XML output, java_home also has a -X option to output in XML.

$ /usr/libexec/java_home --help
Usage: java_home [options...]
    Returns the path to a Java home directory from the current user's settings.

Options:
    [-v/--version   <version>]       Filter Java versions in the "JVMVersion" form 1.X(+ or *).
    [-a/--arch      <architecture>]  Filter JVMs matching architecture (i386, x86_64, etc).
    [-d/--datamodel <datamodel>]     Filter JVMs capable of -d32 or -d64
    [-t/--task      <task>]          Use the JVM list for a specific task (Applets, WebStart, BundledApp, JNI, or CommandLine)
    [-F/--failfast]                  Fail when filters return no JVMs, do not continue with default.
    [   --exec      <command> ...]   Execute the $JAVA_HOME/bin/<command> with the remaining arguments.
    [-R/--request]                   Request installation of a Java Runtime if not installed.
    [-X/--xml]                       Print full JVM list and additional data as XML plist.
    [-V/--verbose]                   Print full JVM list with architectures.
    [-h/--help]                      This usage information.

Excel VBA Loop on columns

Another method to try out. Also select could be replaced when you set the initial column into a Range object. Performance wise it helps.

Dim rng as Range

Set rng = WorkSheets(1).Range("A1") '-- you may change the sheet name according to yours.

'-- here is your loop
i = 1
Do
   '-- do something: e.g. show the address of the column that you are currently in
   Msgbox rng.offset(0,i).Address 
   i = i + 1
Loop Until i > 10

** Two methods to get the column name using column number**

  • Split()

code

colName = Split(Range.Offset(0,i).Address, "$")(1)
  • String manipulation:

code

Function myColName(colNum as Long) as String
    myColName = Left(Range(0, colNum).Address(False, False), _ 
    1 - (colNum > 10)) 
End Function 

error: package javax.servlet does not exist

The answer provided by @Matthias Herlitzius is mostly correct. Just for further clarity.

The servlet-api jar is best left up to the server to manage see here for detail

With that said, the dependency to add may vary according to your server/container. For example in Wildfly the dependency would be

<dependency>
    <groupId>org.jboss.spec.javax.servlet</groupId>
    <artifactId>jboss-servlet-api_3.1_spec</artifactId>
    <scope>provided</scope>
</dependency>

So becareful to check how your container has provided the servlet implementation.

JFrame: How to disable window resizing?

it's easy to use:

frame.setResizable(false);

How can I get the file name from request.FILES?

NOTE if you are using python 3.x:

request.FILES is a multivalue dictionary like object that keeps the files uploaded through an upload file button. Say in your html code the name of the button (type="file") is "myfile" so "myfile" will be the key in this dictionary. If you uploaded one file, then the value for this key will be only one and if you uploaded multiple files, then you will have multiple values for that specific key. If you use request.FILES['myfile'] you will get the first or last value (I cannot say for sure). This is fine if you only uploaded one file, but if you want to get all files you should do this:

list=[] #myfile is the key of a multi value dictionary, values are the uploaded files
for f in request.FILES.getlist('myfile'): #myfile is the name of your html file button
    filename = f.name
    list.append(filename)

of course one can squeeze the whole thing in one line, but this is easy to understand

Hiding a button in Javascript

Something like this should remove it

document.getElementById('x').style.visibility='hidden';

If you are going to do alot of this dom manipulation might be worth looking at jquery

What is LDAP used for?

To take the definitions the other mentioned earlier a bit further, how about this perspective...

LDAP is Lightweight Directory Access Protocol. DAP, is an X.500 notion, and in X.500 is VERY heavy weight! (It sort of requires a full 7 layer ISO network stack, which basically only IBM's SNA protocol ever realistically implemented).

There are many other approaches to DAP. Novell has one called NDAP (NCP Novell Core Protocols are the transport, and NDAP is how it reads the directory).

LDAP is just a very lightweight DAP, as the name suggests.

ASP.NET MVC: What is the purpose of @section?

You want to use sections when you want a bit of code/content to render in a placeholder that has been defined in a layout page.

In the specific example you linked, he has defined the RenderSection in the _Layout.cshtml. Any view that uses that layout can define an @section of the same name as defined in Layout, and it will replace the RenderSection call in the layout.

Perhaps you're wondering how we know Index.cshtml uses that layout? This is due to a bit of MVC/Razor convention. If you look at the dialog where he is adding the view, the box "Use layout or master page" is checked, and just below that it says "Leave empty if it is set in a Razor _viewstart file". It isn't shown, but inside that _ViewStart.cshtml file is code like:

@{
    Layout = "~/Views/Shared/_Layout.cshtml";
}

The way viewstarts work is that any cshtml file within the same directory or child directories will run the ViewStart before it runs itself.

Which is what tells us that Index.cshtml uses Shared/_Layout.cshtml.

Removing an element from an Array (Java)

Your question isn't very clear. From your own answer, I can tell better what you are trying to do:

public static String[] removeElements(String[] input, String deleteMe) {
    List result = new LinkedList();

    for(String item : input)
        if(!deleteMe.equals(item))
            result.add(item);

    return result.toArray(input);
}

NB: This is untested. Error checking is left as an exercise to the reader (I'd throw IllegalArgumentException if either input or deleteMe is null; an empty list on null list input doesn't make sense. Removing null Strings from the array might make sense, but I'll leave that as an exercise too; currently, it will throw an NPE when it tries to call equals on deleteMe if deleteMe is null.)

Choices I made here:

I used a LinkedList. Iteration should be just as fast, and you avoid any resizes, or allocating too big of a list if you end up deleting lots of elements. You could use an ArrayList, and set the initial size to the length of input. It likely wouldn't make much of a difference.

Username and password in command for git push

For anyone having issues with passwords with special chars just omit the password and it will prompt you for it:

git push https://[email protected]/YOUR_GIT_USERNAME/yourGitFileName.git

spring data jpa @query and pageable

I tried all above solution and non worked , finally I removed the Sorting from Pagination and it worked

Can a table row expand and close?

To answer your question, no. That would be possible with div though. THe only question is would cause a hazzle if the functionality were done with div rather than tables.

Get the current fragment object

Maybe the simplest way is:

public MyFragment getVisibleFragment(){
    FragmentManager fragmentManager = MainActivity.this.getSupportFragmentManager();
    List<Fragment> fragments = fragmentManager.getFragments();
    for(Fragment fragment : fragments){
        if(fragment != null && fragment.getUserVisibleHint())
            return (MyFragment)fragment;
    }
    return null;
}

It worked for me

sequelize findAll sort order in nodejs

If you are using MySQL, you can use order by FIELD(id, ...) approach:

Company.findAll({
    where: {id : {$in : companyIds}},
    order: sequelize.literal("FIELD(company.id,"+companyIds.join(',')+")")
})

Keep in mind, it might be slow. But should be faster, than manual sorting with JS.

"Mixed content blocked" when running an HTTP AJAX operation in an HTTPS page

I had the same issue with Axios requests in a Vue-CLI App. On further checking in Network tab of Chrome, I found that the request URL of axios correctly had https but response 'location' header was http.

This was caused by nginx and I fixed it by adding these 2 lines to server config for nginx:

server {
    ...
    add_header Strict-Transport-Security "max-age=31536000" always;
    add_header Content-Security-Policy upgrade-insecure-requests;
    ...
}

Might be irrelevant but my Vue-CLI App was served under a subpath in nginx with config as:

location ^~ /admin {
        alias   /home/user/apps/app_admin/dist;
        index  index.html;
        try_files $uri $uri/ /index.html;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Host $host;
}

ArrayList or List declaration in Java

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

Is generic where you want to hide implementation details while returning it to client, at later point of time you may change implementation from ArrayList to LinkedList transparently.

This mechanism is useful in cases where you design libraries etc., which may change their implementation details at some point of time with minimal changes on client side.

ArrayList<String> arrayList = new ArrayList<String>();

This mandates you always need to return ArrayList. At some point of time if you would like to change implementation details to LinkedList, there should be changes on client side also to use LinkedList instead of ArrayList.

C++ error 'Undefined reference to Class::Function()'

In the definition of your Card class, a declaration for a default construction appears:

class Card
{
    // ...

    Card(); // <== Declaration of default constructor!

    // ...
};

But no corresponding definition is given. In fact, this function definition (from card.cpp):

void Card() {
//nothing
}

Does not define a constructor, but rather a global function called Card that returns void. You probably meant to write this instead:

Card::Card() {
//nothing
}

Unless you do that, since the default constructor is declared but not defined, the linker will produce error about undefined references when a call to the default constructor is found.


The same applies to your constructor accepting two arguments. This:

void Card(Card::Rank rank, Card::Suit suit) {
    cardRank = rank;
    cardSuit = suit;
}

Should be rewritten into this:

Card::Card(Card::Rank rank, Card::Suit suit) {
    cardRank = rank;
    cardSuit = suit;
}

And the same also applies for other member functions: it seems you did not add the Card:: qualifier before the member function names in their definitions. Without it, those functions are global functions rather than definitions of member functions.


Your destructor, on the other hand, is declared but never defined. Just provide a definition for it in card.cpp:

Card::~Card() { }

Duplicate symbols for architecture x86_64 under Xcode

For anyone else who is having this issue, I didn't see my resolution in any of these answers.

After having a .pbxproj merge conflict which was manually addressed (albeit poorly), there were duplicate references to individual class files in the .pbxproj. Deleting those from the Project > Build Phases > Compile Sources fixed everything for me.

Hope this helps someone down the line.

SHA-1 fingerprint of keystore certificate

Using Google Play app signing feature & Google APIs integration in your app?

  1. If you are using Google Play App Signing, don't forget that release signing-certificate fingerprint needed for Google API credentials is not the regular upload signing keys (SHA-1) you obtain from your app by this method:

Upload signing certificate

  1. You can obtain your release SHA-1 only from App signing page of your Google Play console as shown below:-

If you use Google Play app signing, Google re-signs your app. Thats how your signing-certificate fingerprint is given by Google Play App Signing as shown below:

App Signing page - Google Play Console

Read more How to get Release SHA-1 (Signing-certificate fingerprint) if using 'Google Play app signing'

Installing a local module using npm?

From the npm-link documentation:

In the local module directory:

$ cd ./package-dir
$ npm link

In the directory of the project to use the module:

$ cd ./project-dir
$ npm link package-name

Or in one go using relative paths:

$ cd ./project-dir
$ npm link ../package-dir

This is equivalent to using two commands above under the hood.

Creating a div element inside a div element in javascript

Yes, you either need to do this onload or in a <script> tag after the closing </body> tag, when the lc element is already found in the document's DOM tree.

How to make Java 6, which fails SSL connection with "SSL peer shut down incorrectly", succeed like Java 7?

It seems that in the debug log for Java 6 the request is send in SSLv2 format.

main, WRITE: SSLv2 client hello message, length = 110

This is not mentioned as enabled by default in Java 7.
Change the client to use SSLv3 and above to avoid such interoperability issues.

Look for differences in JSSE providers in Java 7 and Java 6

How do I automatically resize an image for a mobile site?

You can use the following css to resize the image for mobile view

object-fit: scale-down; max-width: 100%

How to safely open/close files in python 2.4

In the above solution, repeated here:

f = open('file.txt', 'r')

try:
    # do stuff with f
finally:
   f.close()

if something bad happens (you never know ...) after opening the file successfully and before the try, the file will not be closed, so a safer solution is:

f = None
try:
    f = open('file.txt', 'r')

    # do stuff with f

finally:
    if f is not None:
       f.close()

Processing $http response in service

As far as caching the response in service is concerned , here's another version that seems more straight forward than what I've seen so far:

App.factory('dataStorage', function($http) {
     var dataStorage;//storage for cache

     return (function() {
         // if dataStorage exists returned cached version
        return dataStorage = dataStorage || $http({
      url: 'your.json',
      method: 'GET',
      cache: true
    }).then(function (response) {

              console.log('if storage don\'t exist : ' + response);

              return response;
            });

    })();

});

this service will return either the cached data or $http.get;

 dataStorage.then(function(data) {
     $scope.data = data;
 },function(e){
    console.log('err: ' + e);
 });

sort files by date in PHP

I use your exact proposed code with only some few additional lines. The idea is more or less the same of the one proposed by @elias, but in this solution there cannot be conflicts on the keys since each file in the directory has a different filename and so adding it to the key solves the conflicts. The first part of the key is the datetime string formatted in a manner such that I can lexicographically compare two of them.

if ($handle = opendir('.')) {
    $result = array();
    while (false !== ($file = readdir($handle))) {
        if ($file != "." && $file != "..") {
            $lastModified = date('F d Y, H:i:s',filemtime($file));
            if(strlen($file)-strpos($file,".swf")== 4){
                $result [date('Y-m-d H:i:s',filemtime($file)).$file] =
                    "<tr><td><input type=\"checkbox\" name=\"box[]\"></td><td><a href=\"$file\" target=\"_blank\">$file</a></td><td>$lastModified</td></tr>";
            }
        }
    }
    closedir($handle);
    krsort($result);
    echo implode('', $result);
}

Rails - Could not find a JavaScript runtime?

if you already install nodejs from source for example, and execjs isn't recognizing it you might want to try this tip: https://coderwall.com/p/hyjdlw

What are unit tests, integration tests, smoke tests, and regression tests?

Unit test: testing of an individual module or independent component in an application is known to be unit testing. The unit testing will be done by the developer.

Integration test: combining all the modules and testing the application to verify the communication and the data flow between the modules are working properly or not. This testing also performed by developers.

Smoke test In a smoke test they check the application in a shallow and wide manner. In smoke testing they check the main functionality of the application. If there is any blocker issue in the application they will report to developer team, and the developing team will fix it and rectify the defect, and give it back to the testing team. Now testing team will check all the modules to verify that changes made in one module will impact the other module or not. In smoke testing the test cases are scripted.

Regression testing executing the same test cases repeatedly to ensure tat the unchanged module does not cause any defect. Regression testting comes under functional testing

move a virtual machine from one vCenter to another vCenter

A much simpler way to do this is to use vCenter Converter Standalone Client and do a P2V but in this case a V2V. It is much faster than copying the entire VM files onto some storage somewhere and copy it onto your new vCenter. It takes a long time to copy or exporting it to an OVF template and then import it. You can set your vCenter Converter Standalone Client to V2V in one step and synchronize and then have it power up the VM on the new Vcenter and shut off on the old vCenter. Simple.

For me using this method I was able to move a VM from one vCenter to another vCenter in about 30 minutes as compared to copying or exporting which took over 2hrs. Your results may vary.


This process below, from another responder, would work even better if you can present that datastore to ESXi servers on the vCenter and then follow step 2. Eliminating having to copy all the VMs then follow rest of the process.

  1. Copy all of the cloned VM's files from its directory, and place it on its destination datastore.
  2. In the VI client connected to the destination vCenter, go to the Inventory->Datastores view.
  3. Open the datastore browser for the datastore where you placed the VM's files.
  4. Find the .vmx file that you copied over and right-click it.
  5. Choose 'Register Virtual Machine', and follow whatever prompts ensue. (Depending on your version of vCenter, this may be 'Add to Inventory' or some other variant)

How do I stretch an image to fit the whole background (100% height x 100% width) in Flutter?

Try setting contentPadding

ListTile(
  contentPadding: EdgeInsets.all(0.0),
  ...
)

How do I add a newline to a windows-forms TextBox?

You can try this :

"This is line-1 \r\n This is line-2"

PHP Parse HTML code

Use PHP Document Object Model:

<?php
   $str = '<h1>T1</h1>Lorem ipsum.<h1>T2</h1>The quick red fox...<h1>T3</h1>... jumps over the lazy brown FROG';
   $DOM = new DOMDocument;
   $DOM->loadHTML($str);

   //get all H1
   $items = $DOM->getElementsByTagName('h1');

   //display all H1 text
   for ($i = 0; $i < $items->length; $i++)
        echo $items->item($i)->nodeValue . "<br/>";
?>

This outputs as:

 T1
 T2
 T3

[EDIT]: After OP Clarification:

If you want the content like Lorem ipsum. etc, you can directly use this regex:

<?php
   $str = '<h1>T1</h1>Lorem ipsum.<h1>T2</h1>The quick red fox...<h1>T3</h1>... jumps over the lazy brown FROG';
   echo preg_replace("#<h1.*?>.*?</h1>#", "", $str);
?>

this outputs:

Lorem ipsum.The quick red fox...... jumps over the lazy brown FROG

Number of regex matches

I know this is a little old, but this but here is a concise function for counting regex patterns.

def regex_cnt(string, pattern):
    return len(re.findall(pattern, string))

string = 'abc123'

regex_cnt(string, '[0-9]')

Rails.env vs RAILS_ENV

Strange behaviour while debugging my app: require "active_support/notifications" (rdb:1) p ENV['RAILS_ENV'] "test" (rdb:1) p Rails.env "development"

I would say that you should stick to one or another (and preferably Rails.env)

How to write a file with C in Linux?

You need to write() the read() data into the new file:

ssize_t nrd;
int fd;
int fd1;

fd = open(aa[1], O_RDONLY);
fd1 = open(aa[2], O_CREAT | O_WRONLY, S_IRUSR | S_IWUSR);
while (nrd = read(fd,buffer,50)) {
    write(fd1,buffer,nrd);
}

close(fd);
close(fd1);

Update: added the proper opens...

Btw, the O_CREAT can be OR'd (O_CREAT | O_WRONLY). You are actually opening too many file handles. Just do the open once.

Shell script "for" loop syntax

Well, as I didn't have the seq command installed on my system (Mac OS X v10.6.1 (Snow Leopard)), I ended up using a while loop instead:

max=5
i=1

while [ $max -gt $i ]
do
    (stuff)
done

*Shrugs* Whatever works.

Command to open file with git

Assuming you are inside your repository root folder

alias notepad="/c/Program\ Files\ \(x86\)/Notepad++/notepad++.exe"

then you can open any file with Notepad++ with:

notepad readme.md

iTunes Connect: How to choose a good SKU?

I put the year and the number series of my app example 2014-01

What is the bit size of long on 64-bit Windows?

This article on MSDN references a number of type aliases (available on Windows) that are a bit more explicit with respect to their width:

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

For instance, although you can use ULONGLONG to reference a 64-bit unsigned integral value, you can also use UINT64. (The same goes for ULONG and UINT32.) Perhaps these will be a bit clearer?

How to iterate through two lists in parallel?

Building on the answer by @unutbu, I have compared the iteration performance of two identical lists when using Python 3.6's zip() functions, Python's enumerate() function, using a manual counter (see count() function), using an index-list, and during a special scenario where the elements of one of the two lists (either foo or bar) may be used to index the other list. Their performances for printing and creating a new list, respectively, were investigated using the timeit() function where the number of repetitions used was 1000 times. One of the Python scripts that I had created to perform these investigations is given below. The sizes of the foo and bar lists had ranged from 10 to 1,000,000 elements.

Results:

  1. For printing purposes: The performances of all the considered approaches were observed to be approximately similar to the zip() function, after factoring an accuracy tolerance of +/-5%. An exception occurred when the list size was smaller than 100 elements. In such a scenario, the index-list method was slightly slower than the zip() function while the enumerate() function was ~9% faster. The other methods yielded similar performance to the zip() function.

    Print loop 1000 reps

  2. For creating lists: Two types of list creation approaches were explored: using the (a) list.append() method and (b) list comprehension. After factoring an accuracy tolerance of +/-5%, for both of these approaches, the zip() function was found to perform faster than the enumerate() function, than using a list-index, than using a manual counter. The performance gain by the zip() function in these comparisons can be 5% to 60% faster. Interestingly, using the element of foo to index bar can yield equivalent or faster performances (5% to 20%) than the zip() function.

    Creating List - 1000reps

Making sense of these results:

A programmer has to determine the amount of compute-time per operation that is meaningful or that is of significance.

For example, for printing purposes, if this time criterion is 1 second, i.e. 10**0 sec, then looking at the y-axis of the graph that is on the left at 1 sec and projecting it horizontally until it reaches the monomials curves, we see that lists sizes that are more than 144 elements will incur significant compute cost and significance to the programmer. That is, any performance gained by the approaches mentioned in this investigation for smaller list sizes will be insignificant to the programmer. The programmer will conclude that the performance of the zip() function to iterate print statements is similar to the other approaches.

Conclusion

Notable performance can be gained from using the zip() function to iterate through two lists in parallel during list creation. When iterating through two lists in parallel to print out the elements of the two lists, the zip() function will yield similar performance as the enumerate() function, as to using a manual counter variable, as to using an index-list, and as to during the special scenario where the elements of one of the two lists (either foo or bar) may be used to index the other list.

The Python3.6 Script that was used to investigate list creation.

import timeit
import matplotlib.pyplot as plt
import numpy as np


def test_zip( foo, bar ):
    store = []
    for f, b in zip(foo, bar):
        #print(f, b)
        store.append( (f, b) ) 

def test_enumerate( foo, bar ):
    store = []
    for n, f in enumerate( foo ):
        #print(f, bar[n])
        store.append( (f, bar[n]) ) 

def test_count( foo, bar ):
    store = []
    count = 0
    for f in foo:
        #print(f, bar[count])
        store.append( (f, bar[count]) )
        count += 1

def test_indices( foo, bar, indices ):
    store = []
    for i in indices:
        #print(foo[i], bar[i])
        store.append( (foo[i], bar[i]) )

def test_existing_list_indices( foo, bar ):
    store = []
    for f in foo:
        #print(f, bar[f])
        store.append( (f, bar[f]) )


list_sizes = [ 10, 100, 1000, 10000, 100000, 1000000 ]
tz = []
te = []
tc = []
ti = []
tii= []

tcz = []
tce = []
tci = []
tcii= []

for a in list_sizes:
    foo = [ i for i in range(a) ]
    bar = [ i for i in range(a) ]
    indices = [ i for i in range(a) ]
    reps = 1000

    tz.append( timeit.timeit( 'test_zip( foo, bar )',
                              'from __main__ import test_zip, foo, bar',
                              number=reps
                              )
               )
    te.append( timeit.timeit( 'test_enumerate( foo, bar )',
                              'from __main__ import test_enumerate, foo, bar',
                              number=reps
                              )
               )
    tc.append( timeit.timeit( 'test_count( foo, bar )',
                              'from __main__ import test_count, foo, bar',
                              number=reps
                              )
               )
    ti.append( timeit.timeit( 'test_indices( foo, bar, indices )',
                              'from __main__ import test_indices, foo, bar, indices',
                              number=reps
                              )
               )
    tii.append( timeit.timeit( 'test_existing_list_indices( foo, bar )',
                               'from __main__ import test_existing_list_indices, foo, bar',
                               number=reps
                               )
                )

    tcz.append( timeit.timeit( '[(f, b) for f, b in zip(foo, bar)]',
                               'from __main__ import foo, bar',
                               number=reps
                               )
                )
    tce.append( timeit.timeit( '[(f, bar[n]) for n, f in enumerate( foo )]',
                               'from __main__ import foo, bar',
                               number=reps
                               )
                )
    tci.append( timeit.timeit( '[(foo[i], bar[i]) for i in indices ]',
                               'from __main__ import foo, bar, indices',
                               number=reps
                               )
                )
    tcii.append( timeit.timeit( '[(f, bar[f]) for f in foo ]',
                                'from __main__ import foo, bar',
                                number=reps
                                )
                 )

print( f'te  = {te}' )
print( f'ti  = {ti}' )
print( f'tii = {tii}' )
print( f'tc  = {tc}' )
print( f'tz  = {tz}' )

print( f'tce  = {te}' )
print( f'tci  = {ti}' )
print( f'tcii = {tii}' )
print( f'tcz  = {tz}' )

fig, ax = plt.subplots( 2, 2 )
ax[0,0].plot( list_sizes, te, label='enumerate()', marker='.' )
ax[0,0].plot( list_sizes, ti, label='index-list', marker='.' )
ax[0,0].plot( list_sizes, tii, label='element of foo', marker='.' )
ax[0,0].plot( list_sizes, tc, label='count()', marker='.' )
ax[0,0].plot( list_sizes, tz, label='zip()', marker='.')
ax[0,0].set_xscale('log')
ax[0,0].set_yscale('log')
ax[0,0].set_xlabel('List Size')
ax[0,0].set_ylabel('Time (s)')
ax[0,0].legend()
ax[0,0].grid( b=True, which='major', axis='both')
ax[0,0].grid( b=True, which='minor', axis='both')

ax[0,1].plot( list_sizes, np.array(te)/np.array(tz), label='enumerate()', marker='.' )
ax[0,1].plot( list_sizes, np.array(ti)/np.array(tz), label='index-list', marker='.' )
ax[0,1].plot( list_sizes, np.array(tii)/np.array(tz), label='element of foo', marker='.' )
ax[0,1].plot( list_sizes, np.array(tc)/np.array(tz), label='count()', marker='.' )
ax[0,1].set_xscale('log')
ax[0,1].set_xlabel('List Size')
ax[0,1].set_ylabel('Performances ( vs zip() function )')
ax[0,1].legend()
ax[0,1].grid( b=True, which='major', axis='both')
ax[0,1].grid( b=True, which='minor', axis='both')

ax[1,0].plot( list_sizes, tce, label='list comprehension using enumerate()',  marker='.')
ax[1,0].plot( list_sizes, tci, label='list comprehension using index-list()',  marker='.')
ax[1,0].plot( list_sizes, tcii, label='list comprehension using element of foo',  marker='.')
ax[1,0].plot( list_sizes, tcz, label='list comprehension using zip()',  marker='.')
ax[1,0].set_xscale('log')
ax[1,0].set_yscale('log')
ax[1,0].set_xlabel('List Size')
ax[1,0].set_ylabel('Time (s)')
ax[1,0].legend()
ax[1,0].grid( b=True, which='major', axis='both')
ax[1,0].grid( b=True, which='minor', axis='both')

ax[1,1].plot( list_sizes, np.array(tce)/np.array(tcz), label='enumerate()', marker='.' )
ax[1,1].plot( list_sizes, np.array(tci)/np.array(tcz), label='index-list', marker='.' )
ax[1,1].plot( list_sizes, np.array(tcii)/np.array(tcz), label='element of foo', marker='.' )
ax[1,1].set_xscale('log')
ax[1,1].set_xlabel('List Size')
ax[1,1].set_ylabel('Performances ( vs zip() function )')
ax[1,1].legend()
ax[1,1].grid( b=True, which='major', axis='both')
ax[1,1].grid( b=True, which='minor', axis='both')

plt.show()

Resizing UITableView to fit content

I've tried this in iOS 7 and it worked for me

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self.tableView sizeToFit];
}

How do you add an action to a button programmatically in xcode

 CGRect buttonFrame = CGRectMake( x-pos, y-pos, width, height );   //
 CGRectMake(10,5,10,10) 

 UIButton *button = [[UIButton alloc] initWithFrame: buttonFrame];

 button setTitle: @"My Button" forState: UIControlStateNormal];

 [button addTarget:self action:@selector(btnClicked:) 
 forControlEvents:UIControlEventTouchUpInside];

 [button setTitleColor: [UIColor BlueVolor] forState:
 UIControlStateNormal];

 [view addSubview:button];




 -(void)btnClicked {
    // your code }

How to replace all dots in a string using JavaScript

Simplest way

"Mr.".split('.').join("");

..............

Console

enter image description here

using extern template (C++11)

extern template is only needed if the template declaration is complete

This was hinted at in other answers, but I don't think enough emphasis was given to it.

What this means is that in the OPs examples, the extern template has no effect because the template definitions on the headers were incomplete:

  • void f();: just declaration, no body
  • class foo: declares method f() but has no definition

So I would recommend just removing the extern template definition in that particular case: you only need to add them if the classes are completely defined.

For example:

TemplHeader.h

template<typename T>
void f();

TemplCpp.cpp

template<typename T>
void f(){}

// Explicit instantiation for char.
template void f<char>();

Main.cpp

#include "TemplHeader.h"

// Commented out from OP code, has no effect.
// extern template void f<T>(); //is this correct?

int main() {
    f<char>();
    return 0;
}

compile and view symbols with nm:

g++ -std=c++11 -Wall -Wextra -pedantic -c -o TemplCpp.o TemplCpp.cpp
g++ -std=c++11 -Wall -Wextra -pedantic -c -o Main.o Main.cpp
g++ -std=c++11 -Wall -Wextra -pedantic -o Main.out Main.o TemplCpp.o
echo TemplCpp.o
nm -C TemplCpp.o | grep f
echo Main.o
nm -C Main.o | grep f

output:

TemplCpp.o
0000000000000000 W void f<char>()
Main.o
                 U void f<char>()

and then from man nm we see that U means undefined, so the definition did stay only on TemplCpp as desired.

All this boils down to the tradeoff of complete header declarations:

  • upsides:
    • allows external code to use our template with new types
    • we have the option of not adding explicit instantiations if we are fine with object bloat
  • downsides:
    • when developing that class, header implementation changes will lead smart build systems to rebuild all includers, which could be many many files
    • if we want to avoid object file bloat, we need not only to do explicit instantiations (same as with incomplete header declarations) but also add extern template on every includer, which programmers will likely forget to do

Further examples of those are shown at: Explicit template instantiation - when is it used?

Since compilation time is so critical in large projects, I would highly recommend incomplete template declarations, unless external parties absolutely need to reuse your code with their own complex custom classes.

And in that case, I would first try to use polymorphism to avoid the build time problem, and only use templates if noticeable performance gains can be made.

Tested in Ubuntu 18.04.

How to get rid of "Unnamed: 0" column in a pandas DataFrame?

It's the index column, pass pd.to_csv(..., index=False) to not write out an unnamed index column in the first place, see the to_csv() docs.

Example:

In [37]:
df = pd.DataFrame(np.random.randn(5,3), columns=list('abc'))
pd.read_csv(io.StringIO(df.to_csv()))

Out[37]:
   Unnamed: 0         a         b         c
0           0  0.109066 -1.112704 -0.545209
1           1  0.447114  1.525341  0.317252
2           2  0.507495  0.137863  0.886283
3           3  1.452867  1.888363  1.168101
4           4  0.901371 -0.704805  0.088335

compare with:

In [38]:
pd.read_csv(io.StringIO(df.to_csv(index=False)))

Out[38]:
          a         b         c
0  0.109066 -1.112704 -0.545209
1  0.447114  1.525341  0.317252
2  0.507495  0.137863  0.886283
3  1.452867  1.888363  1.168101
4  0.901371 -0.704805  0.088335

You could also optionally tell read_csv that the first column is the index column by passing index_col=0:

In [40]:
pd.read_csv(io.StringIO(df.to_csv()), index_col=0)

Out[40]:
          a         b         c
0  0.109066 -1.112704 -0.545209
1  0.447114  1.525341  0.317252
2  0.507495  0.137863  0.886283
3  1.452867  1.888363  1.168101
4  0.901371 -0.704805  0.088335

How to build a 'release' APK in Android Studio?

Click \Build\Select Build Variant... in Android Studio. And choose release.

How do I execute a program using Maven?

With the global configuration that you have defined for the exec-maven-plugin:

<plugin>
  <groupId>org.codehaus.mojo</groupId>
  <artifactId>exec-maven-plugin</artifactId>
  <version>1.4.0</version>
  <configuration>
    <mainClass>org.dhappy.test.NeoTraverse</mainClass>
  </configuration>
</plugin>

invoking mvn exec:java on the command line will invoke the plugin which is configured to execute the class org.dhappy.test.NeoTraverse.

So, to trigger the plugin from the command line, just run:

mvn exec:java

Now, if you want to execute the exec:java goal as part of your standard build, you'll need to bind the goal to a particular phase of the default lifecycle. To do this, declare the phase to which you want to bind the goal in the execution element:

<plugin>
  <groupId>org.codehaus.mojo</groupId>
  <artifactId>exec-maven-plugin</artifactId>
  <version>1.4</version>
  <executions>
    <execution>
      <id>my-execution</id>
      <phase>package</phase>
      <goals>
        <goal>java</goal>
      </goals>
    </execution>
  </executions>
  <configuration>
    <mainClass>org.dhappy.test.NeoTraverse</mainClass>
  </configuration>
</plugin>

With this example, your class would be executed during the package phase. This is just an example, adapt it to suit your needs. Works also with plugin version 1.1.

Setting up FTP on Amazon Cloud Server

maybe worth mentioning in addition to clone45's answer:

Fixing Write Permissions for Chrooted FTP Users in vsftpd

The vsftpd version that comes with Ubuntu 12.04 Precise does not permit chrooted local users to write by default. By default you will have this in /etc/vsftpd.conf:

chroot_local_user=YES
write_enable=YES

In order to allow local users to write, you need to add the following parameter:

allow_writeable_chroot=YES

Note: Issues with write permissions may show up as following FileZilla errors:

Error: GnuTLS error -15: An unexpected TLS packet was received.
Error: Could not connect to server

References:
Fixing Write Permissions for Chrooted FTP Users in vsftpd
VSFTPd stopped working after update

How can I create a blank/hardcoded column in a sql query?

SELECT
    hat,
    shoe,
    boat,
    0 as placeholder -- for column having 0 value    
FROM
    objects


--OR '' as Placeholder -- for blank column    
--OR NULL as Placeholder -- for column having null value

Validate that text field is numeric usiung jQuery

This should work. I would trim the whitespace from the input field first of all:

if($('#Field').val() != "") {
    var value = $('#Field').val().replace(/^\s\s*/, '').replace(/\s\s*$/, '');
    var intRegex = /^\d+$/;
    if(!intRegex.test(value)) {
        errors += "Field must be numeric.<br/>";
        success = false;
    }
} else {
    errors += "Field is blank.</br />";
    success = false;
}

'Framework not found' in Xcode

1:- Delete the framework from the Xcode project. Quit the Xcode.

2:- Open your project in XCode and go to file under Menu and select Add files to "YourProjectName".

enter image description here

3:- Select "YourFramwork.framework" in the directory where you keep it.

4:- Click on the Copy items if needed checkbox.

5:- Click Add.

enter image description here

Make sure that you have the framework added in both Embedded Binaries and Linked Frameworks and Libraries under Target settings - General. As shown in the following images:-

enter image description here

enter image description here

sql - insert into multiple tables in one query

Multiple SQL statements must be executed with the mysqli_multi_query() function.

Example (MySQLi Object-oriented):

    <?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
} 

$sql = "INSERT INTO names (firstname, lastname)
VALUES ('inpute value here', 'inpute value here');";
$sql .= "INSERT INTO phones (landphone, mobile)
VALUES ('inpute value here', 'inpute value here');";

if ($conn->multi_query($sql) === TRUE) {
    echo "New records created successfully";
} else {
    echo "Error: " . $sql . "<br>" . $conn->error;
}

$conn->close();
?>

How to hide a mobile browser's address bar?

The easiest way to archive browser address bar hiding on page scroll is to add "display": "standalone", to manifest.json file.

Extreme wait-time when taking a SQL Server database offline

There is most likely a connection to the DB from somewhere (a rare example: asynchronous statistic update)

To find connections, use sys.sysprocesses

USE master
SELECT * FROM sys.sysprocesses WHERE dbid = DB_ID('MyDB')

To force disconnections, use ROLLBACK IMMEDIATE

USE master
ALTER DATABASE MyDB SET SINGLE_USER WITH ROLLBACK IMMEDIATE

Sending mass email using PHP

First off, using the mail() function that comes with PHP is not an optimal solution. It is easily marked as spammed, and you need to set up header to ensure that you are sending HTML emails correctly. As for whether the code snippet will work, it would, but I doubt you will get HTML code inside it correctly without specifying extra headers

I'll suggest you take a look at SwiftMailer, which has HTML support, support for different mime types and SMTP authentication (which is less likely to mark your mail as spam).

Simple http post example in Objective-C?

 NSMutableDictionary *contentDictionary = [[NSMutableDictionary alloc]init];
[contentDictionary setValue:@"name" forKey:@"email"];
[contentDictionary setValue:@"name" forKey:@"username"];
[contentDictionary setValue:@"name" forKey:@"password"];
[contentDictionary setValue:@"name" forKey:@"firstName"];
[contentDictionary setValue:@"name" forKey:@"lastName"];

NSData *data = [NSJSONSerialization dataWithJSONObject:contentDictionary options:NSJSONWritingPrettyPrinted error:nil];
NSString *jsonStr = [[NSString alloc] initWithData:data
                                          encoding:NSUTF8StringEncoding];
NSLog(@"%@",jsonStr);

NSString *urlString = [NSString stringWithFormat:@"http://testgcride.com:8081/v1/users"];
NSURL *url = [NSURL URLWithString:urlString];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:@"POST"];
   [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];


[request setHTTPBody:[jsonStr dataUsingEncoding:NSUTF8StringEncoding]];

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager.requestSerializer setAuthorizationHeaderFieldWithUsername:@"moinsam" password:@"cheese"];
manager.requestSerializer = [AFJSONRequestSerializer serializer];

AFHTTPRequestOperation *operation = [manager HTTPRequestOperationWithRequest:request success:<block> failure:<block>];

Java Date vs Calendar

  • Date and Calendar are really the same fundamental concept (both represent an instant in time and are wrappers around an underlying long value).

  • One could argue that Calendar is actually even more broken than Date is, as it seems to offer concrete facts about things like day of the week and time of day, whereas if you change its timeZone property, the concrete turns into blancmange! Neither objects are really useful as a store of year-month-day or time-of-day for this reason.

  • Use Calendar only as a calculator which, when given Date and TimeZone objects, will do calculations for you. Avoid its use for property typing in an application.

  • Use SimpleDateFormat together with TimeZone and Date to generate display Strings.

  • If you're feeling adventurous use Joda-Time, although it is unnecessarily complicated IMHO and is soon to be superceded by the JSR-310 date API in any event.

  • I have answered before that it is not difficult to roll your own YearMonthDay class, which uses Calendar under the hood for date calculations. I was downvoted for the suggestion but I still believe it is a valid one because Joda-Time (and JSR-310) are really so over-complicated for most use-cases.

How to search in a List of Java object

You can give a try to Apache Commons Collections.

There is a class CollectionUtils that allows you to select or filter items by custom Predicate.

Your code would be like this:

Predicate condition = new Predicate() {
   boolean evaluate(Object sample) {
        return ((Sample)sample).value3.equals("three");
   }
};
List result = CollectionUtils.select( list, condition );

Update:

In java8, using Lambdas and StreamAPI this should be:

List<Sample> result = list.stream()
     .filter(item -> item.value3.equals("three"))
     .collect(Collectors.toList());

much nicer!

How do I cancel form submission in submit button onclick event?

You need to return false;:

<input type='submit' value='submit request' onclick='return btnClick();' />

function btnClick() {
    return validData();
}

How to deploy ASP.NET webservice to IIS 7?

  1. rebuild project in VS
  2. copy project folder to iis folder, probably C:\inetpub\wwwroot\
  3. in iis manager (run>inetmgr) add website, point to folder, point application pool based on your .net
  4. add web service to created website, almost the same as 3.
  5. INSTALL ASP for windows 7 and .net 4.0: c:\windows\microsoft.net framework\v4.(some numbers)\regiis.exe -i
  6. check access to web service on your browser

How to pass the values from one jsp page to another jsp without submit button?

I am trying to Understand your Question and it seems that you want the values in the first JSP to be available in the Second JSP.

  1. It is very bad Habit to Place Java Code snippets Inside JSP file, so that code snippet should go to a servlet.

  2. Pick the values in a servlet ie.

    String username = request.getParameter("username");
    String password = request.getParameter("password");
    
  3. Then Store the Values inside the Session:

    HttpSession sess = request.getSession(); 
    sess.setAttribute("username", username);
    sess.setAttribute("password", password);
    
  4. These values Will be available anywhere in the Application as long as the session is valid.

    HttpSession sess = request.getSession(false); //use false to use the existing session
    sess.getAttribute("username");//this will return username anytime in the session
    sess.getAttribute("password");//this will return password Any time in the session
    

I hope this is what you wanted to know, but please do not use code snippets in the JSP. You can always get the values into the JSP using jstl in the JSPs:

 ${username}//this will give you the username in the JSP
 ${password}// this will give you the password in the JSP

Check an integer value is Null in c#

Because int is a ValueType then you can use the following code:

if(Age == default(int) || Age == null)

or

if(Age.HasValue && Age != 0) or if (!Age.HasValue || Age == 0)

How can I flush GPU memory using CUDA (physical reset is unavailable)

check what is using your GPU memory with

sudo fuser -v /dev/nvidia*

Your output will look something like this:

                     USER        PID  ACCESS COMMAND
/dev/nvidia0:        root       1256  F...m  Xorg
                     username   2057  F...m  compiz
                     username   2759  F...m  chrome
                     username   2777  F...m  chrome
                     username   20450 F...m  python
                     username   20699 F...m  python

Then kill the PID that you no longer need on htop or with

sudo kill -9 PID.

In the example above, Pycharm was eating a lot of memory so I killed 20450 and 20699.

Bringing a subview to be in front of all other views

As far as i experienced zposition is a best way.

self.view.layer.zPosition = 1;

Show "loading" animation on button click

try

$("#btnId").click(function(e){
 e.preventDefault();
 //show loading gif

 $.ajax({
  ...
  success:function(data){
   //remove gif
  },
  error:function(){//remove gif}

 });
});

EDIT: after reading the comments

in case you decide against ajax

$("#btnId").click(function(e){
     e.preventDefault();
     //show loading gif
     $(this).closest('form').submit();
});

How do I find out my MySQL URL, host, port and username?

Here are the default settings

default-username is root
default-password is null/empty //mean nothing
default-url is localhost or 127.0.0.1 for apache and
localhost/phpmyadmin for mysql // if you are using xampp/wamp/mamp
default-port = 3306

How to convert List to Json in Java

Look at the google gson library. It provides a rich api for dealing with this and is very straightforward to use.

Regular Expression For Duplicate Words

Regex to Strip 2+ duplicate words (consecutive/non-consecutive words)

Try this regex that can catch 2 or more duplicates words and only leave behind one single word. And the duplicate words need not even be consecutive.

/\b(\w+)\b(?=.*?\b\1\b)/ig

Here, \b is used for Word Boundary, ?= is used for positive lookahead, and \1 is used for back-referencing.

Example Source

Change placeholder text

For JavaScript use:

document.getElementsByClassName('select-holder')[0].placeholder = "This is my new text";

For jQuery use:

$('.select-holder')[0].placeholder = "This is my new text";

Squaring all elements in a list

One more map solution:

def square(a):
    return map(pow, a, [2]*len(a))

fatal: could not create work tree dir 'kivy'

Assuming that you are using Windows, run the application as Admin.

For that, you have at least two options:

• Open the file location, right click and select "Run as Administrator".

Run Git Bash as Admin

• Using Windows Start menu, search for "Git Bash", and you will find the following:

Git Bash using Windows Start Menu

Then, just press "Run as Administrator".

Setting default permissions for newly created files and sub-directories under a directory in Linux?

Here's how to do it using default ACLs, at least under Linux.

First, you might need to enable ACL support on your filesystem. If you are using ext4 then it is already enabled. Other filesystems (e.g., ext3) need to be mounted with the acl option. In that case, add the option to your /etc/fstab. For example, if the directory is located on your root filesystem:

/dev/mapper/qz-root   /    ext3    errors=remount-ro,acl   0  1

Then remount it:

mount -oremount /

Now, use the following command to set the default ACL:

setfacl -dm u::rwx,g::rwx,o::r /shared/directory

All new files in /shared/directory should now get the desired permissions. Of course, it also depends on the application creating the file. For example, most files won't be executable by anyone from the start (depending on the mode argument to the open(2) or creat(2) call), just like when using umask. Some utilities like cp, tar, and rsync will try to preserve the permissions of the source file(s) which will mask out your default ACL if the source file was not group-writable.

Hope this helps!

How to set image in imageview in android?

If you created ImageView from Java Class

ImageView img = new ImageView(this);

//Here we are setting the image in image view
img.setImageResource(R.drawable.my_image);

Android button with icon and text

For anyone looking to do this dynamically then setCompoundDrawables(Drawable left, Drawable top, Drawable right, Drawable bottom) on the buttons object will assist.

Sample

Button search = (Button) findViewById(R.id.yoursearchbutton);
search.setCompoundDrawables('your_drawable',null,null,null);

Fastest way to convert a dict's keys & values from `unicode` to `str`?

>>> d = {u"a": u"b", u"c": u"d"}
>>> d
{u'a': u'b', u'c': u'd'}
>>> import json
>>> import yaml
>>> d = {u"a": u"b", u"c": u"d"}
>>> yaml.safe_load(json.dumps(d))
{'a': 'b', 'c': 'd'}

jQuery: Currency Format Number

_x000D_
_x000D_
var input=950000; _x000D_
var output=parseInt(input).toLocaleString(); _x000D_
alert(output);
_x000D_
_x000D_
_x000D_

How to design RESTful search/filtering?

Don't fret too much if your initial API is fully RESTful or not (specially when you are just in the alpha stages). Get the back-end plumbing to work first. You can always do some sort of URL transformation/re-writing to map things out, refining iteratively until you get something stable enough for widespread testing ("beta").

You can define URIs whose parameters are encoded by position and convention on the URIs themselves, prefixed by a path you know you'll always map to something. I don't know PHP, but I would assume that such a facility exists (as it exists in other languages with web frameworks):

.ie. Do a "user" type of search with param[i]=value[i] for i=1..4 on store #1 (with value1,value2,value3,... as a shorthand for URI query parameters):

1) GET /store1/search/user/value1,value2,value3,value4

or

2) GET /store1/search/user,value1,value2,value3,value4

or as follows (though I would not recommend it, more on that later)

3) GET /search/store1,user,value1,value2,value3,value4

With option 1, you map all URIs prefixed with /store1/search/user to the search handler (or whichever the PHP designation) defaulting to do searches for resources under store1 (equivalent to /search?location=store1&type=user.

By convention documented and enforced by the API, parameters values 1 through 4 are separated by commas and presented in that order.

Option 2 adds the search type (in this case user) as positional parameter #1. Either option is just a cosmetic choice.

Option 3 is also possible, but I don't think I would like it. I think the ability of search within certain resources should be presented in the URI itself preceding the search itself (as if indicating clearly in the URI that the search is specific within the resource.)

The advantage of this over passing parameters on the URI is that the search is part of the URI (thus treating a search as a resource, a resource whose contents can - and will - change over time.) The disadvantage is that parameter order is mandatory.

Once you do something like this, you can use GET, and it would be a read-only resource (since you can't POST or PUT to it - it gets updated when it's GET'ed). It would also be a resource that only comes to exist when it is invoked.

One could also add more semantics to it by caching the results for a period of time or with a DELETE causing the cache to be deleted. This, however, might run counter to what people typically use DELETE for (and because people typically control caching with caching headers.)

How you go about it would be a design decision, but this would be the way I'd go about. It is not perfect, and I'm sure there will be cases where doing this is not the best thing to do (specially for very complex search criteria).

How to call function on child component on parent events

you can use key to reload child component using key

<component :is="child1" :filter="filter" :key="componentKey"></component>

If you want to reload component with new filter, if button click filter the child component

reloadData() {            
   this.filter = ['filter1','filter2']
   this.componentKey += 1;  
},

and use the filter to trigger the function

NuGet behind a proxy

To anyone using VS2015: I was encountering a "407 Proxy Authentication required" error, which broke my build. After a few hours investigating, it turns out MSBuild wasn't sending credentials when trying to download Nuget as part of the 'DownloadNuGet' target. The solution was to add the following XML to C:\Program Files (x86)\MSBuild\14.0\Bin\MSBuild.exe.config inside the <configuration> element:

<system.net>
            <defaultProxy useDefaultCredentials="true">
            </defaultProxy>
</system.net>

Cross origin requests are only supported for HTTP but it's not cross-domain

For all python users:

Simply go to your destination folder in the terminal.

cd projectFoder

then start HTTP server For Python3+:

python -m http.server 8000

Serving HTTP on :: port 8000 (http://[::]:8000/) ...

go to your link: http://0.0.0.0:8000/

Enjoy :)

Auto increment in MongoDB to store sequence of Unique User ID

The best way I found to make this to my purpose was to increment from the max value you have in the field and for that, I used the following syntax:

var array = db.CollectionName.find({}).sort({ _id: -1 }).limit(1).toArray(); var max = max.length?max[0]+1:1;

Even if an User ID is deleted, this wont create duplicate

How to use mongoose findOne

Found the problem, need to use function(err,obj) instead:

Auth.findOne({nick: 'noname'}, function(err,obj) { console.log(obj); });

Why does C# XmlDocument.LoadXml(string) fail when an XML header is included?

I had the same problem when switching from absolute to relative path for my xml file. The following solves both loading and using relative source path issues. Using a XmlDataProvider, which is defined in xaml (should be possible in code too) :

    <Window.Resources>
    <XmlDataProvider 
        x:Name="myDP"
        x:Key="MyData"
        Source=""
        XPath="/RootElement/Element"
        IsAsynchronous="False"
        IsInitialLoadEnabled="True"                         
        debug:PresentationTraceSources.TraceLevel="High"  /> </Window.Resources>

The data provider automatically loads the document once the source is set. Here's the code :

        m_DataProvider = this.FindResource("MyData") as XmlDataProvider;
        FileInfo file = new FileInfo("MyXmlFile.xml");

        m_DataProvider.Document = new XmlDocument();
        m_DataProvider.Source = new Uri(file.FullName);

Method List in Visual Studio Code

For find method in all files you can press CTRL + P and then start search with #

example : #signin

enter image description here

Way to run Excel macros from command line or batch file?

You can check if Excel is already open. There is no need to create another isntance

   If CheckAppOpen("excel.application")  Then
           'MsgBox "App Loaded"
            Set xlApp = GetObject(, "excel.Application")   
   Else
            ' MsgBox "App Not Loaded"
            Set  wrdApp = CreateObject(,"excel.Application")   
   End If

Oracle Trigger ORA-04098: trigger is invalid and failed re-validation

in my case, this error is raised due to sequence was not created..

CREATE SEQUENCE  J.SOME_SEQ  MINVALUE 1 MAXVALUE 9999999999999999999999999999 INCREMENT BY 1 START WITH 1 CACHE 20 NOORDER  NOCYCLE ;

How to take the first N items from a generator or list?

The answer for how to do this can be found here

>>> generator = (i for i in xrange(10))
>>> list(next(generator) for _ in range(4))
[0, 1, 2, 3]
>>> list(next(generator) for _ in range(4))
[4, 5, 6, 7]
>>> list(next(generator) for _ in range(4))
[8, 9]

Notice that the last call asks for the next 4 when only 2 are remaining. The use of the list() instead of [] is what gets the comprehension to terminate on the StopIteration exception that is thrown by next().

Bloomberg BDH function with ISIN

To download ISIN code data the only place I see this is on the ISIN organizations website, www.isin.org. try http://isin.org, they should have a function where you can easily download.

What is the best open-source java charting library? (other than jfreechart)

There aren't a lot of them because they would be in competition with JFreeChart, and it's awesome. You can get documentation and examples by downloading the developer's guide. There are also tons of free online tutorials if you search for them.

checking for typeof error in JS

Or use this for different types of errors

function isError(val) {
  return (!!val && typeof val === 'object')
    && ((Object.prototype.toString.call(val) === '[object Error]')
      || (typeof val.message === 'string' && typeof val.name === 'string'))
}

Measure string size in Bytes in php

Further to PhoneixS answer to get the correct length of string in bytes - Since mb_strlen() is slower than strlen(), for the best performance one can check "mbstring.func_overload" ini setting so that mb_strlen() is used only when it is really required:

$content_length = ini_get('mbstring.func_overload') ? mb_strlen($content , '8bit') : strlen($content);

Showing which files have changed between two revisions

There is also a GUI based method.

You can use gitk.

  1. Run:

    $ gitk --all
    
  2. Right click on a commit of a branch and select Mark this commit in the pop-up menu.

  3. Right click on a commit of another branch and select Diff this -> marked commit or Diff marked commit -> this.

Then there will be a changed files list in the right bottom panel and diff details in the left bottom panel.

Working around MySQL error "Deadlock found when trying to get lock; try restarting transaction"

The answer is correct, however the perl documentation on how to handle deadlocks is a bit sparse and perhaps confusing with PrintError, RaiseError and HandleError options. It seems that rather than going with HandleError, use on Print and Raise and then use something like Try:Tiny to wrap your code and check for errors. The below code gives an example where the db code is inside a while loop that will re-execute an errored sql statement every 3 seconds. The catch block gets $_ which is the specific err message. I pass this to a handler function "dbi_err_handler" which checks $_ against a host of errors and returns 1 if the code should continue (thereby breaking the loop) or 0 if its a deadlock and should be retried...

$sth = $dbh->prepare($strsql);
my $db_res=0;
while($db_res==0)
{
   $db_res=1;
   try{$sth->execute($param1,$param2);}
   catch
   {
       print "caught $_ in insertion to hd_item_upc for upc $upc\n";
       $db_res=dbi_err_handler($_); 
       if($db_res==0){sleep 3;}
   }
}

dbi_err_handler should have at least the following:

sub dbi_err_handler
{
    my($message) = @_;
    if($message=~ m/DBD::mysql::st execute failed: Deadlock found when trying to get lock; try restarting transaction/)
    {
       $caught=1;
       $retval=0; # we'll check this value and sleep/re-execute if necessary
    }
    return $retval;
}

You should include other errors you wish to handle and set $retval depending on whether you'd like to re-execute or continue..

Hope this helps someone -

How to convert List<Integer> to int[] in Java?

With Eclipse Collections, you can do the following if you have a list of type java.util.List<Integer>:

List<Integer> integers = Lists.mutable.with(1, 2, 3, 4, 5);
int[] ints = LazyIterate.adapt(integers).collectInt(i -> i).toArray();

Assert.assertArrayEquals(new int[]{1, 2, 3, 4, 5}, ints);

If you already have an Eclipse Collections type like MutableList, you can do the following:

MutableList<Integer> integers = Lists.mutable.with(1, 2, 3, 4, 5);
int[] ints = integers.asLazy().collectInt(i -> i).toArray();

Assert.assertArrayEquals(new int[]{1, 2, 3, 4, 5}, ints);

Note: I am a committer for Eclipse Collections

Eclipse copy/paste entire line keyboard shortcut

If you want to copy a line to the clipboard you can also use the trick:

Ctrl-Alt-Down followed by Ctrl-X

The drawback is that the file where you copy the line from becomes dirty.

Changing the width of Bootstrap popover

you can also add the data-container="body" which should do the job :

<div class="row">
    <div class="col-md-6">
        <label for="name">Name:</label>
        <input id="name" class="form-control" type="text" 
                         data-toggle="popover" data-trigger="hover"

                         data-container="body"

                         data-content="My popover content.My popover content.My popover content.My popover content." />
    </div>
</div>

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

git filter-branch is a powerful command which you can use it to delete a huge file from the commits history. The file will stay for a while and Git will remove it in the next garbage collection. Below is the full process from deleteing files from commit history. For safety, below process runs the commands on a new branch first. If the result is what you needed, then reset it back to the branch you actually want to change.

# Do it in a new testing branch
$ git checkout -b test

# Remove file-name from every commit on the new branch
# --index-filter, rewrite index without checking out
# --cached, remove it from index but not include working tree
# --ignore-unmatch, ignore if files to be removed are absent in a commit
# HEAD, execute the specified command for each commit reached from HEAD by parent link
$ git filter-branch --index-filter 'git rm --cached --ignore-unmatch file-name' HEAD

# The output is OK, reset it to the prior branch master
$ git checkout master
$ git reset --soft test

# Remove test branch
$ git branch -d test

# Push it with force
$ git push --force origin master

JavaScript Nested function

function x() {}

is equivalent (or very similar) to

var x = function() {}

unless I'm mistaken.

So there is nothing funny going on.

How to get size in bytes of a CLOB column in Oracle?

NVL(length(clob_col_name),0) works for me.

phpMyAdmin Error: The mbstring extension is missing. Please check your PHP configuration

this ones solved my problem

1.open command prompt in administration

  1. then open apache bin folder like this,

    c:\ cd wamp\bin\apache\apache2.4.17\bin>

  2. then type after the above

    c:\ cd wamp\bin\apache\apache2.4.17\bin> mklink php.ini d:\wamp\bin\php\php5.6.15\phpForApache.ini

  3. thats it close the command prompt and restart the wamp and open it in admin mode.

  4. original post : PHP: No php.ini file thanks to xiao.

Calling the base class constructor from the derived class constructor

First off, a PetStore is not a farm.

Let's get past this though. You actually don't need access to the private members, you have everything you need in the public interface:

Animal_* getAnimal_(int i);
void addAnimal_(Animal_* newAnimal);

These are the methods you're given access to and these are the ones you should use.

I mean I did this Inheritance so I can add animals to my PetStore but now since sizeF is private how can I do that ??

Simple, you call addAnimal. It's public and it also increments sizeF.

Also, note that

PetStore()
{
 idF=0;
};

is equivalent to

PetStore() : Farm()
{
 idF=0;
};

i.e. the base constructor is called, base members are initialized.

Copy entire directory contents to another directory?

With regard to Java, there is no such method in the standard API. In Java 7, the java.nio.file.Files class will provide a copy convenience method.

References

  1. The Java Tutorials

  2. Copying files from one directory to another in Java

How to convert int to string on Arduino?

Here below is a self composed myitoa() which is by far smaller in code, and reserves a FIXED array of 7 (including terminating 0) in char *mystring, which is often desirable. It is obvious that one can build the code with character-shift instead, if one need a variable-length output-string.

void myitoa(int number, char *mystring) {
  boolean negative = number>0;

  mystring[0] = number<0? '-' : '+';
  number = number<0 ? -number : number;
  for (int n=5; n>0; n--) {
     mystring[n] = ' ';
     if(number > 0) mystring[n] = number%10 + 48;
     number /= 10;
  }  
  mystring[6]=0;
}

angularjs getting previous route path

You'll need to couple the event listener to $rootScope in Angular 1.x, but you should probably future proof your code a bit by not storing the value of the previous location on $rootScope. A better place to store the value would be a service:

var app = angular.module('myApp', [])
.service('locationHistoryService', function(){
    return {
        previousLocation: null,

        store: function(location){
            this.previousLocation = location;
        },

        get: function(){
            return this.previousLocation;
        }
})
.run(['$rootScope', 'locationHistoryService', function($location, locationHistoryService){
    $rootScope.$on('$locationChangeSuccess', function(e, newLocation, oldLocation){
        locationHistoryService.store(oldLocation);
    });
}]);

Python None comparison: should I use "is" or ==?

PEP 8 defines that it is better to use the is operator when comparing singletons.

Excel Date Conversion from yyyymmdd to mm/dd/yyyy

Found another (manual) answer which worked well for me

  1. Select the column.
  2. Choose Data tab
  3. Text to Columns - opens new box
  4. (choose Delimited), Next
  5. (uncheck all boxes, use "none" for text qualifier), Next
  6. use the ymd option from the Date dropdown.
  7. Click Finish

How to get the current time in milliseconds in C Programming

quick answer

#include<stdio.h>   
#include<time.h>   

int main()   
{   
    clock_t t1, t2;  
    t1 = clock();   
    int i;
    for(i = 0; i < 1000000; i++)   
    {   
        int x = 90;  
    }   

    t2 = clock();   

    float diff = ((float)(t2 - t1) / 1000000.0F ) * 1000;   
    printf("%f",diff);   

    return 0;   
}

How to find all duplicate from a List<string>?

Using LINQ, ofcourse. The below code would give you dictionary of item as string, and the count of each item in your sourc list.

var item2ItemCount = list.GroupBy(item => item).ToDictionary(x=>x.Key,x=>x.Count());

multiple conditions for JavaScript .includes() method

That should work even if one, and only one of the conditions is true :

var str = "bonjour le monde vive le javascript";
var arr = ['bonjour','europe', 'c++'];

function contains(target, pattern){
    var value = 0;
    pattern.forEach(function(word){
      value = value + target.includes(word);
    });
    return (value === 1)
}

console.log(contains(str, arr));

How to pass values arguments to modal.show() function in Bootstrap

You could do it like this:

<a class="btn btn-primary announce" data-toggle="modal" data-id="107" >Announce</a>

Then use jQuery to bind the click and send the Announce data-id as the value in the modals #cafeId:

$(document).ready(function(){
   $(".announce").click(function(){ // Click to only happen on announce links
     $("#cafeId").val($(this).data('id'));
     $('#createFormId').modal('show');
   });
});

Prevent form submission on Enter key press

Use event.preventDefault() inside user defined function

<form onsubmit="userFunction(event)"> ...

_x000D_
_x000D_
function userFunction(ev) 
{
    if(!event.target.send.checked) 
    {
        console.log('form NOT submit on "Enter" key')

        ev.preventDefault();
    }
}
_x000D_
Open chrome console> network tab to see
<form onsubmit="userFunction(event)" action="/test.txt">
  <input placeholder="type and press Enter" /><br>
  <input type="checkbox" name="send" /> submit on enter
</form>
_x000D_
_x000D_
_x000D_

Define a struct inside a class in C++

Something like:

class Tree {

 struct node {
   int data;
   node *llink;
   node *rlink;
 };
 .....
 .....
 .....
};

What is username and password when starting Spring Boot with Tomcat?

If you can't find the password based on other answers that point to a default one, the log message wording in recent versions changed to

Using generated security password: <some UUID>

Remove warning messages in PHP

There is already answer with Error Control Operator but it lacks of explanation. You can use @ operator with every expression and it hides errors (except of Fatal Errors).

@$test['test']; //PHP Notice:  Undefined variable: test

@(14/0); // PHP Warning:  Division by zero

//This is not working. You can't hide Fatal Errors this way.
@customFuntion(); // PHP Fatal error:  Uncaught Error: Call to undefined function customFuntion()

For debugging it's fast and perfect method. But you should never ever use it on production nor permanent include in your local version. It will give you a lot of unnecessary irritation.

You should consider instead:

1. Error reporting settings as mentioned in accepted answer.

error_reporting(E_ERROR | E_PARSE);

or from PHP INI settings

ini_set('display_errors','Off');

2. Catching exceptions

try {
    $var->method();
} catch (Error $e) {
    // Handle error
    echo $e->getMessage();
}

Why does an image captured using camera intent gets rotated on some devices on Android?

Better try to take the picture in a specific orientation.

android:screenOrientation="landscape"
android:configChanges="orientation|keyboardHidden"

For best results give landscape orientation in the cameraview activity.

Can I run multiple programs in a Docker container?

You can run 2 processes in foreground by using wait. Just make a bash script with the following content. Eg start.sh:

# runs 2 commands simultaneously:

mongod & # your first application
P1=$!
python script.py & # your second application
P2=$!
wait $P1 $P2

In your Dockerfile, start it with

CMD bash start.sh

MySql : Grant read only options?

Various permissions that you can grant to a user are

ALL PRIVILEGES- This would allow a MySQL user all access to a designated database (or if no database is selected, across the system)
CREATE- allows them to create new tables or databases
DROP- allows them to them to delete tables or databases
DELETE- allows them to delete rows from tables
INSERT- allows them to insert rows into tables
SELECT- allows them to use the Select command to read through databases
UPDATE- allow them to update table rows
GRANT OPTION- allows them to grant or remove other users' privileges

To provide a specific user with a permission, you can use this framework:

GRANT [type of permission] ON [database name].[table name] TO ‘[username]’@'localhost’;

I found this article very helpful

Docker Error bind: address already in use

In your case it was some other process that was using the port and as indicated in the comments, sudo netstat -pna | grep 3000 helped you in solving the problem.

While in other cases (I myself encountered it many times) it mostly is the same container running at some other instance. In that case docker ps was very helpful as often I left the same containers running in other directories and then tried running again at other places, where same container names were used.

How docker ps helped me: docker rm -f $(docker ps -aq) is a short command which I use to remove all containers.

Edit: Added how docker ps helped me.

Open a Web Page in a Windows Batch FIle

When you use the start command to a website it will use the default browser by default but if you want to use a specific browser then use start iexplorer.exe www.website.com

Also you cannot have http:// in the url.

JavaScript string and number conversion

Below is a very irritating example of how JavaScript can get you into trouble:

If you just try to use parseInt() to convert to number and then add another number to the result it will concatenate two strings.

However, you can solve the problem by placing the sum expression in parentheses as shown in the example below.

Result: Their age sum is: 98; Their age sum is NOT: 5048

_x000D_
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<body>_x000D_
_x000D_
<p id="demo"></p>_x000D_
_x000D_
<script>_x000D_
function Person(first, last, age, eye) {_x000D_
    this.firstName = first;_x000D_
    this.lastName = last;_x000D_
    this.age = age;_x000D_
    this.eyeColor = eye;_x000D_
}_x000D_
_x000D_
var myFather = new Person("John", "Doe", "50", "blue");_x000D_
var myMother = new Person("Sally", "Rally", 48, "green");_x000D_
_x000D_
document.getElementById("demo").innerHTML = "Their age sum is: "+_x000D_
 (parseInt(myFather.age)+myMother.age)+"; Their age sum is NOT: " +_x000D_
 parseInt(myFather.age)+myMother.age; _x000D_
</script>_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

android TextView: setting the background color dynamically doesn't work

two ways to do that:

1.create color in colors.xml file like:

<resources>
        <color name="white">#ffffff</color>
</resources>

and use it int activity java class as:

et.setBackgroundResource(R.color.white);

2.

et.setBackgroundColor(getResources().getColor(R.color.white));
                or
et.setBackgroundColor(Color.parseColor("#ffffff"));

Is there any free OCR library for Android?

Google Goggles is the perfect application for doing both OCR and translation.
And the good news is that Google Goggles to Become App Platform.

Until then, you can use IQ Engines.

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

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

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

Stopping Docker containers by image name - Ubuntu

docker stop $(docker ps -a | grep "zalenium")
docker rm $(docker ps -a | grep "zalenium")

This should be enough.

how to check if object already exists in a list

If it's maintainable to use those 2 properties, you could:

bool alreadyExists = myList.Any(x=> x.Foo=="ooo" && x.Bar == "bat");

VB.NET Connection string (Web.Config, App.Config)

Connection in APPConfig

<connectionStrings>
  <add name="ConnectionString" connectionString="Data Source=192.168.1.25;Initial Catalog=Login;Persist Security Info=True;User ID=sa;Password=example.com"   providerName="System.Data.SqlClient" />
</connectionStrings>

In Class.Cs

public string ConnectionString
{
    get
    {
        return System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ToString();
    }
}

An efficient compression algorithm for short text strings

Check out Smaz:

Smaz is a simple compression library suitable for compressing very short strings.

How do you show animated GIFs on a Windows Form (c#)

Note that in Windows, you traditionally don't use animated Gifs, but little AVI animations: there is a Windows native control just to display them. There are even tools to convert animated Gifs to AVI (and vice-versa).

Run a script in Dockerfile

It's best practice to use COPY instead of ADD when you're copying from the local file system to the image. Also, I'd recommend creating a sub-folder to place your content into. If nothing else, it keeps things tidy. Make sure you mark the script as executable using chmod.

Here, I am creating a scripts sub-folder to place my script into and run it from:

RUN mkdir -p /scripts
COPY script.sh /scripts
WORKDIR /scripts
RUN chmod +x script.sh
RUN script.sh

What does 'COLLATE SQL_Latin1_General_CP1_CI_AS' do?

It sets how the database server sorts (compares pieces of text). in this case:

SQL_Latin1_General_CP1_CI_AS

breaks up into interesting parts:

  1. latin1 makes the server treat strings using charset latin 1, basically ascii
  2. CP1 stands for Code Page 1252
  3. CI case insensitive comparisons so 'ABC' would equal 'abc'
  4. AS accent sensitive, so 'ü' does not equal 'u'

P.S. For more detailed information be sure to read @solomon-rutzky's answer.

Correct way to synchronize ArrayList in java

Let's take a normal list (implemented by the ArrayList class) and make it synchronized. This is shown in the SynchronizedListExample class. We pass the Collections.synchronizedList method a new ArrayList of Strings. The method returns a synchronized List of Strings. //Here is SynchronizedArrayList class

package com.mnas.technology.automation.utility;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import org.apache.log4j.Logger;
/**
* 
* @author manoj.kumar
* @email [email protected]
* 
*/
public class SynchronizedArrayList {
    static Logger log = Logger.getLogger(SynchronizedArrayList.class.getName());
    public static void main(String[] args) {    
        List<String> synchronizedList = Collections.synchronizedList(new ArrayList<String>());
        synchronizedList.add("Aditya");
        synchronizedList.add("Siddharth");
        synchronizedList.add("Manoj");
        // when iterating over a synchronized list, we need to synchronize access to the synchronized list
        synchronized (synchronizedList) {
            Iterator<String> iterator = synchronizedList.iterator();
            while (iterator.hasNext()) {
                log.info("Synchronized Array List Items: " + iterator.next());
            }
        }    
    }
}

Notice that when iterating over the list, this access is still done using a synchronized block that locks on the synchronizedList object. In general, iterating over a synchronized collection should be done in a synchronized block

How do you convert a jQuery object into a string?

The accepted answer doesn't cover text nodes (undefined is printed out).

This code snippet solves it:

_x000D_
_x000D_
var htmlElements = $('<p><a href="http://google.com">google</a></p>??<p><a href="http://bing.com">bing</a></p>'),_x000D_
    htmlString = '';_x000D_
    _x000D_
htmlElements.each(function () {_x000D_
    var element = $(this).get(0);_x000D_
_x000D_
    if (element.nodeType === Node.ELEMENT_NODE) {_x000D_
        htmlString += element.outerHTML;_x000D_
    }_x000D_
    else if (element.nodeType === Node.TEXT_NODE) {_x000D_
        htmlString += element.nodeValue;_x000D_
    }_x000D_
});_x000D_
_x000D_
alert('String html: ' + htmlString);
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
_x000D_
_x000D_
_x000D_

How do I update a Linq to SQL dbml file?

Here is the complete step-by-step method that worked for me in order to update the LINQ to SQL dbml and associated files to include a new column that I added to one of the database tables.

You need to make the changes to your design surface as suggested by other above; however, you need to do some extra steps. These are the complete steps:

  1. Drag your updated table from Server Explorer onto the design surface

  2. Copy the new column from this "new" table to the "old" table (see M463 answer for details on this step)

  3. Delete the "new" table that you just dragged over

  4. Click and highlight the stored procedure, then delete it

  5. Drag the new stored procedure and drop into place.

  6. Delete the .designer.vb file in the code-behind of the .dbml (if you do not delete this, your code-behind containing the schema will not update even if you rebuild and the new table field will not be included)

  7. Clean and Rebuild the solution (this will rebuild the .designer.vb file to include all the new changes!).

Hash Map in Python

Python dictionary is a built-in type that supports key-value pairs.

streetno = {"1": "Sachin Tendulkar", "2": "Dravid", "3": "Sehwag", "4": "Laxman", "5": "Kohli"}

as well as using the dict keyword:

streetno = dict({"1": "Sachin Tendulkar", "2": "Dravid"}) 

or:

streetno = {}
streetno["1"] = "Sachin Tendulkar" 

How to detect the OS from a Bash script?

I think the following should work. I'm not sure about win32 though.

if [[ "$OSTYPE" == "linux-gnu"* ]]; then
        # ...
elif [[ "$OSTYPE" == "darwin"* ]]; then
        # Mac OSX
elif [[ "$OSTYPE" == "cygwin" ]]; then
        # POSIX compatibility layer and Linux environment emulation for Windows
elif [[ "$OSTYPE" == "msys" ]]; then
        # Lightweight shell and GNU utilities compiled for Windows (part of MinGW)
elif [[ "$OSTYPE" == "win32" ]]; then
        # I'm not sure this can happen.
elif [[ "$OSTYPE" == "freebsd"* ]]; then
        # ...
else
        # Unknown.
fi

How to deploy a Java Web Application (.war) on tomcat?

Note that you can deploy remotely using HTTP.

http://localhost:8080/manager/deploy

Upload the web application archive (WAR) file that is specified as the request data in this HTTP PUT request, install it into the appBase directory of our corresponding virtual host, and start it using the war file name without the .war extension as the path. The application can later be undeployed (and the corresponding application directory removed) by use of the /undeploy. To deploy the ROOT web application (the application with a context path of "/"), name the war ROOT.war.

and if you're using Ant you can do this using Tomcat Ant tasks (perhaps following a successful build).

To determine which path you then hit on your browser, you need to know the port Tomcat is running on, the context and your servlet path. See here for more details.

Pretty printing XML in Python

You can try this variation...

Install BeautifulSoup and the backend lxml (parser) libraries:

user$ pip3 install lxml bs4

Process your XML document:

from bs4 import BeautifulSoup

with open('/path/to/file.xml', 'r') as doc: 
    for line in doc: 
        print(BeautifulSoup(line, 'lxml-xml').prettify())  

Convert R vector to string vector of 1 element

Use the collapse argument to paste:

paste(a,collapse=" ")
[1] "aa bb cc"

uint8_t vs unsigned char

Just to be pedantic, some systems may not have an 8 bit type. According to Wikipedia:

An implementation is required to define exact-width integer types for N = 8, 16, 32, or 64 if and only if it has any type that meets the requirements. It is not required to define them for any other N, even if it supports the appropriate types.

So uint8_t isn't guaranteed to exist, though it will for all platforms where 8 bits = 1 byte. Some embedded platforms may be different, but that's getting very rare. Some systems may define char types to be 16 bits, in which case there probably won't be an 8-bit type of any kind.

Other than that (minor) issue, @Mark Ransom's answer is the best in my opinion. Use the one that most clearly shows what you're using the data for.

Also, I'm assuming you meant uint8_t (the standard typedef from C99 provided in the stdint.h header) rather than uint_8 (not part of any standard).

Mockito How to mock only the call of a method of the superclass

Maybe the easiest option if inheritance makes sense is to create a new method (package private??) to call the super (lets call it superFindall), spy the real instance and then mock the superFindAll() method in the way you wanted to mock the parent class one. It's not the perfect solution in terms of coverage and visibility but it should do the job and it's easy to apply.

 public Childservice extends BaseService {
    public void save(){
        //some code
        superSave();
    }

    void superSave(){
        super.save();
    }
}

Facebook API "This app is in development mode"

in your app dashboard check status to on facebook change develope mode to live

Centering a button vertically in table cell, using Twitter Bootstrap

add this to your css

.table-vcenter td {
   vertical-align: middle!important;
}

then add to the class to your table:

        <table class="table table-hover table-striped table-vcenter">

What does "async: false" do in jQuery.ajax()?

Async:False will hold the execution of rest code. Once you get response of ajax, only then, rest of the code will execute.

Reset Excel to default borders

If you have applied border and/or fill on a cell, you need to clear both to go back to the default borders.

You may apply 'None' as the border option and expect the default borders to show, but it will not when the cell fill is white. It's not immediately obvious that it has a white fill, as unfilled cells are also white.

In this case, apply a 'No Fill' on the cells, and you will get the default borders back.

Screenshot of Excel indicating locations of No Border and No Fill options

That's it. No messy format painting, no 'Clear Formats', none of those destructive methods. Easy, quick and painless.

Read Post Data submitted to ASP.Net Form

Read the Request.Form NameValueCollection and process your logic accordingly:

NameValueCollection nvc = Request.Form;
string userName, password;
if (!string.IsNullOrEmpty(nvc["txtUserName"]))
{
  userName = nvc["txtUserName"];
}

if (!string.IsNullOrEmpty(nvc["txtPassword"]))
{
  password = nvc["txtPassword"];
}

//Process login
CheckLogin(userName, password);

... where "txtUserName" and "txtPassword" are the Names of the controls on the posting page.

How to iterate through a DataTable

foreach (DataRow row in myDataTable.Rows)
{
   Console.WriteLine(row["ImagePath"]);
}

I am writing this from memory.
Hope this gives you enough hint to understand the object model.

DataTable -> DataRowCollection -> DataRow (which one can use & look for column contents for that row, either using columnName or ordinal).

-> = contains.

Single-threaded apartment - cannot instantiate ActiveX control

The problem you're running into is that most background thread / worker APIs will create the thread in a Multithreaded Apartment state. The error message indicates that the control requires the thread be a Single Threaded Apartment.

You can work around this by creating a thread yourself and specifying the STA apartment state on the thread.

var t = new Thread(MyThreadStartMethod);
t.SetApartmentState(ApartmentState.STA);
t.Start();

How to make an HTTP get request with parameters

In a GET request, you pass parameters as part of the query string.

string url = "http://somesite.com?var=12345";

What is an OS kernel ? How does it differ from an operating system?

Kernel resides in OS.Actually it is a memory space specially provided for handling the os functions.Some even say OS handles Resources of system and Kernel is one which is heart of os and maintain,manage i.e.keep track of os.