Programs & Examples On #Identity column

An Identity column is a column in a database table that is made up of values managed by the server and cannot be modified, to be used as a primary key for the table. It is usually an auto-incrementing number.

Adding an identity to an existing column

I don't believe you can alter an existing column to be an identity column using tsql. However, you can do it through the Enterprise Manager design view.

Alternatively you could create a new row as the identity column, drop the old column, then rename your new column.

ALTER TABLE FooTable
ADD BarColumn INT IDENTITY(1, 1)
               NOT NULL
               PRIMARY KEY CLUSTERED

BULK INSERT with identity (auto-increment) column

  1. Create a table with Identity column + other columns;
  2. Create a view over it and expose only the columns you will bulk insert;
  3. BCP in the view

How do you determine what SQL Tables have an identity column programmatically

sys.columns.is_identity = 1

e.g.,

select o.name, c.name
from sys.objects o inner join sys.columns c on o.object_id = c.object_id
where c.is_identity = 1

Inserting into Oracle and retrieving the generated sequence ID

There are no auto incrementing features in Oracle for a column. You need to create a SEQUENCE object. You can use the sequence like:

insert into table(batch_id, ...) values(my_sequence.nextval, ...)

...to return the next number. To find out the last created sequence nr (in your session), you would use:

my_sequence.currval

This site has several complete examples on how to use sequences.

how to set active class to nav menu from twitter bootstrap

it is a workaround. try

<div class="nav-collapse">
  <ul class="nav">
    <li id="home" class="active"><a href="~/Home/Index">Home</a></li>
    <li><a href="#">Project</a></li>
    <li><a href="#">Customer</a></li>
    <li><a href="#">Staff</a></li>
    <li  id="demo"><a href="~/Home/demo">Broker</a></li>
    <li id='sale'><a href="#">Sale</a></li>
  </ul>
</div>

and on each page js add

$(document).ready(function () {
  $(".nav li").removeClass("active");//this will remove the active class from  
                                     //previously active menu item 
  $('#home').addClass('active');
  //for demo
  //$('#demo').addClass('active');
  //for sale 
  //$('#sale').addClass('active');
});

Bootstrap 3: Keep selected tab on page refresh

Well, this is already in 2018 but I think it is better late than never (like a title in a TV program), lol. Down here is the jQuery code that I create during my thesis.

<script type="text/javascript">
$(document).ready(function(){
    $('a[data-toggle="tab"]').on('show.affectedDiv.tab', function(e) {
        localStorage.setItem('activeTab', $(e.target).attr('href'));
    });
    var activeTab = localStorage.getItem('activeTab');
    if(activeTab){
        $('#myTab a[href="' + activeTab + '"]').tab('show');
    }
});
</script>

and here is the code for bootstrap tabs:

<div class="affectedDiv">
    <ul class="nav nav-tabs" id="myTab">
        <li class="active"><a data-toggle="tab" href="#sectionA">Section A</a></li>
        <li><a data-toggle="tab" href="#sectionB">Section B</a></li>
        <li><a data-toggle="tab" href="#sectionC">Section C</a></li>
    </ul>
    <div class="tab-content">
        <div id="sectionA" class="tab-pane fade in active">
            <h3>Section A</h3>
            <p>Aliquip placeat salvia cillum iphone. Seitan aliquip quis cardigan american apparel, butcher voluptate nisi qui. Raw denim you probably haven't heard of them jean shorts Austin. Nesciunt tofu stumptown aliqua, retro synth master cleanse. Mustache cliche tempor, williamsburg carles vegan helvetica. Reprehenderit butcher retro keffiyeh dreamcatcher synth.</p>
        </div>
        <div id="sectionB" class="tab-pane fade">
            <h3>Section B</h3>
            <p>Vestibulum nec erat eu nulla rhoncus fringilla ut non neque. Vivamus nibh urna, ornare id gravida ut, mollis a magna. Aliquam porttitor condimentum nisi, eu viverra ipsum porta ut. Nam hendrerit bibendum turpis, sed molestie mi fermentum id. Aenean volutpat velit sem. Sed consequat ante in rutrum convallis. Nunc facilisis leo at faucibus adipiscing.</p>
        </div>
        <div id="sectionC" class="tab-pane fade">
            <h3>Section C</h3>
            <p>Vestibulum nec erat eu nulla rhoncus fringilla ut non neque. Vivamus nibh urna, ornare id gravida ut, mollis a magna. Aliquam porttitor condimentum nisi, eu viverra ipsum porta ut. Nam hendrerit bibendum turpis, sed molestie mi fermentum id. Aenean volutpat velit sem. Sed consequat ante in rutrum convallis. Nunc facilisis leo at faucibus adipiscing.</p>
        </div>
    </div>
</div>


Dont forget to call the bootstrap and other fundamental things 

here are quick codes for you:

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>


Now let's come to the explanation:

The jQuery code in the above example simply gets the element's href attribute value when a new tab has been shown using the jQuery .attr() method and save it locally in the user's browser through HTML5 localStorage object. Later, when the user refresh the page it retrieves this data and activate the related tab via .tab('show') method.

Looking up for some examples? here is one for you guys.. https://jsfiddle.net/Wineson123/brseabdr/

I wish my answer could help you all.. Cheerio! :)

Android: How to enable/disable option menu item on button click?

How to update the current menu in order to enable or disable the items when an AsyncTask is done.

In my use case I needed to disable my menu while my AsyncTask was loading data, then after loading all the data, I needed to enable all the menu again in order to let the user use it.

This prevented the app to let users click on menu items while data was loading.

First, I declare a state variable , if the variable is 0 the menu is shown, if that variable is 1 the menu is hidden.

private mMenuState = 1; //I initialize it on 1 since I need all elements to be hidden when my activity starts loading.

Then in my onCreateOptionsMenu() I check for this variable , if it's 1 I disable all my items, if not, I just show them all

 @Override
    public boolean onCreateOptionsMenu(Menu menu) {

        getMenuInflater().inflate(R.menu.menu_galeria_pictos, menu);

        if(mMenuState==1){
            for (int i = 0; i < menu.size(); i++) {
                menu.getItem(i).setVisible(false);
            }
        }else{
             for (int i = 0; i < menu.size(); i++) {
                menu.getItem(i).setVisible(true);
            }
        }

        return super.onCreateOptionsMenu(menu);
    }

Now, when my Activity starts, onCreateOptionsMenu() will be called just once, and all my items will be gone because I set up the state for them at the start.

Then I create an AsyncTask Where I set that state variable to 0 in my onPostExecute()

This step is very important!

When you call invalidateOptionsMenu(); it will relaunch onCreateOptionsMenu();

So, after setting up my state to 0, I just redraw all the menu but this time with my variable on 0 , that said, all the menu will be shown after all the asynchronous process is done, and then my user can use the menu.

 public class LoadMyGroups extends AsyncTask<Void, Void, Void> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            mMenuState = 1; //you can set here the state of the menu too if you dont want to initialize it at global declaration. 

        }

        @Override
        protected Void doInBackground(Void... voids) {
           //Background work

            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            super.onPostExecute(aVoid);

            mMenuState=0; //We change the state and relaunch onCreateOptionsMenu
            invalidateOptionsMenu(); //Relaunch onCreateOptionsMenu

        }
    }

Results

enter image description here

Counter increment in Bash loop not working

It seems that you didn't update the counter is the script, use counter++

Dialog throwing "Unable to add window — token null is not for an application” with getApplication() as context

I think it may happen as well if you are trying to show a dialog from a thread which is not the main UI thread.

Use runOnUiThread() in that case.

What is the convention for word separator in Java package names?

Anyone can use underscore _ (its Okay)

No one should use hypen - (its Bad practice)

No one should use capital letters inside package names (Bad practice)

NOTE: Here "Bad Practice" is meant for technically you are allowed to use that, but conventionally its not in good manners to write.

Source: Naming a Package(docs.oracle)

Calculate a Running Total in SQL Server

If you are using Sql server 2008 R2 above. Then, It would be shortest way to do;

Select id
    ,somedate
    ,somevalue,
LAG(runningtotal) OVER (ORDER BY somedate) + somevalue AS runningtotal
From TestTable 

LAG is use to get previous row value. You can do google for more info.

[1]:

Cannot deserialize the current JSON array (e.g. [1,2,3])

I think the problem you're having is that your JSON is a list of objects when it comes in and it doesnt directly relate to your root class.

var content would look something like this (i assume):

[
  {
    "id": 3636,
    "is_default": true,
    "name": "Unit",
    "quantity": 1,
    "stock": "100000.00",
    "unit_cost": "0"
  },
  {
    "id": 4592,
    "is_default": false,
    "name": "Bundle",
    "quantity": 5,
    "stock": "100000.00",
    "unit_cost": "0"
  }
]

Note: make use of http://jsonviewer.stack.hu/ to format your JSON.

So if you try the following it should work:

  public static List<RootObject> GetItems(string user, string key, Int32 tid, Int32 pid)
    {
        // Customize URL according to geo location parameters
        var url = string.Format(uniqueItemUrl, user, key, tid, pid);

        // Syncronious Consumption
        var syncClient = new WebClient();

        var content = syncClient.DownloadString(url);

        return JsonConvert.DeserializeObject<List<RootObject>>(content);

    }

You will need to then iterate if you don't wish to return a list of RootObject.


I went ahead and tested this in a Console app, worked fine.

enter image description here

How do I pass a method as a parameter in Python

Yes it is, just use the name of the method, as you have written. Methods and functions are objects in Python, just like anything else, and you can pass them around the way you do variables. In fact, you can think about a method (or function) as a variable whose value is the actual callable code object.

Since you asked about methods, I'm using methods in the following examples, but note that everything below applies identically to functions (except without the self parameter).

To call a passed method or function, you just use the name it's bound to in the same way you would use the method's (or function's) regular name:

def method1(self):
    return 'hello world'

def method2(self, methodToRun):
    result = methodToRun()
    return result

obj.method2(obj.method1)

Note: I believe a __call__() method does exist, i.e. you could technically do methodToRun.__call__(), but you probably should never do so explicitly. __call__() is meant to be implemented, not to be invoked from your own code.

If you wanted method1 to be called with arguments, then things get a little bit more complicated. method2 has to be written with a bit of information about how to pass arguments to method1, and it needs to get values for those arguments from somewhere. For instance, if method1 is supposed to take one argument:

def method1(self, spam):
    return 'hello ' + str(spam)

then you could write method2 to call it with one argument that gets passed in:

def method2(self, methodToRun, spam_value):
    return methodToRun(spam_value)

or with an argument that it computes itself:

def method2(self, methodToRun):
    spam_value = compute_some_value()
    return methodToRun(spam_value)

You can expand this to other combinations of values passed in and values computed, like

def method1(self, spam, ham):
    return 'hello ' + str(spam) + ' and ' + str(ham)

def method2(self, methodToRun, ham_value):
    spam_value = compute_some_value()
    return methodToRun(spam_value, ham_value)

or even with keyword arguments

def method2(self, methodToRun, ham_value):
    spam_value = compute_some_value()
    return methodToRun(spam_value, ham=ham_value)

If you don't know, when writing method2, what arguments methodToRun is going to take, you can also use argument unpacking to call it in a generic way:

def method1(self, spam, ham):
    return 'hello ' + str(spam) + ' and ' + str(ham)

def method2(self, methodToRun, positional_arguments, keyword_arguments):
    return methodToRun(*positional_arguments, **keyword_arguments)

obj.method2(obj.method1, ['spam'], {'ham': 'ham'})

In this case positional_arguments needs to be a list or tuple or similar, and keyword_arguments is a dict or similar. In method2 you can modify positional_arguments and keyword_arguments (e.g. to add or remove certain arguments or change the values) before you call method1.

How do I create a constant in Python?

Here is an implementation of a "Constants" class, which creates instances with read-only (constant) attributes. E.g. can use Nums.PI to get a value that has been initialized as 3.14159, and Nums.PI = 22 raises an exception.

# ---------- Constants.py ----------
class Constants(object):
    """
    Create objects with read-only (constant) attributes.
    Example:
        Nums = Constants(ONE=1, PI=3.14159, DefaultWidth=100.0)
        print 10 + Nums.PI
        print '----- Following line is deliberate ValueError -----'
        Nums.PI = 22
    """

    def __init__(self, *args, **kwargs):
        self._d = dict(*args, **kwargs)

    def __iter__(self):
        return iter(self._d)

    def __len__(self):
        return len(self._d)

    # NOTE: This is only called if self lacks the attribute.
    # So it does not interfere with get of 'self._d', etc.
    def __getattr__(self, name):
        return self._d[name]

    # ASSUMES '_..' attribute is OK to set. Need this to initialize 'self._d', etc.
    #If use as keys, they won't be constant.
    def __setattr__(self, name, value):
        if (name[0] == '_'):
            super(Constants, self).__setattr__(name, value)
        else:
            raise ValueError("setattr while locked", self)

if (__name__ == "__main__"):
    # Usage example.
    Nums = Constants(ONE=1, PI=3.14159, DefaultWidth=100.0)
    print 10 + Nums.PI
    print '----- Following line is deliberate ValueError -----'
    Nums.PI = 22

Thanks to @MikeGraham 's FrozenDict, which I used as a starting point. Changed, so instead of Nums['ONE'] the usage syntax is Nums.ONE.

And thanks to @Raufio's answer, for idea to override __ setattr __.

Or for an implementation with more functionality, see @Hans_meine 's named_constants at GitHub

Should I use `import os.path` or `import os`?

os.path works in a funny way. It looks like os should be a package with a submodule path, but in reality os is a normal module that does magic with sys.modules to inject os.path. Here's what happens:

  • When Python starts up, it loads a bunch of modules into sys.modules. They aren't bound to any names in your script, but you can access the already-created modules when you import them in some way.

    • sys.modules is a dict in which modules are cached. When you import a module, if it already has been imported somewhere, it gets the instance stored in sys.modules.
  • os is among the modules that are loaded when Python starts up. It assigns its path attribute to an os-specific path module.

  • It injects sys.modules['os.path'] = path so that you're able to do "import os.path" as though it was a submodule.

I tend to think of os.path as a module I want to use rather than a thing in the os module, so even though it's not really a submodule of a package called os, I import it sort of like it is one and I always do import os.path. This is consistent with how os.path is documented.


Incidentally, this sort of structure leads to a lot of Python programmers' early confusion about modules and packages and code organization, I think. This is really for two reasons

  1. If you think of os as a package and know that you can do import os and have access to the submodule os.path, you may be surprised later when you can't do import twisted and automatically access twisted.spread without importing it.

  2. It is confusing that os.name is a normal thing, a string, and os.path is a module. I always structure my packages with empty __init__.py files so that at the same level I always have one type of thing: a module/package or other stuff. Several big Python projects take this approach, which tends to make more structured code.

How to upload files to server using Putty (ssh)

"C:\Program Files\PuTTY\pscp.exe" -scp file.py server.com:

file.py will be uploaded into your HOME dir on remote server.

or when the remote server has a different user, use "C:\Program Files\PuTTY\pscp.exe" -l username -scp file.py server.com:

After connecting to the server pscp will ask for a password.

Colspan all columns

According to the specification colspan="0" should result in a table width td.

However, this is only true if your table has a width! A table may contain rows of different widths. So, the only case that the renderer knows the width of the table if you define a colgroup! Otherwise, result of colspan="0" is indeterminable...

http://www.w3.org/TR/REC-html40/struct/tables.html#adef-colspan

I cannot test it on older browsers, but this is part of specification since 4.0...

A completely free agile software process tool

One possibility would be to use a Google Drawing, part of Google Drive, if you want a more visual and easy-to-edit option. You can create the cards by grouping a color-filled rectangle and one or more text fields together. Being a sufficiently free-form online vector drawing program, it doesn't really limit your possibilities like if you use a more dedicated solution.

The only real downsides are that you have to first create the building blocks from the beginning, and don't get numerical statistics like with a more structured tool.

SQL Query with Join, Count and Where

SELECT COUNT(*), table1.category_id, table2.category_name 
FROM table1 
INNER JOIN table2 ON table1.category_id=table2.category_id 
WHERE table1.colour <> 'red'
GROUP BY table1.category_id, table2.category_name 

d3 add text to circle

Here is an example showing some text in circles with data from a json file: http://bl.ocks.org/4474971. Which gives the following:

enter image description here

The main idea behind this is to encapsulate the text and the circle in the same "div" as you would do in html to have the logo and the name of the company in the same div in a page header.

The main code is:

var width = 960,
    height = 500;

var svg = d3.select("body").append("svg")
    .attr("width", width)
    .attr("height", height)

d3.json("data.json", function(json) {
    /* Define the data for the circles */
    var elem = svg.selectAll("g")
        .data(json.nodes)

    /*Create and place the "blocks" containing the circle and the text */  
    var elemEnter = elem.enter()
        .append("g")
        .attr("transform", function(d){return "translate("+d.x+",80)"})

    /*Create the circle for each block */
    var circle = elemEnter.append("circle")
        .attr("r", function(d){return d.r} )
        .attr("stroke","black")
        .attr("fill", "white")

    /* Create the text for each block */
    elemEnter.append("text")
        .attr("dx", function(d){return -20})
        .text(function(d){return d.label})
})

and the json file is:

{"nodes":[
  {"x":80, "r":40, "label":"Node 1"}, 
  {"x":200, "r":60, "label":"Node 2"}, 
  {"x":380, "r":80, "label":"Node 3"}
]}

The resulting html code shows the encapsulation you want:

<svg width="960" height="500">
    <g transform="translate(80,80)">
        <circle r="40" stroke="black" fill="white"></circle>
        <text dx="-20">Node 1</text>
    </g>
    <g transform="translate(200,80)">
        <circle r="60" stroke="black" fill="white"></circle>
        <text dx="-20">Node 2</text>
    </g>
    <g transform="translate(380,80)">
        <circle r="80" stroke="black" fill="white"></circle>
        <text dx="-20">Node 3</text>
    </g>
</svg>

How to convert a string with comma-delimited items to a list in Python?

m = '[[1,2,3],[4,5,6],[7,8,9]]'

m= eval(m.split()[0])

[[1, 2, 3], [4, 5, 6], [7, 8, 9]]

How do you write a migration to rename an ActiveRecord model and its table in Rails?

Here's an example:

class RenameOldTableToNewTable < ActiveRecord::Migration
  def self.up
    rename_table :old_table_name, :new_table_name
  end

  def self.down
    rename_table :new_table_name, :old_table_name
  end
end

I had to go and rename the model declaration file manually.

Edit:

In Rails 3.1 & 4, ActiveRecord::Migration::CommandRecorder knows how to reverse rename_table migrations, so you can do this:

class RenameOldTableToNewTable < ActiveRecord::Migration
  def change
    rename_table :old_table_name, :new_table_name
  end 
end

(You still have to go through and manually rename your files.)

IF EXIST C:\directory\ goto a else goto b problems windows XP batch files

To check for DIRECTORIES you should not use something like:

if exist c:\windows\

To work properly use:

if exist c:\windows\\.

note the "." at the end.

grep --ignore-case --only

This is a known bug on the initial 2.5.1, and has been fixed in early 2007 (Redhat 2.5.1-5) according to the bug reports. Unfortunately Apple is still using 2.5.1 even on Mac OS X 10.7.2.

You could get a newer version via Homebrew (3.0) or MacPorts (2.26) or fink (3.0-1).


Edit: Apparently it has been fixed on OS X 10.11 (or maybe earlier), even though the grep version reported is still 2.5.1.

How do I print the key-value pairs of a dictionary in python

If you want to sort the output by dict key you can use the collection package.

import collections
for k, v in collections.OrderedDict(sorted(d.items())).items():
    print(k, v)

It works on python 3

Trying to get PyCharm to work, keep getting "No Python interpreter selected"

You don't have Python Interpreter installed on your machine whereas Pycharm is looking for a Python interpreter, just go to https://www.python.org/downloads/ and download python and then create a new project, you'll be all set!

Change a Nullable column to NOT NULL with Default Value

If its SQL Server you can do it on the column properties within design view

Try this?:

ALTER TABLE dbo.TableName 
  ADD CONSTRAINT DF_TableName_ColumnName
    DEFAULT '01/01/2000' FOR ColumnName

How to install OpenJDK 11 on Windows?

You can use Amazon Corretto. It is free to use multiplatform, production-ready distribution of the OpenJDK. It comes with long-term support that will include performance enhancements and security fixes. Check the installation instructions here.

You can also check Zulu from Azul.

One more thing I like to highlight here is both Amazon Corretto and Zulu are TCK Compliant. You can see the OpenJDK builds comparison here and here.

CodeIgniter activerecord, retrieve last insert id?

In codeigniter 3, you can do it as follow:

if($this->db->insert("table_name",$table_data)) {
    $inserted_id = $this->db->insert_id();
    return $inserted_id;
}

You may get help for Codeigniter 3 from here https://codeigniter.com/user_guide/database/helpers.html

In Codeigniter 4, you can get last inserted id as follow:

$builder = $db->table("your table name");
if($builder->insert($table_data)) {
    $inserted_id = $db->insertID();
    return $inserted_id;
}

You may get help for Codeigniter 4 from here https://codeigniter4.github.io/userguide/database/helpers.html

How to checkout a specific Subversion revision from the command line?

If you already have it checked out locally then you can cd to where it is checked out, then use this syntax:

$ svn up -rXXXX

ref: Checkout a specific revision from subversion from command line

Tensorflow: Using Adam optimizer

The AdamOptimizer class creates additional variables, called "slots", to hold values for the "m" and "v" accumulators.

See the source here if you're curious, it's actually quite readable: https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/training/adam.py#L39 . Other optimizers, such as Momentum and Adagrad use slots too.

These variables must be initialized before you can train a model.

The normal way to initialize variables is to call tf.initialize_all_variables() which adds ops to initialize the variables present in the graph when it is called.

(Aside: unlike its name suggests, initialize_all_variables() does not initialize anything, it only add ops that will initialize the variables when run.)

What you must do is call initialize_all_variables() after you have added the optimizer:

...build your model...
# Add the optimizer
train_op = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)
# Add the ops to initialize variables.  These will include 
# the optimizer slots added by AdamOptimizer().
init_op = tf.initialize_all_variables()

# launch the graph in a session
sess = tf.Session()
# Actually intialize the variables
sess.run(init_op)
# now train your model
for ...:
  sess.run(train_op)

Center the nav in Twitter Bootstrap

http://www.bootply.com/3iSOTAyumP in this example the button for collapse was not clickable because the .navbar-brand was in front.

http://www.bootply.com/RfnEgu45qR there is an updated version where the collapse buttons is actually clickable.

Oracle query execution time

select LAST_LOAD_TIME, ELAPSED_TIME, MODULE, SQL_TEXT elapsed from v$sql
  order by LAST_LOAD_TIME desc

More complicated example (don't forget to delete or to substitute PATTERN):

select * from (
  select LAST_LOAD_TIME, to_char(ELAPSED_TIME/1000, '999,999,999.000') || ' ms' as TIME,
         MODULE, SQL_TEXT from SYS."V_\$SQL"
    where SQL_TEXT like '%PATTERN%'
    order by LAST_LOAD_TIME desc
  ) where ROWNUM <= 5;

Safely limiting Ansible playbooks to a single machine?

There's also a cute little trick that lets you specify a single host on the command line (or multiple hosts, I guess), without an intermediary inventory:

ansible-playbook -i "imac1-local," user.yml

Note the comma (,) at the end; this signals that it's a list, not a file.

Now, this won't protect you if you accidentally pass a real inventory file in, so it may not be a good solution to this specific problem. But it's a handy trick to know!

Rounding a variable to two decimal places C#

Make sure you provide a number, typically a double is used. Math.Round can take 1-3 arguments, the first argument is the variable you wish to round, the second is the number of decimal places and the third is the type of rounding.

double pay = 200 + bonus;
double pay = Math.Round(pay);
// Rounds to nearest even number, rounding 0.5 will round "down" to zero because zero is even
double pay = Math.Round(pay, 2, MidpointRounding.ToEven);
// Rounds up to nearest number
double pay = Math.Round(pay, 2, MidpointRounding.AwayFromZero);

Insert multiple rows with one query MySQL

In most cases inserting multiple records with one Insert statement is much faster in MySQL than inserting records with for/foreach loop in PHP.

Let's assume $column1 and $column2 are arrays with same size posted by html form.

You can create your query like this:

<?php
    $query = 'INSERT INTO TABLE (`column1`, `column2`) VALUES ';
    $query_parts = array();
    for($x=0; $x<count($column1); $x++){
        $query_parts[] = "('" . $column1[$x] . "', '" . $column2[$x] . "')";
    }
    echo $query .= implode(',', $query_parts);
?>

If data is posted for two records the query will become:

INSERT INTO TABLE (column1, column2) VALUES ('data', 'data'), ('data', 'data')

SQL: Select columns with NULL values only

This should give you a list of all columns in the table "Person" that has only NULL-values. You will get the results as multiple result-sets, which are either empty or contains the name of a single column. You need to replace "Person" in two places to use it with another table.

DECLARE crs CURSOR LOCAL FAST_FORWARD FOR SELECT name FROM syscolumns WHERE id=OBJECT_ID('Person')
OPEN crs
DECLARE @name sysname
FETCH NEXT FROM crs INTO @name
WHILE @@FETCH_STATUS = 0
BEGIN
    EXEC('SELECT ''' + @name + ''' WHERE NOT EXISTS (SELECT * FROM Person WHERE ' + @name + ' IS NOT NULL)')
    FETCH NEXT FROM crs INTO @name
END
CLOSE crs
DEALLOCATE crs

PHP call Class method / function

You need to create Object for the class.

$obj = new Functions();
$var = $obj->filter($_GET['params']);

How to Call VBA Function from Excel Cells?

The issue you have encountered is that UDFs cannot modify the Excel environment, they can only return a value to the calling cell.

There are several alternatives

  1. For the sample given you don't actually need VBA. This formula will work
    ='C:\Users\UserName\Desktop\[TestSample.xlsx]Sheet1'!$B$2

  2. Use a rather messy work around: See this answer

  3. You can use ExecuteExcel4Macro or OLEDB

Truncate with condition

You can simply export the table with a query clause using datapump and import it back with table_exists_action=replace clause. Its will drop and recreate your table and take very less time. Please read about it before implementing.

Bootstrap 3 Glyphicons CDN

If you only want to have glyphicons icons without any additional css you can create a css file and put the code below and include it into main css file.

I have to create this extra file as link below was messing with my site styles too.

//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css

Instead to using it directly I created a css file bootstrap-glyphicons.css

_x000D_
_x000D_
@font-face{font-family:'Glyphicons Halflings';src:url('http://netdna.bootstrapcdn.com/bootstrap/3.0.0/fonts/glyphicons-halflings-regular.eot');src:url('http://netdna.bootstrapcdn.com/bootstrap/3.0.0/fonts/glyphicons-halflings-regular.eot?#iefix') format('embedded-opentype'),url('http://netdna.bootstrapcdn.com/bootstrap/3.0.0/fonts/glyphicons-halflings-regular.woff') format('woff'),url('http://netdna.bootstrapcdn.com/bootstrap/3.0.0/fonts/glyphicons-halflings-regular.ttf') format('truetype'),url('http://netdna.bootstrapcdn.com/bootstrap/3.0.0/fonts/glyphicons-halflings-regular.svg#glyphicons-halflingsregular') format('svg');}.glyphicon{position:relative;top:1px;display:inline-block;font-family:'Glyphicons Halflings';font-style:normal;font-weight:normal;line-height:1;-webkit-font-smoothing:antialiased;}_x000D_
.glyphicon-asterisk:before{content:"\2a";}_x000D_
.glyphicon-plus:before{content:"\2b";}_x000D_
.glyphicon-euro:before{content:"\20ac";}_x000D_
.glyphicon-minus:before{content:"\2212";}_x000D_
.glyphicon-cloud:before{content:"\2601";}_x000D_
.glyphicon-envelope:before{content:"\2709";}_x000D_
.glyphicon-pencil:before{content:"\270f";}_x000D_
.glyphicon-glass:before{content:"\e001";}_x000D_
.glyphicon-music:before{content:"\e002";}_x000D_
.glyphicon-search:before{content:"\e003";}_x000D_
.glyphicon-heart:before{content:"\e005";}_x000D_
.glyphicon-star:before{content:"\e006";}_x000D_
.glyphicon-star-empty:before{content:"\e007";}_x000D_
.glyphicon-user:before{content:"\e008";}_x000D_
.glyphicon-film:before{content:"\e009";}_x000D_
.glyphicon-th-large:before{content:"\e010";}_x000D_
.glyphicon-th:before{content:"\e011";}_x000D_
.glyphicon-th-list:before{content:"\e012";}_x000D_
.glyphicon-ok:before{content:"\e013";}_x000D_
.glyphicon-remove:before{content:"\e014";}_x000D_
.glyphicon-zoom-in:before{content:"\e015";}_x000D_
.glyphicon-zoom-out:before{content:"\e016";}_x000D_
.glyphicon-off:before{content:"\e017";}_x000D_
.glyphicon-signal:before{content:"\e018";}_x000D_
.glyphicon-cog:before{content:"\e019";}_x000D_
.glyphicon-trash:before{content:"\e020";}_x000D_
.glyphicon-home:before{content:"\e021";}_x000D_
.glyphicon-file:before{content:"\e022";}_x000D_
.glyphicon-time:before{content:"\e023";}_x000D_
.glyphicon-road:before{content:"\e024";}_x000D_
.glyphicon-download-alt:before{content:"\e025";}_x000D_
.glyphicon-download:before{content:"\e026";}_x000D_
.glyphicon-upload:before{content:"\e027";}_x000D_
.glyphicon-inbox:before{content:"\e028";}_x000D_
.glyphicon-play-circle:before{content:"\e029";}_x000D_
.glyphicon-repeat:before{content:"\e030";}_x000D_
.glyphicon-refresh:before{content:"\e031";}_x000D_
.glyphicon-list-alt:before{content:"\e032";}_x000D_
.glyphicon-flag:before{content:"\e034";}_x000D_
.glyphicon-headphones:before{content:"\e035";}_x000D_
.glyphicon-volume-off:before{content:"\e036";}_x000D_
.glyphicon-volume-down:before{content:"\e037";}_x000D_
.glyphicon-volume-up:before{content:"\e038";}_x000D_
.glyphicon-qrcode:before{content:"\e039";}_x000D_
.glyphicon-barcode:before{content:"\e040";}_x000D_
.glyphicon-tag:before{content:"\e041";}_x000D_
.glyphicon-tags:before{content:"\e042";}_x000D_
.glyphicon-book:before{content:"\e043";}_x000D_
.glyphicon-print:before{content:"\e045";}_x000D_
.glyphicon-font:before{content:"\e047";}_x000D_
.glyphicon-bold:before{content:"\e048";}_x000D_
.glyphicon-italic:before{content:"\e049";}_x000D_
.glyphicon-text-height:before{content:"\e050";}_x000D_
.glyphicon-text-width:before{content:"\e051";}_x000D_
.glyphicon-align-left:before{content:"\e052";}_x000D_
.glyphicon-align-center:before{content:"\e053";}_x000D_
.glyphicon-align-right:before{content:"\e054";}_x000D_
.glyphicon-align-justify:before{content:"\e055";}_x000D_
.glyphicon-list:before{content:"\e056";}_x000D_
.glyphicon-indent-left:before{content:"\e057";}_x000D_
.glyphicon-indent-right:before{content:"\e058";}_x000D_
.glyphicon-facetime-video:before{content:"\e059";}_x000D_
.glyphicon-picture:before{content:"\e060";}_x000D_
.glyphicon-map-marker:before{content:"\e062";}_x000D_
.glyphicon-adjust:before{content:"\e063";}_x000D_
.glyphicon-tint:before{content:"\e064";}_x000D_
.glyphicon-edit:before{content:"\e065";}_x000D_
.glyphicon-share:before{content:"\e066";}_x000D_
.glyphicon-check:before{content:"\e067";}_x000D_
.glyphicon-move:before{content:"\e068";}_x000D_
.glyphicon-step-backward:before{content:"\e069";}_x000D_
.glyphicon-fast-backward:before{content:"\e070";}_x000D_
.glyphicon-backward:before{content:"\e071";}_x000D_
.glyphicon-play:before{content:"\e072";}_x000D_
.glyphicon-pause:before{content:"\e073";}_x000D_
.glyphicon-stop:before{content:"\e074";}_x000D_
.glyphicon-forward:before{content:"\e075";}_x000D_
.glyphicon-fast-forward:before{content:"\e076";}_x000D_
.glyphicon-step-forward:before{content:"\e077";}_x000D_
.glyphicon-eject:before{content:"\e078";}_x000D_
.glyphicon-chevron-left:before{content:"\e079";}_x000D_
.glyphicon-chevron-right:before{content:"\e080";}_x000D_
.glyphicon-plus-sign:before{content:"\e081";}_x000D_
.glyphicon-minus-sign:before{content:"\e082";}_x000D_
.glyphicon-remove-sign:before{content:"\e083";}_x000D_
.glyphicon-ok-sign:before{content:"\e084";}_x000D_
.glyphicon-question-sign:before{content:"\e085";}_x000D_
.glyphicon-info-sign:before{content:"\e086";}_x000D_
.glyphicon-screenshot:before{content:"\e087";}_x000D_
.glyphicon-remove-circle:before{content:"\e088";}_x000D_
.glyphicon-ok-circle:before{content:"\e089";}_x000D_
.glyphicon-ban-circle:before{content:"\e090";}_x000D_
.glyphicon-arrow-left:before{content:"\e091";}_x000D_
.glyphicon-arrow-right:before{content:"\e092";}_x000D_
.glyphicon-arrow-up:before{content:"\e093";}_x000D_
.glyphicon-arrow-down:before{content:"\e094";}_x000D_
.glyphicon-share-alt:before{content:"\e095";}_x000D_
.glyphicon-resize-full:before{content:"\e096";}_x000D_
.glyphicon-resize-small:before{content:"\e097";}_x000D_
.glyphicon-exclamation-sign:before{content:"\e101";}_x000D_
.glyphicon-gift:before{content:"\e102";}_x000D_
.glyphicon-leaf:before{content:"\e103";}_x000D_
.glyphicon-eye-open:before{content:"\e105";}_x000D_
.glyphicon-eye-close:before{content:"\e106";}_x000D_
.glyphicon-warning-sign:before{content:"\e107";}_x000D_
.glyphicon-plane:before{content:"\e108";}_x000D_
.glyphicon-random:before{content:"\e110";}_x000D_
.glyphicon-comment:before{content:"\e111";}_x000D_
.glyphicon-magnet:before{content:"\e112";}_x000D_
.glyphicon-chevron-up:before{content:"\e113";}_x000D_
.glyphicon-chevron-down:before{content:"\e114";}_x000D_
.glyphicon-retweet:before{content:"\e115";}_x000D_
.glyphicon-shopping-cart:before{content:"\e116";}_x000D_
.glyphicon-folder-close:before{content:"\e117";}_x000D_
.glyphicon-folder-open:before{content:"\e118";}_x000D_
.glyphicon-resize-vertical:before{content:"\e119";}_x000D_
.glyphicon-resize-horizontal:before{content:"\e120";}_x000D_
.glyphicon-hdd:before{content:"\e121";}_x000D_
.glyphicon-bullhorn:before{content:"\e122";}_x000D_
.glyphicon-certificate:before{content:"\e124";}_x000D_
.glyphicon-thumbs-up:before{content:"\e125";}_x000D_
.glyphicon-thumbs-down:before{content:"\e126";}_x000D_
.glyphicon-hand-right:before{content:"\e127";}_x000D_
.glyphicon-hand-left:before{content:"\e128";}_x000D_
.glyphicon-hand-up:before{content:"\e129";}_x000D_
.glyphicon-hand-down:before{content:"\e130";}_x000D_
.glyphicon-circle-arrow-right:before{content:"\e131";}_x000D_
.glyphicon-circle-arrow-left:before{content:"\e132";}_x000D_
.glyphicon-circle-arrow-up:before{content:"\e133";}_x000D_
.glyphicon-circle-arrow-down:before{content:"\e134";}_x000D_
.glyphicon-globe:before{content:"\e135";}_x000D_
.glyphicon-tasks:before{content:"\e137";}_x000D_
.glyphicon-filter:before{content:"\e138";}_x000D_
.glyphicon-fullscreen:before{content:"\e140";}_x000D_
.glyphicon-dashboard:before{content:"\e141";}_x000D_
.glyphicon-heart-empty:before{content:"\e143";}_x000D_
.glyphicon-link:before{content:"\e144";}_x000D_
.glyphicon-phone:before{content:"\e145";}_x000D_
.glyphicon-usd:before{content:"\e148";}_x000D_
.glyphicon-gbp:before{content:"\e149";}_x000D_
.glyphicon-sort:before{content:"\e150";}_x000D_
.glyphicon-sort-by-alphabet:before{content:"\e151";}_x000D_
.glyphicon-sort-by-alphabet-alt:before{content:"\e152";}_x000D_
.glyphicon-sort-by-order:before{content:"\e153";}_x000D_
.glyphicon-sort-by-order-alt:before{content:"\e154";}_x000D_
.glyphicon-sort-by-attributes:before{content:"\e155";}_x000D_
.glyphicon-sort-by-attributes-alt:before{content:"\e156";}_x000D_
.glyphicon-unchecked:before{content:"\e157";}_x000D_
.glyphicon-expand:before{content:"\e158";}_x000D_
.glyphicon-collapse-down:before{content:"\e159";}_x000D_
.glyphicon-collapse-up:before{content:"\e160";}_x000D_
.glyphicon-log-in:before{content:"\e161";}_x000D_
.glyphicon-flash:before{content:"\e162";}_x000D_
.glyphicon-log-out:before{content:"\e163";}_x000D_
.glyphicon-new-window:before{content:"\e164";}_x000D_
.glyphicon-record:before{content:"\e165";}_x000D_
.glyphicon-save:before{content:"\e166";}_x000D_
.glyphicon-open:before{content:"\e167";}_x000D_
.glyphicon-saved:before{content:"\e168";}_x000D_
.glyphicon-import:before{content:"\e169";}_x000D_
.glyphicon-export:before{content:"\e170";}_x000D_
.glyphicon-send:before{content:"\e171";}_x000D_
.glyphicon-floppy-disk:before{content:"\e172";}_x000D_
.glyphicon-floppy-saved:before{content:"\e173";}_x000D_
.glyphicon-floppy-remove:before{content:"\e174";}_x000D_
.glyphicon-floppy-save:before{content:"\e175";}_x000D_
.glyphicon-floppy-open:before{content:"\e176";}_x000D_
.glyphicon-credit-card:before{content:"\e177";}_x000D_
.glyphicon-transfer:before{content:"\e178";}_x000D_
.glyphicon-cutlery:before{content:"\e179";}_x000D_
.glyphicon-header:before{content:"\e180";}_x000D_
.glyphicon-compressed:before{content:"\e181";}_x000D_
.glyphicon-earphone:before{content:"\e182";}_x000D_
.glyphicon-phone-alt:before{content:"\e183";}_x000D_
.glyphicon-tower:before{content:"\e184";}_x000D_
.glyphicon-stats:before{content:"\e185";}_x000D_
.glyphicon-sd-video:before{content:"\e186";}_x000D_
.glyphicon-hd-video:before{content:"\e187";}_x000D_
.glyphicon-subtitles:before{content:"\e188";}_x000D_
.glyphicon-sound-stereo:before{content:"\e189";}_x000D_
.glyphicon-sound-dolby:before{content:"\e190";}_x000D_
.glyphicon-sound-5-1:before{content:"\e191";}_x000D_
.glyphicon-sound-6-1:before{content:"\e192";}_x000D_
.glyphicon-sound-7-1:before{content:"\e193";}_x000D_
.glyphicon-copyright-mark:before{content:"\e194";}_x000D_
.glyphicon-registration-mark:before{content:"\e195";}_x000D_
.glyphicon-cloud-download:before{content:"\e197";}_x000D_
.glyphicon-cloud-upload:before{content:"\e198";}_x000D_
.glyphicon-tree-conifer:before{content:"\e199";}_x000D_
.glyphicon-tree-deciduous:before{content:"\e200";}_x000D_
.glyphicon-briefcase:before{content:"\1f4bc";}_x000D_
.glyphicon-calendar:before{content:"\1f4c5";}_x000D_
.glyphicon-pushpin:before{content:"\1f4cc";}_x000D_
.glyphicon-paperclip:before{content:"\1f4ce";}_x000D_
.glyphicon-camera:before{content:"\1f4f7";}_x000D_
.glyphicon-lock:before{content:"\1f512";}_x000D_
.glyphicon-bell:before{content:"\1f514";}_x000D_
.glyphicon-bookmark:before{content:"\1f516";}_x000D_
.glyphicon-fire:before{content:"\1f525";}_x000D_
.glyphicon-wrench:before{content:"\1f527";}
_x000D_
_x000D_
_x000D_

And imported the created css file into my main css file which enable me to just import the glyphicons only. Hope this help

@import url("bootstrap-glyphicons.css");

How to find unused/dead code in java projects

CodePro was recently released by Google with the Eclipse project. It is free and highly effective. The plugin has a 'Find Dead Code' feature with one/many entry point(s). Works pretty well.

Why, Fatal error: Class 'PHPUnit_Framework_TestCase' not found in ...?

It may well be that you're running WordPress core tests, and have recently upgraded your PhpUnit to version 6. If that's the case, then the recent change to namespacing in PhpUnit will have broken your code.

Fortunately, there's a patch to the core tests at https://core.trac.wordpress.org/changeset/40547 which will work around the problem. It also includes changes to travis.yml, which you may not have in your setup; if that's the case then you'll need to edit the .diff file to ignore the Travis patch.

  1. Download the "Unified Diff" patch from the bottom of https://core.trac.wordpress.org/changeset/40547
  2. Edit the patch file to remove the Travis part of the patch if you don't need that. Delete from the top of the file to just above this line:

    Index: /branches/4.7/tests/phpunit/includes/bootstrap.php
    
  3. Save the diff in the directory above your /includes/ directory - in my case this was the Wordpress directory itself

  4. Use the Unix patch tool to patch the files. You'll also need to strip the first few slashes to move from an absolute to a relative directory structure. As you can see from point 3 above, there are five slashes before the include directory, which a -p5 flag will get rid of for you.

    $ cd [WORDPRESS DIRECTORY]
    $ patch -p5 < changeset_40547.diff 
    

After I did this my tests ran correctly again.

How do I use CSS with a ruby on rails application?

To add to the above, the most obvious place to add stylesheet_link_tag is in your global application layout - application.html.erb.

AngularJS : ng-click not working

i tried using the same ng-click for two elements with same name showDetail2('abc')

it is working for me . can you check rest of the code which may be breaking you to move further.

here is the sample jsfiddle i tried:

How do I draw a grid onto a plot in Python?

Using rcParams you can show grid very easily as follows

plt.rcParams['axes.facecolor'] = 'white'
plt.rcParams['axes.edgecolor'] = 'white'
plt.rcParams['axes.grid'] = True
plt.rcParams['grid.alpha'] = 1
plt.rcParams['grid.color'] = "#cccccc"

If grid is not showing even after changing these parameters then use

plt.grid(True)

before calling

plt.show()

Comparing two joda DateTime instances

This code (example) :

    Chronology ch1 = GregorianChronology.getInstance();     Chronology ch2 = ISOChronology.getInstance();      DateTime dt = new DateTime("2013-12-31T22:59:21+01:00",ch1);     DateTime dt2 = new DateTime("2013-12-31T22:59:21+01:00",ch2);      System.out.println(dt);     System.out.println(dt2);      boolean b = dt.equals(dt2);      System.out.println(b); 

Will print :

2013-12-31T16:59:21.000-05:00 2013-12-31T16:59:21.000-05:00 false 

You are probably comparing two DateTimes with same date but different Chronology.

How do I return a char array from a function?

You have to realize that char[10] is similar to a char* (see comment by @DarkDust). You are in fact returning a pointer. Now the pointer points to a variable (str) which is destroyed as soon as you exit the function, so the pointer points to... nothing!

Usually in C, you explicitly allocate memory in this case, which won't be destroyed when the function ends:

char* testfunc()
{
    char* str = malloc(10 * sizeof(char));
    return str;
}

Be aware though! The memory pointed at by str is now never destroyed. If you don't take care of this, you get something that is known as a 'memory leak'. Be sure to free() the memory after you are done with it:

foo = testfunc();
// Do something with your foo
free(foo); 

What exactly is the difference between Web API and REST API in MVC?

ASP.NET Web API is a framework that makes it easy to build HTTP services that reach a broad range of clients, including browsers and mobile devices. ASP.NET Web API is an ideal platform for building RESTful applications on the .NET Framework.

REST

RESTs sweet spot is when you are exposing a public API over the internet to handle CRUD operations on data. REST is focused on accessing named resources through a single consistent interface.

SOAP

SOAP brings it’s own protocol and focuses on exposing pieces of application logic (not data) as services. SOAP exposes operations. SOAP is focused on accessing named operations, each implement some business logic through different interfaces.

Though SOAP is commonly referred to as “web services” this is a misnomer. SOAP has very little if anything to do with the Web. REST provides true “Web services” based on URIs and HTTP.

Reference: http://spf13.com/post/soap-vs-rest

And finally: What they could be referring to is REST vs. RPC See this: http://encosia.com/rest-vs-rpc-in-asp-net-web-api-who-cares-it-does-both/

Find and replace entire mysql database

I had the same issue on MySQL. I took the procedure from symcbean and adapted her to my needs.

Mine is only replacing textual values (or any type you put in the SELECT FROM information_schema) so if you have date fields, you will not have an error in execution.

Mind the collate in SET @stmt, it must match you database collation.

I used a template request in a variable with multiple replaces but if you have motivation, you could have done it with one CONCAT().

Anyway, if you have serialized data in your database, don't use this. It will not work unless you replace your string with a string with the same lenght.

Hope it helps someone.

DELIMITER $$

DROP PROCEDURE IF EXISTS replace_all_occurences_in_database$$
CREATE PROCEDURE replace_all_occurences_in_database (find_string varchar(255), replace_string varchar(255))
BEGIN
  DECLARE loop_done integer DEFAULT 0;
  DECLARE current_table varchar(255);
  DECLARE current_column varchar(255);
  DECLARE all_columns CURSOR FOR
  SELECT
    t.table_name,
    c.column_name
  FROM information_schema.tables t,
       information_schema.columns c
  WHERE t.table_schema = DATABASE()
  AND c.table_schema = DATABASE()
  AND t.table_name = c.table_name
  AND c.DATA_TYPE IN('varchar', 'text', 'longtext');

  DECLARE CONTINUE HANDLER FOR NOT FOUND
  SET loop_done = 1;

  OPEN all_columns;

table_loop:
LOOP
  FETCH all_columns INTO current_table, current_column;
  IF (loop_done > 0) THEN
    LEAVE table_loop;
  END IF;
  SET @stmt = 'UPDATE `|table|` SET `|column|` = REPLACE(`|column|`, "|find|", "|replace|") WHERE `|column|` LIKE "%|find|%"' COLLATE `utf8mb4_unicode_ci`;
  SET @stmt = REPLACE(@stmt, '|table|', current_table);
  SET @stmt = REPLACE(@stmt, '|column|', current_column);
  SET @stmt = REPLACE(@stmt, '|find|', find_string);
  SET @stmt = REPLACE(@stmt, '|replace|', replace_string);
  PREPARE s1 FROM @stmt;
  EXECUTE s1;
  DEALLOCATE PREPARE s1;
END LOOP;
END
$$

DELIMITER ;

Algorithm to find all Latitude Longitude locations within a certain distance from a given Lat Lng location

Start by Comparing the distance between latitudes. Each degree of latitude is approximately 69 miles (111 kilometers) apart. The range varies (due to the earth's slightly ellipsoid shape) from 68.703 miles (110.567 km) at the equator to 69.407 (111.699 km) at the poles. The distance between two locations will be equal or larger than the distance between their latitudes.

Note that this is not true for longitudes - the length of each degree of longitude is dependent on the latitude. However, if your data is bounded to some area (a single country for example) - you can calculate a minimal and maximal bounds for the longitudes as well.


Continue will a low-accuracy, fast distance calculation that assumes spherical earth:

The great circle distance d between two points with coordinates {lat1,lon1} and {lat2,lon2} is given by:

d = acos(sin(lat1)*sin(lat2)+cos(lat1)*cos(lat2)*cos(lon1-lon2))

A mathematically equivalent formula, which is less subject to rounding error for short distances is:

d = 2*asin(sqrt((sin((lat1-lat2)/2))^2 +
    cos(lat1)*cos(lat2)*(sin((lon1-lon2)/2))^2))

d is the distance in radians

distance_km ˜ radius_km * distance_radians ˜ 6371 * d

(6371 km is the average radius of the earth)

This method computational requirements are mimimal. However the result is very accurate for small distances.


Then, if it is in a given distance, more or less, use a more accurate method.

GeographicLib is the most accurate implementation I know, though Vincenty inverse formula may be used as well.


If you are using an RDBMS, set the latitude as the primary key and the longitude as a secondary key. Query for a latitude range, or for a latitude/longitude range, as described above, then calculate the exact distances for the result set.

Note that modern versions of all major RDBMSs support geographical data-types and queries natively.

Amazon S3 upload file and get URL

No you cannot get the URL in single action but two :)

First of all, you may have to make the file public before uploading because it makes no sense to get the URL that no one can access. You can do so by setting ACL as Michael Astreiko suggested. You can get the resource URL either by calling getResourceUrl or getUrl.

AmazonS3Client s3Client = (AmazonS3Client)AmazonS3ClientBuilder.defaultClient();
s3Client.putObject(new PutObjectRequest("your-bucket", "some-path/some-key.jpg", new File("somePath/someKey.jpg")).withCannedAcl(CannedAccessControlList.PublicRead))
s3Client.getResourceUrl("your-bucket", "some-path/some-key.jpg");

Note1: The different between getResourceUrl and getUrl is that getResourceUrl will return null when exception occurs.

Note2: getUrl method is not defined in the AmazonS3 interface. You have to cast the object to AmazonS3Client if you use the standard builder.

Python Linked List

Immutable lists are best represented through two-tuples, with None representing NIL. To allow simple formulation of such lists, you can use this function:

def mklist(*args):
    result = None
    for element in reversed(args):
        result = (element, result)
    return result

To work with such lists, I'd rather provide the whole collection of LISP functions (i.e. first, second, nth, etc), than introducing methods.

Python: How to ignore an exception and proceed?

Try this:

try:
    blah()
except:
    pass

Limiting the output of PHP's echo to 200 characters

function TitleTextLimit($text,$limit=200){
 if(strlen($text)<=$limit){
    echo $text;
 }else{
    $text = substr($text,0,$limit) . '...';
    echo $text;
 }

How do you print in a Go test using the "testing" package?

t.Log() will not show up until after the test is complete, so if you're trying to debug a test that is hanging or performing badly it seems you need to use fmt.

Yes: that was the case up to Go 1.13 (August 2019) included.

And that was followed in golang.org issue 24929

Consider the following (silly) automated tests:

func TestFoo(t *testing.T) {
    t.Parallel()

  for i := 0; i < 15; i++ {
        t.Logf("%d", i)
        time.Sleep(3 * time.Second)
    }
}

func TestBar(t *testing.T) {
    t.Parallel()

  for i := 0; i < 15; i++ {
        t.Logf("%d", i)
        time.Sleep(2 * time.Second)
    }
}

func TestBaz(t *testing.T) {
    t.Parallel()

  for i := 0; i < 15; i++ {
        t.Logf("%d", i)
        time.Sleep(1 * time.Second)
    }
}

If I run go test -v, I get no log output until all of TestFoo is done, then no output until all of TestBar is done, and again no more output until all of TestBaz is done.
This is fine if the tests are working, but if there is some sort of bug, there are a few cases where buffering log output is problematic:

  • When iterating locally, I want to be able to make a change, run my tests, see what's happening in the logs immediately to understand what's going on, hit CTRL+C to shut the test down early if necessary, make another change, re-run the tests, and so on.
    If TestFoo is slow (e.g., it's an integration test), I get no log output until the very end of the test. This significantly slows down iteration.
  • If TestFoo has a bug that causes it to hang and never complete, I'd get no log output whatsoever. In these cases, t.Log and t.Logf are of no use at all.
    This makes debugging very difficult.
  • Moreover, not only do I get no log output, but if the test hangs too long, either the Go test timeout kills the test after 10 minutes, or if I increase that timeout, many CI servers will also kill off tests if there is no log output after a certain amount of time (e.g., 10 minutes in CircleCI).
    So now my tests are killed and I have nothing in the logs to tell me what happened.

But for (possibly) Go 1.14 (Q1 2020): CL 127120

testing: stream log output in verbose mode

The output now is:

=== RUN   TestFoo
=== PAUSE TestFoo
=== RUN   TestBar
=== PAUSE TestBar
=== RUN   TestGaz
=== PAUSE TestGaz
=== CONT  TestFoo
    TestFoo: main_test.go:14: hello from foo
=== CONT  TestGaz
=== CONT  TestBar
    TestGaz: main_test.go:38: hello from gaz
    TestBar: main_test.go:26: hello from bar
    TestFoo: main_test.go:14: hello from foo
    TestBar: main_test.go:26: hello from bar
    TestGaz: main_test.go:38: hello from gaz
    TestFoo: main_test.go:14: hello from foo
    TestGaz: main_test.go:38: hello from gaz
    TestBar: main_test.go:26: hello from bar
    TestFoo: main_test.go:14: hello from foo
    TestGaz: main_test.go:38: hello from gaz
    TestBar: main_test.go:26: hello from bar
    TestGaz: main_test.go:38: hello from gaz
    TestFoo: main_test.go:14: hello from foo
    TestBar: main_test.go:26: hello from bar
--- PASS: TestFoo (1.00s)
--- PASS: TestGaz (1.00s)
--- PASS: TestBar (1.00s)
PASS
ok      dummy/streaming-test    1.022s

It is indeed in Go 1.14, as Dave Cheney attests in "go test -v streaming output":

In Go 1.14, go test -v will stream t.Log output as it happens, rather than hoarding it til the end of the test run.

Under Go 1.14 the fmt.Println and t.Log lines are interleaved, rather than waiting for the test to complete, demonstrating that test output is streamed when go test -v is used.

Advantage, according to Dave:

This is a great quality of life improvement for integration style tests that often retry for long periods when the test is failing.
Streaming t.Log output will help Gophers debug those test failures without having to wait until the entire test times out to receive their output.

DLL and LIB files - what and why?

One other difference lies in the performance.

As the DLL is loaded at runtime by the .exe(s), the .exe(s) and the DLL work with shared memory concept and hence the performance is low relatively to static linking.

On the other hand, a .lib is code that is linked statically at compile time into every process that requests. Hence the .exe(s) will have single memory, thus increasing the performance of the process.

How to save a bitmap on internal storage

To Save your bitmap in sdcard use the following code

Store Image

private void storeImage(Bitmap image) {
    File pictureFile = getOutputMediaFile();
    if (pictureFile == null) {
        Log.d(TAG,
                "Error creating media file, check storage permissions: ");// e.getMessage());
        return;
    } 
    try {
        FileOutputStream fos = new FileOutputStream(pictureFile);
        image.compress(Bitmap.CompressFormat.PNG, 90, fos);
        fos.close();
    } catch (FileNotFoundException e) {
        Log.d(TAG, "File not found: " + e.getMessage());
    } catch (IOException e) {
        Log.d(TAG, "Error accessing file: " + e.getMessage());
    }  
}

To Get the Path for Image Storage

/** Create a File for saving an image or video */
private  File getOutputMediaFile(){
    // To be safe, you should check that the SDCard is mounted
    // using Environment.getExternalStorageState() before doing this. 
    File mediaStorageDir = new File(Environment.getExternalStorageDirectory()
            + "/Android/data/"
            + getApplicationContext().getPackageName()
            + "/Files"); 

    // This location works best if you want the created images to be shared
    // between applications and persist after your app has been uninstalled.

    // Create the storage directory if it does not exist
    if (! mediaStorageDir.exists()){
        if (! mediaStorageDir.mkdirs()){
            return null;
        }
    } 
    // Create a media file name
    String timeStamp = new SimpleDateFormat("ddMMyyyy_HHmm").format(new Date());
    File mediaFile;
        String mImageName="MI_"+ timeStamp +".jpg";
        mediaFile = new File(mediaStorageDir.getPath() + File.separator + mImageName);  
    return mediaFile;
} 

EDIT From Your comments i have edited the onclick view in this the button1 and button2 functions will be executed separately.

public onClick(View v){

switch(v.getId()){
case R.id.button1:
//Your button 1 function
break;
case R.id. button2:
//Your button 2 function
break;
} 
}

Getting "type or namespace name could not be found" but everything seems ok?

Struggled with this for a while, and not for the first time. In times past it usually was a configuration mismatch, but this time it wasn't.

This time it has turned out to be that Auto-Generate Binding Redirects was set to true in my application.

Indeed, if I set it to true in my library, then my library gets this error for types in the Microsoft.Reporting namespace, and if I set it to true in my application, then my application gets this error for types from my library.

Additionally, it seems that the value defaults to false for my library, but true for my application. So if I don't specify either one, my library builds fine but my application gets the error for my library. So, I have to specifically set it to false in my application or else I will get this error with no indication as to why.

I also find that I will get this message regardless of the setting if a project is not using sdk csproj. Once I convert to sdk csproj, then the setting makes a difference.

Also, in my case, this all seems to specifically have to do with the Microsoft.ReportingServices.ReportViewerControl.Winforms nuget package, which is in my root library.

git replace local version with remote version

I understand the question as this: you want to completely replace the contents of one file (or a selection) from upstream. You don't want to affect the index directly (so you would go through add + commit as usual).

Simply do

git checkout remote/branch -- a/file b/another/file

If you want to do this for extensive subtrees and instead wish to affect the index directly use

git read-tree remote/branch:subdir/

You can then (optionally) update your working copy by doing

git checkout-index -u --force

What do Push and Pop mean for Stacks?

The algorithm to go from infix to prefix expressions is:

-reverse input

TOS = top of stack
If next symbol is:
 - an operand -> output it
 - an operator ->
        while TOS is an operator of higher priority -> pop and output TOS
        push symbol
 - a closing parenthesis -> push it
 - an opening parenthesis -> pop and output TOS until TOS is matching
        parenthesis, then pop and discard TOS.

-reverse output

So your example goes something like (x PUSH, o POP):

2*3/(2-1)+5*(4-1)
)1-4(*5+)1-2(/3*2

Next
Symbol  Stack           Output
)       x )
1         )             1
-       x )-            1
4         )-            14
(       o )             14-
        o               14-
*       x *             14-
5         *             14-5
+       o               14-5*
        x +             14-5*
)       x +)            14-5*
1         +)            14-5*1
-       x +)-           14-5*1
2         +)-           14-5*12
(       o +)            14-5*12-
        o +             14-5*12-
/       x +/            14-5*12-
3         +/            14-5*12-3
*       x +/*           14-5*12-3
2         +/*           14-5*12-32
        o +/            14-5*12-32*
        o +             14-5*12-32*/
        o               14-5*12-32*/+

+/*23-21*5-41

How to increase image size of pandas.DataFrame.plot in jupyter notebook?

Try figsize param in df.plot(figsize=(width,height)):

df = pd.DataFrame({"a":[1,2],"b":[1,2]})
df.plot(figsize=(3,3));

enter image description here

df = pd.DataFrame({"a":[1,2],"b":[1,2]})
df.plot(figsize=(5,3));

enter image description here

The size in figsize=(5,3) is given in inches per (width, height)

https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.plot.html

How do I get the last inserted ID of a MySQL table in PHP?

You can get the latest inserted id by the in built php function mysql_insert_id();

$id = mysql_insert_id();

you an also get the latest id by

$id = last_insert_id();

Implement paging (skip / take) functionality with this query

In order to do this in SQL Server, you must order the query by a column, so you can specify the rows you want.

Example:

select * from table order by [some_column] 
offset 10 rows
FETCH NEXT 10 rows only

And you can't use the "TOP" keyword when doing this.

You can learn more here: https://technet.microsoft.com/pt-br/library/gg699618%28v=sql.110%29.aspx

How do I insert values into a Map<K, V>?

The syntax is

data.put("John","Taxi driver");

Count unique values in a column in Excel

Here's an elegant array formula (which I found here http://www.excel-easy.com/examples/count-unique-values.html) that does the trick nicely:

Type

=SUM(1/COUNTIF(List,List))

and confirm with CTRL-SHIFT-ENTER

Caching a jquery ajax response in javascript/browser

        function getDatas() {
            let cacheKey = 'memories';

            if (cacheKey in localStorage) {
                let datas = JSON.parse(localStorage.getItem(cacheKey));

                // if expired
                if (datas['expires'] < Date.now()) {
                    localStorage.removeItem(cacheKey);

                    getDatas()
                } else {
                    setDatas(datas);
                }
            } else {
                $.ajax({
                    "dataType": "json",
                    "success": function(datas, textStatus, jqXHR) {
                        let today = new Date();

                        datas['expires'] = today.setDate(today.getDate() + 7) // expires in next 7 days

                        setDatas(datas);

                        localStorage.setItem(cacheKey, JSON.stringify(datas));
                    },
                    "url": "http://localhost/phunsanit/snippets/PHP/json.json_encode.php",
                });
            }
        }

        function setDatas(datas) {
            // display json as text
            $('#datasA').text(JSON.stringify(datas));

            // your code here
           ....

        }

        // call
        getDatas();

enter link description here

How to sum a variable by group

You can also use the dplyr package for that purpose:

library(dplyr)
x %>% 
  group_by(Category) %>% 
  summarise(Frequency = sum(Frequency))

#Source: local data frame [3 x 2]
#
#  Category Frequency
#1    First        30
#2   Second         5
#3    Third        34

Or, for multiple summary columns (works with one column too):

x %>% 
  group_by(Category) %>% 
  summarise(across(everything(), sum))

Here are some more examples of how to summarise data by group using dplyr functions using the built-in dataset mtcars:

# several summary columns with arbitrary names
mtcars %>% 
  group_by(cyl, gear) %>%                            # multiple group columns
  summarise(max_hp = max(hp), mean_mpg = mean(mpg))  # multiple summary columns

# summarise all columns except grouping columns using "sum" 
mtcars %>% 
  group_by(cyl) %>% 
  summarise(across(everything(), sum))

# summarise all columns except grouping columns using "sum" and "mean"
mtcars %>% 
  group_by(cyl) %>% 
  summarise(across(everything(), list(mean = mean, sum = sum)))

# multiple grouping columns
mtcars %>% 
  group_by(cyl, gear) %>% 
  summarise(across(everything(), list(mean = mean, sum = sum)))

# summarise specific variables, not all
mtcars %>% 
  group_by(cyl, gear) %>% 
  summarise(across(c(qsec, mpg, wt), list(mean = mean, sum = sum)))

# summarise specific variables (numeric columns except grouping columns)
mtcars %>% 
  group_by(gear) %>% 
  summarise(across(where(is.numeric), list(mean = mean, sum = sum)))

For more information, including the %>% operator, see the introduction to dplyr.

How to use the CSV MIME-type?

This code can be used to export any file, including csv

// application/octet-stream tells the browser not to try to interpret the file
header('Content-type: application/octet-stream');
header('Content-Length: ' . filesize($data));
header('Content-Disposition: attachment; filename="export.csv"');

Update React component every second

So you were on the right track. Inside your componentDidMount() you could have finished the job by implementing setInterval() to trigger the change, but remember the way to update a components state is via setState(), so inside your componentDidMount() you could have done this:

componentDidMount() {
  setInterval(() => {
   this.setState({time: Date.now()})    
  }, 1000)
}

Also, you use Date.now() which works, with the componentDidMount() implementation I offered above, but you will get a long set of nasty numbers updating that is not human readable, but it is technically the time updating every second in milliseconds since January 1, 1970, but we want to make this time readable to how we humans read time, so in addition to learning and implementing setInterval you want to learn about new Date() and toLocaleTimeString() and you would implement it like so:

class TimeComponent extends Component {
  state = { time: new Date().toLocaleTimeString() };
}

componentDidMount() {
  setInterval(() => {
   this.setState({ time: new Date().toLocaleTimeString() })    
  }, 1000)
}

Notice I also removed the constructor() function, you do not necessarily need it, my refactor is 100% equivalent to initializing site with the constructor() function.

Have border wrap around text

The easiest way to do it is to make the display an inline block

<div id='page' style='width: 600px'>
  <h1 style='border:2px black solid; font-size:42px; display: inline-block;'>Title</h1>
</div>

if you do this it should work

PostgreSQL next value of the sequences?

RETURNING

Since PostgreSQL 8.2, that's possible with a single round-trip to the database:

INSERT INTO tbl(filename)
VALUES ('my_filename')
RETURNING tbl_id;

tbl_id would typically be a serial or IDENTITY (Postgres 10 or later) column. More in the manual.

Explicitly fetch value

If filename needs to include tbl_id (redundantly), you can still use a single query.

Use lastval() or the more specific currval():

INSERT INTO tbl (filename)
VALUES ('my_filename' || currval('tbl_tbl_id_seq')   -- or lastval()
RETURNING tbl_id;

See:

If multiple sequences may be advanced in the process (even by way of triggers or other side effects) the sure way is to use currval('tbl_tbl_id_seq').

Name of sequence

The string literal 'tbl_tbl_id_seq' in my example is supposed to be the actual name of the sequence and is cast to regclass, which raises an exception if no sequence of that name can be found in the current search_path.

tbl_tbl_id_seq is the automatically generated default for a table tbl with a serial column tbl_id. But there are no guarantees. A column default can fetch values from any sequence if so defined. And if the default name is taken when creating the table, Postgres picks the next free name according to a simple algorithm.

If you don't know the name of the sequence for a serial column, use the dedicated function pg_get_serial_sequence(). Can be done on the fly:

INSERT INTO tbl (filename)
VALUES ('my_filename' || currval(pg_get_serial_sequence('tbl', 'tbl_id'))
RETURNING tbl_id;

db<>fiddle here
Old sqlfiddle

Converting byte array to string in javascript

I had some decrypted byte arrays with padding characters and other stuff I didn't need, so I did this (probably not perfect, but it works for my limited use)

var junk = String.fromCharCode.apply(null, res).split('').map(char => char.charCodeAt(0) <= 127 && char.charCodeAt(0) >= 32 ? char : '').join('');

Array of an unknown length in C#

A little background information:

As said, if you want to have a dynamic collection of things, use a List<T>. Internally, a List uses an array for storage too. That array has a fixed size just like any other array. Once an array is declared as having a size, it doesn't change. When you add an item to a List, it's added to the array. Initially, the List starts out with an array that I believe has a length of 16. When you try to add the 17th item to the List, what happens is that a new array is allocated, that's (I think) twice the size of the old one, so 32 items. Then the content of the old array is copied into the new array. So while a List may appear dynamic to the outside observer, internally it has to comply to the rules as well.

And as you might have guessed, the copying and allocation of the arrays isn't free so one should aim to have as few of those as possible and to do that you can specify (in the constructor of List) an initial size of the array, which in a perfect scenario is just big enough to hold everything you want. However, this is micro-optimization and it's unlikely it will ever matter to you, but it's always nice to know what you're actually doing.

Calling a method every x minutes

I based this on @asawyer's answer. He doesn't seem to get a compile error, but some of us do. Here is a version which the C# compiler in Visual Studio 2010 will accept.

var timer = new System.Threading.Timer(
    e => MyMethod(),  
    null, 
    TimeSpan.Zero, 
    TimeSpan.FromMinutes(5));

UIView frame, bounds and center

This question already has a good answer, but I want to supplement it with some more pictures. My full answer is here.

To help me remember frame, I think of a picture frame on a wall. Just like a picture can be moved anywhere on the wall, the coordinate system of a view's frame is the superview. (wall=superview, frame=view)

To help me remember bounds, I think of the bounds of a basketball court. The basketball is somewhere within the court just like the coordinate system of the view's bounds is within the view itself. (court=view, basketball/players=content inside the view)

Like the frame, view.center is also in the coordinates of the superview.

Frame vs Bounds - Example 1

The yellow rectangle represents the view's frame. The green rectangle represents the view's bounds. The red dot in both images represents the origin of the frame or bounds within their coordinate systems.

Frame
    origin = (0, 0)
    width = 80
    height = 130

Bounds 
    origin = (0, 0)
    width = 80
    height = 130

enter image description here


Example 2

Frame
    origin = (40, 60)  // That is, x=40 and y=60
    width = 80
    height = 130

Bounds 
    origin = (0, 0)
    width = 80
    height = 130

enter image description here


Example 3

Frame
    origin = (20, 52)  // These are just rough estimates.
    width = 118
    height = 187

Bounds 
    origin = (0, 0)
    width = 80
    height = 130

enter image description here


Example 4

This is the same as example 2, except this time the whole content of the view is shown as it would look like if it weren't clipped to the bounds of the view.

Frame
    origin = (40, 60)
    width = 80
    height = 130

Bounds 
    origin = (0, 0)
    width = 80
    height = 130

enter image description here


Example 5

Frame
    origin = (40, 60)
    width = 80
    height = 130

Bounds 
    origin = (280, 70)
    width = 80
    height = 130

enter image description here

Again, see here for my answer with more details.

How do I check if an element is really visible with JavaScript?

For the point 2.

I see that no one has suggested to use document.elementFromPoint(x,y), to me it is the fastest way to test if an element is nested or hidden by another. You can pass the offsets of the targetted element to the function.

Here's PPK test page on elementFromPoint.

From MDN's documentation:

The elementFromPoint() method—available on both the Document and ShadowRoot objects—returns the topmost Element at the specified coordinates (relative to the viewport).

Why does Eclipse complain about @Override on interface methods?

Use Eclipse to search and replace (remove) all instances of "@Override". Then add back the non-interface overrides using "Clean Up".

Steps:

  1. Select the projects or folders containing your source files.
  2. Go to "Search > Search..." (Ctrl-H) to bring up the Search dialog.
  3. Go to the "File Search" tab.
  4. Enter "@Override" in "Containing text" and "*.java" in "File name patterns". Click "Replace...", then "OK", to remove all instances of "@Override".
  5. Go to "Window > Preferences > Java > Code Style > Clean Up" and create a new profile.
  6. Edit the profile, and uncheck everything except "Missing Code > Add missing Annotations > @Override". Make sure "Implementations of interface methods" is unchecked.
  7. Select the projects or folders containing your source files.
  8. Select "Source > Clean Up..." (Alt+Shift+s, then u), then "Finish" to add back the non-interface overrides.

How do I delete an entity from symfony2

Symfony is smart and knows how to make the find() by itself :

public function deleteGuestAction(Guest $guest)
{
    if (!$guest) {
        throw $this->createNotFoundException('No guest found');
    }

    $em = $this->getDoctrine()->getEntityManager();
    $em->remove($guest);
    $em->flush();

    return $this->redirect($this->generateUrl('GuestBundle:Page:viewGuests.html.twig'));
}

To send the id in your controller, use {{ path('your_route', {'id': guest.id}) }}

Shortcut to Apply a Formula to an Entire Column in Excel

Try double-clicking on the bottom right hand corner of the cell (ie on the box that you would otherwise drag).

Copy filtered data to another sheet using VBA

Best way of doing it

Below code is to copy the visible data in DBExtract sheet, and paste it into duplicateRecords sheet, with only filtered values. Range selected by me is the maximum range that can be occupied by my data. You can change it as per your need.

  Sub selectVisibleRange()

    Dim DbExtract, DuplicateRecords As Worksheet
    Set DbExtract = ThisWorkbook.Sheets("Export Worksheet")
    Set DuplicateRecords = ThisWorkbook.Sheets("DuplicateRecords")

    DbExtract.Range("A1:BF9999").SpecialCells(xlCellTypeVisible).Copy
    DuplicateRecords.Cells(1, 1).PasteSpecial


    End Sub

Does uninstalling a package with "pip" also remove the dependent packages?

i've successfully removed dependencies of a package using this bash line:

for dep in $(pip show somepackage | grep Requires | sed 's/Requires: //g; s/,//g') ; do pip uninstall -y $dep ; done

this worked on pip 1.5.4

Is it valid to define functions in JSON results?

A short answer is NO...

JSON is a text format that is completely language independent but uses conventions that are familiar to programmers of the C-family of languages, including C, C++, C#, Java, JavaScript, Perl, Python, and many others. These properties make JSON an ideal data-interchange language.

Look at the reason why:

When exchanging data between a browser and a server, the data can only be text.

JSON is text, and we can convert any JavaScript object into JSON, and send JSON to the server.

We can also convert any JSON received from the server into JavaScript objects.

This way we can work with the data as JavaScript objects, with no complicated parsing and translations.

But wait...

There is still ways to store your function, it's widely not recommended to that, but still possible:

We said, you can save a string... how about converting your function to a string then?

const data = {func: '()=>"a FUNC"'};

Then you can stringify data using JSON.stringify(data) and then using JSON.parse to parse it (if this step needed)...

And eval to execute a string function (before doing that, just let you know using eval widely not recommended):

eval(data.func)(); //return "a FUNC"

What is the best way to convert seconds into (Hour:Minutes:Seconds:Milliseconds) time?

to get total seconds

var i = TimeSpan.FromTicks(startDate.Ticks).TotalSeconds;

and to get datetime from seconds

var thatDateTime = new DateTime().AddSeconds(i)

Get restaurants near my location

Is this what you are looking for?

https://maps.googleapis.com/maps/api/place/search/xml?location=49.260691,-123.137784&radius=500&sensor=false&key=*PlacesAPIKey*&types=restaurant

types is optional

How do I add 24 hours to a unix timestamp in php?

A Unix timestamp is simply the number of seconds since January the first 1970, so to add 24 hours to a Unix timestamp we just add the number of seconds in 24 hours. (24 * 60 *60)

time() + 24*60*60;

Get Selected Item Using Checkbox in Listview

make the checkbox non-focusable, and on list-item click do this, here codevalue is the position.

    Arraylist<Integer> selectedschools=new Arraylist<Integer>();

    lvPickSchool.setOnItemClickListener(new AdapterView.OnItemClickListener() 
  {

   @Override
        public void onItemClick(AdapterView<?> parent, View view, int codevalue, long id)
   {
                      CheckBox cb = (CheckBox) view.findViewById(R.id.cbVisitingStatus);

            cb.setChecked(!cb.isChecked());
            if(cb.isChecked())
            {

                if(!selectedschool.contains(codevaule))
                {
                    selectedschool.add(codevaule);
                }
            }
            else
            {
                if(selectedschool.contains(codevaule))
                {
                    selectedschool.remove(codevaule);
                }
            }
        }
    });

fork: retry: Resource temporarily unavailable

Another possibility is too many threads. We just ran into this error message when running a test harness against an app that uses a thread pool. We used

watch -n 5 -d "ps -eL <java_pid> | wc -l"

to watch the ongoing count of Linux native threads running within the given Java process ID. After this hit about 1,000 (for us--YMMV), we started getting the error message you mention.

How to get names of classes inside a jar file?

You can try this :

unzip -v /your/jar.jar

This will be helpful only if your jar is executable i.e. in manifest you have defined some class as main class

PHP Configuration: It is not safe to rely on the system's timezone settings

also you can try this

date.timezone = <?php date('Y'); ?>

Bytes of a string in Java

Try this :

Bytes.toBytes(x).length

Assuming you declared and initialized x before

How to submit form on change of dropdown list?

Simple JavaScript will do -

<form action="myservlet.do" method="POST">
    <select name="myselect" id="myselect" onchange="this.form.submit()">
        <option value="1">One</option>
        <option value="2">Two</option>
        <option value="3">Three</option>
        <option value="4">Four</option>
    </select>
</form>

Here is a link for a good javascript tutorial.

Unix shell script find out which directory the script file resides?

BASE_DIR="$(cd "$(dirname "$0")"; pwd)";
echo "BASE_DIR => $BASE_DIR"

disable a hyperlink using jQuery

Try:

$(this).prop( "disabled", true );

MongoDb shuts down with Code 100

In my case, I got a similar error and it was happening because I had run mongod with the root user and that had created a log file only accessible by the root. I could fix this by changing the ownership from root to the user you normally run mongod from. The log file was in /var/lib/mongodb/journal/

Git pull a certain branch from GitHub

for pulling the branch from GitHub you can use

git checkout --track origin/the-branch-name

Make sure that the branch name is exactly the same.

How to center div vertically inside of absolutely positioned parent div

An additional simple solution

HTML:

<div id="d1">
    <div id="d2">
        Text
    </div>
</div>

CSS:

#d1{
    position:absolute;
    top:100px;left:100px;
}

#d2{
    border:1px solid black;
    height:50px; width:50px;
    display:table-cell;
    vertical-align:middle;
    text-align:center;  
}

How to resolve merge conflicts in Git repository?

See How Conflicts Are Presented or, in Git, the git merge documentation to understand what merge conflict markers are.

Also, the How to Resolve Conflicts section explains how to resolve the conflicts:

After seeing a conflict, you can do two things:

  • Decide not to merge. The only clean-ups you need are to reset the index file to the HEAD commit to reverse 2. and to clean up working tree changes made by 2. and 3.; git merge --abort can be used for this.

  • Resolve the conflicts. Git will mark the conflicts in the working tree. Edit the files into shape and git add them to the index. Use git commit to seal the deal.

You can work through the conflict with a number of tools:

  • Use a mergetool. git mergetool to launch a graphical mergetool which will work you through the merge.

  • Look at the diffs. git diff will show a three-way diff, highlighting changes from both the HEAD and MERGE_HEAD versions.

  • Look at the diffs from each branch. git log --merge -p <path> will show diffs first for the HEAD version and then the MERGE_HEAD version.

  • Look at the originals. git show :1:filename shows the common ancestor, git show :2:filename shows the HEAD version, and git show :3:filename shows the MERGE_HEAD version.

You can also read about merge conflict markers and how to resolve them in the Pro Git book section Basic Merge Conflicts.

Go to Matching Brace in Visual Studio?

On my Italian keyboard, it's CTRL + ^.

Get Character value from KeyCode in JavaScript... then trim

I know this is an old question, but I came across it today searching for a pre-packaged solution to this problem, and found nothing that really met my needs.

Here is a solution (English only) that correctly supports Upper Case (shifted), Lower Case, punctuation, number keypad, etc.

It also allows for simple and straight-forward identification of - and reaction to - non-printable keys, like ESC, Arrows, Function keys, etc.

https://jsfiddle.net/5hhu896g/1/

keyboardCharMap and keyboardNameMap are the key to making this work

Thanks to DaveAlger for saving me some typing - and much discovery! - by providing the Named Key Array.

Comparing mongoose _id and strings

converting object id to string(using toString() method) will do the job.

How do I pre-populate a jQuery Datepicker textbox with today's date?

Try this

$(this).datepicker("destroy").datepicker({
            changeMonth: false, changeYear: false,defaultDate:new Date(), dateFormat: "dd-mm-yy",  showOn: "focus", yearRange: "-5:+10"
        }).focus();

Javascript - Append HTML to container element without innerHTML

To give an alternative (as using DocumentFragment does not seem to work): You can simulate it by iterating over the children of the newly generated node and only append those.

var e = document.createElement('div');
e.innerHTML = htmldata;

while(e.firstChild) {
    element.appendChild(e.firstChild);
}

Redirect to an external URL from controller action in Spring MVC

Did you try RedirectView where you can provide the contextRelative parameter?

What should be the sizeof(int) on a 64-bit machine?

Size of a pointer should be 8 byte on any 64-bit C/C++ compiler, but not necessarily size of int.

jQuery table sort

My vote! jquery.sortElements.js and simple jquery
Very simple, very easy, thanks nandhp...

            $('th').live('click', function(){

            var th = $(this), thIndex = th.index(), var table = $(this).parent().parent();

                switch($(this).attr('inverse')){
                case 'false': inverse = true; break;
                case 'true:': inverse = false; break;
                default: inverse = false; break;
                }
            th.attr('inverse',inverse)

            table.find('td').filter(function(){
                return $(this).index() === thIndex;
            }).sortElements(function(a, b){
                return $.text([a]) > $.text([b]) ?
                    inverse ? -1 : 1
                    : inverse ? 1 : -1;
            }, function(){
                // parentNode is the element we want to move
                return this.parentNode; 
            });
            inverse = !inverse;     
            });

Dei uma melhorada do código
One cod better! Function for All tables in all Th in all time... Look it!
DEMO

Html/PHP - Form - Input as array

in addition: for those who have a empty POST variable, don't use this:

name="[levels][level][]"

rather use this (as it is already here in this example):

name="levels[level][]"

Google maps API V3 - multiple markers on exact same spot

@Ignatius most excellent answer, updated to work with v2.0.7 of MarkerClustererPlus.

  1. Add a prototype click method in the MarkerClusterer class, like so - we will override this later in the map initialize() function:

    // BEGIN MODIFICATION (around line 715)
    MarkerClusterer.prototype.onClick = function() { 
        return true; 
    };
    // END MODIFICATION
    
  2. In the ClusterIcon class, add the following code AFTER the click/clusterclick trigger:

    // EXISTING CODE (around line 143)
    google.maps.event.trigger(mc, "click", cClusterIcon.cluster_);
    google.maps.event.trigger(mc, "clusterclick", cClusterIcon.cluster_); // deprecated name
    
    // BEGIN MODIFICATION
    var zoom = mc.getMap().getZoom();
    // Trying to pull this dynamically made the more zoomed in clusters not render
    // when then kind of made this useless. -NNC @ BNB
    // var maxZoom = mc.getMaxZoom();
    var maxZoom = 15;
    // if we have reached the maxZoom and there is more than 1 marker in this cluster
    // use our onClick method to popup a list of options
    if (zoom >= maxZoom && cClusterIcon.cluster_.markers_.length > 1) {
        return mc.onClick(cClusterIcon);
    }
    // END MODIFICATION
    
  3. Then, in your initialize() function where you initialize the map and declare your MarkerClusterer object:

    markerCluster = new MarkerClusterer(map, markers);
    // onClick OVERRIDE
    markerCluster.onClick = function(clickedClusterIcon) { 
      return multiChoice(clickedClusterIcon.cluster_); 
    }
    

    Where multiChoice() is YOUR (yet to be written) function to popup an InfoWindow with a list of options to select from. Note that the markerClusterer object is passed to your function, because you will need this to determine how many markers there are in that cluster. For example:

    function multiChoice(clickedCluster) {
      if (clickedCluster.getMarkers().length > 1)
      {
        // var markers = clickedCluster.getMarkers();
        // do something creative!
        return false;
      }
      return true;
    };
    

Python3: ImportError: No module named '_ctypes' when using Value from module multiprocessing

None of the solution worked. You have to recompile your python again; once all the required packages were completely installed.

Follow this:

  1. Install required packages
  2. Run ./configure --enable-optimizations

https://gist.github.com/jerblack/798718c1910ccdd4ede92481229043be

.htaccess deny from all

This syntax has changed with the newer Apache HTTPd server, please see upgrade to apache 2.4 doc for full details.

2.2 configuration syntax was

Order deny,allow
Deny from all

2.4 configuration now is

Require all denied

Thus, this 2.2 syntax

order deny,allow
deny from all
allow from 127.0.0.1

Would ne now written

Require local

Node.js Best Practice Exception Handling

Following is a summarization and curation from many different sources on this topic including code example and quotes from selected blog posts. The complete list of best practices can be found here


Best practices of Node.JS error handling


Number1: Use promises for async error handling

TL;DR: Handling async errors in callback style is probably the fastest way to hell (a.k.a the pyramid of doom). The best gift you can give to your code is using instead a reputable promise library which provides much compact and familiar code syntax like try-catch

Otherwise: Node.JS callback style, function(err, response), is a promising way to un-maintainable code due to the mix of error handling with casual code, excessive nesting and awkward coding patterns

Code example - good

doWork()
.then(doWork)
.then(doError)
.then(doWork)
.catch(errorHandler)
.then(verify);

code example anti pattern – callback style error handling

getData(someParameter, function(err, result){
    if(err != null)
      //do something like calling the given callback function and pass the error
    getMoreData(a, function(err, result){
          if(err != null)
            //do something like calling the given callback function and pass the error
        getMoreData(b, function(c){ 
                getMoreData(d, function(e){ 
                    ...
                });
            });
        });
    });
});

Blog quote: "We have a problem with promises" (From the blog pouchdb, ranked 11 for the keywords "Node Promises")

"…And in fact, callbacks do something even more sinister: they deprive us of the stack, which is something we usually take for granted in programming languages. Writing code without a stack is a lot like driving a car without a brake pedal: you don’t realize how badly you need it, until you reach for it and it’s not there. The whole point of promises is to give us back the language fundamentals we lost when we went async: return, throw, and the stack. But you have to know how to use promises correctly in order to take advantage of them."


Number2: Use only the built-in Error object

TL;DR: It pretty common to see code that throws errors as string or as a custom type – this complicates the error handling logic and the interoperability between modules. Whether you reject a promise, throw exception or emit error – using Node.JS built-in Error object increases uniformity and prevents loss of error information

Otherwise: When executing some module, being uncertain which type of errors come in return – makes it much harder to reason about the coming exception and handle it. Even worth, using custom types to describe errors might lead to loss of critical error information like the stack trace!

Code example - doing it right

    //throwing an Error from typical function, whether sync or async
 if(!productToAdd)
 throw new Error("How can I add new product when no value provided?");

//'throwing' an Error from EventEmitter
const myEmitter = new MyEmitter();
myEmitter.emit('error', new Error('whoops!'));

//'throwing' an Error from a Promise
 return new promise(function (resolve, reject) {
 DAL.getProduct(productToAdd.id).then((existingProduct) =>{
 if(existingProduct != null)
 return reject(new Error("Why fooling us and trying to add an existing product?"));

code example anti pattern

//throwing a String lacks any stack trace information and other important properties
if(!productToAdd)
    throw ("How can I add new product when no value provided?");

Blog quote: "A string is not an error" (From the blog devthought, ranked 6 for the keywords “Node.JS error object”)

"…passing a string instead of an error results in reduced interoperability between modules. It breaks contracts with APIs that might be performing instanceof Error checks, or that want to know more about the error. Error objects, as we’ll see, have very interesting properties in modern JavaScript engines besides holding the message passed to the constructor.."


Number3: Distinguish operational vs programmer errors

TL;DR: Operations errors (e.g. API received an invalid input) refer to known cases where the error impact is fully understood and can be handled thoughtfully. On the other hand, programmer error (e.g. trying to read undefined variable) refers to unknown code failures that dictate to gracefully restart the application

Otherwise: You may always restart the application when an error appear, but why letting ~5000 online users down because of a minor and predicted error (operational error)? the opposite is also not ideal – keeping the application up when unknown issue (programmer error) occurred might lead unpredicted behavior. Differentiating the two allows acting tactfully and applying a balanced approach based on the given context

Code example - doing it right

    //throwing an Error from typical function, whether sync or async
 if(!productToAdd)
 throw new Error("How can I add new product when no value provided?");

//'throwing' an Error from EventEmitter
const myEmitter = new MyEmitter();
myEmitter.emit('error', new Error('whoops!'));

//'throwing' an Error from a Promise
 return new promise(function (resolve, reject) {
 DAL.getProduct(productToAdd.id).then((existingProduct) =>{
 if(existingProduct != null)
 return reject(new Error("Why fooling us and trying to add an existing product?"));

code example - marking an error as operational (trusted)

//marking an error object as operational 
var myError = new Error("How can I add new product when no value provided?");
myError.isOperational = true;

//or if you're using some centralized error factory (see other examples at the bullet "Use only the built-in Error object")
function appError(commonType, description, isOperational) {
    Error.call(this);
    Error.captureStackTrace(this);
    this.commonType = commonType;
    this.description = description;
    this.isOperational = isOperational;
};

throw new appError(errorManagement.commonErrors.InvalidInput, "Describe here what happened", true);

//error handling code within middleware
process.on('uncaughtException', function(error) {
    if(!error.isOperational)
        process.exit(1);
});

Blog Quote: "Otherwise you risk the state" (From the blog debugable, ranked 3 for the keywords "Node.JS uncaught exception")

"…By the very nature of how throw works in JavaScript, there is almost never any way to safely “pick up where you left off”, without leaking references, or creating some other sort of undefined brittle state. The safest way to respond to a thrown error is to shut down the process. Of course, in a normal web server, you might have many connections open, and it is not reasonable to abruptly shut those down because an error was triggered by someone else. The better approach is to send an error response to the request that triggered the error, while letting the others finish in their normal time, and stop listening for new requests in that worker"


Number4: Handle errors centrally, through but not within middleware

TL;DR: Error handling logic such as mail to admin and logging should be encapsulated in a dedicated and centralized object that all end-points (e.g. Express middleware, cron jobs, unit-testing) call when an error comes in.

Otherwise: Not handling errors within a single place will lead to code duplication and probably to errors that are handled improperly

Code example - a typical error flow

//DAL layer, we don't handle errors here
DB.addDocument(newCustomer, (error, result) => {
    if (error)
        throw new Error("Great error explanation comes here", other useful parameters)
});

//API route code, we catch both sync and async errors and forward to the middleware
try {
    customerService.addNew(req.body).then(function (result) {
        res.status(200).json(result);
    }).catch((error) => {
        next(error)
    });
}
catch (error) {
    next(error);
}

//Error handling middleware, we delegate the handling to the centrzlied error handler
app.use(function (err, req, res, next) {
    errorHandler.handleError(err).then((isOperationalError) => {
        if (!isOperationalError)
            next(err);
    });
});

Blog quote: "Sometimes lower levels can’t do anything useful except propagate the error to their caller" (From the blog Joyent, ranked 1 for the keywords “Node.JS error handling”)

"…You may end up handling the same error at several levels of the stack. This happens when lower levels can’t do anything useful except propagate the error to their caller, which propagates the error to its caller, and so on. Often, only the top-level caller knows what the appropriate response is, whether that’s to retry the operation, report an error to the user, or something else. But that doesn’t mean you should try to report all errors to a single top-level callback, because that callback itself can’t know in what context the error occurred"


Number5: Document API errors using Swagger

TL;DR: Let your API callers know which errors might come in return so they can handle these thoughtfully without crashing. This is usually done with REST API documentation frameworks like Swagger

Otherwise: An API client might decide to crash and restart only because he received back an error he couldn’t understand. Note: the caller of your API might be you (very typical in a microservices environment)

Blog quote: "You have to tell your callers what errors can happen" (From the blog Joyent, ranked 1 for the keywords “Node.JS logging”)

…We’ve talked about how to handle errors, but when you’re writing a new function, how do you deliver errors to the code that called your function? …If you don’t know what errors can happen or don’t know what they mean, then your program cannot be correct except by accident. So if you’re writing a new function, you have to tell your callers what errors can happen and what they mea


Number6: Shut the process gracefully when a stranger comes to town

TL;DR: When an unknown error occurs (a developer error, see best practice number #3)- there is uncertainty about the application healthiness. A common practice suggests restarting the process carefully using a ‘restarter’ tool like Forever and PM2

Otherwise: When an unfamiliar exception is caught, some object might be in a faulty state (e.g an event emitter which is used globally and not firing events anymore due to some internal failure) and all future requests might fail or behave crazily

Code example - deciding whether to crash

//deciding whether to crash when an uncaught exception arrives
//Assuming developers mark known operational errors with error.isOperational=true, read best practice #3
process.on('uncaughtException', function(error) {
 errorManagement.handler.handleError(error);
 if(!errorManagement.handler.isTrustedError(error))
 process.exit(1)
});


//centralized error handler encapsulates error-handling related logic 
function errorHandler(){
 this.handleError = function (error) {
 return logger.logError(err).then(sendMailToAdminIfCritical).then(saveInOpsQueueIfCritical).then(determineIfOperationalError);
 }

 this.isTrustedError = function(error)
 {
 return error.isOperational;
 }

Blog quote: "There are three schools of thoughts on error handling" (From the blog jsrecipes)

…There are primarily three schools of thoughts on error handling: 1. Let the application crash and restart it. 2. Handle all possible errors and never crash. 3. Balanced approach between the two


Number7: Use a mature logger to increase errors visibility

TL;DR: A set of mature logging tools like Winston, Bunyan or Log4J, will speed-up error discovery and understanding. So forget about console.log.

Otherwise: Skimming through console.logs or manually through messy text file without querying tools or a decent log viewer might keep you busy at work until late

Code example - Winston logger in action

//your centralized logger object
var logger = new winston.Logger({
 level: 'info',
 transports: [
 new (winston.transports.Console)(),
 new (winston.transports.File)({ filename: 'somefile.log' })
 ]
 });

//custom code somewhere using the logger
logger.log('info', 'Test Log Message with some parameter %s', 'some parameter', { anything: 'This is metadata' });

Blog quote: "Lets identify a few requirements (for a logger):" (From the blog strongblog)

…Lets identify a few requirements (for a logger): 1. Time stamp each log line. This one is pretty self explanatory – you should be able to tell when each log entry occured. 2. Logging format should be easily digestible by humans as well as machines. 3. Allows for multiple configurable destination streams. For example, you might be writing trace logs to one file but when an error is encountered, write to the same file, then into error file and send an email at the same time…


Number8: Discover errors and downtime using APM products

TL;DR: Monitoring and performance products (a.k.a APM) proactively gauge your codebase or API so they can auto-magically highlight errors, crashes and slow parts that you were missing

Otherwise: You might spend great effort on measuring API performance and downtimes, probably you’ll never be aware which are your slowest code parts under real world scenario and how these affects the UX

Blog quote: "APM products segments" (From the blog Yoni Goldberg)

"…APM products constitutes 3 major segments:1. Website or API monitoring – external services that constantly monitor uptime and performance via HTTP requests. Can be setup in few minutes. Following are few selected contenders: Pingdom, Uptime Robot, and New Relic 2. Code instrumentation – products family which require to embed an agent within the application to benefit feature slow code detection, exceptions statistics, performance monitoring and many more. Following are few selected contenders: New Relic, App Dynamics 3. Operational intelligence dashboard – these line of products are focused on facilitating the ops team with metrics and curated content that helps to easily stay on top of application performance. This is usually involves aggregating multiple sources of information (application logs, DB logs, servers log, etc) and upfront dashboard design work. Following are few selected contenders: Datadog, Splunk"


The above is a shortened version - see here more best practices and examples

XML shape drawable not rendering desired color

I had a similar problem and found that if you remove the size definition, it works for some reason.

Remove:

<size
    android:width="60dp"
    android:height="40dp" />

from the shape.

Let me know if this works!

How to encode text to base64 in python

Use the below code:

import base64

#Taking input through the terminal.
welcomeInput= raw_input("Enter 1 to convert String to Base64, 2 to convert Base64 to String: ") 

if(int(welcomeInput)==1 or int(welcomeInput)==2):
    #Code to Convert String to Base 64.
    if int(welcomeInput)==1:
        inputString= raw_input("Enter the String to be converted to Base64:") 
        base64Value = base64.b64encode(inputString.encode())
        print "Base64 Value = " + base64Value
    #Code to Convert Base 64 to String.
    elif int(welcomeInput)==2:
        inputString= raw_input("Enter the Base64 value to be converted to String:") 
        stringValue = base64.b64decode(inputString).decode('utf-8')
        print "Base64 Value = " + stringValue

else:
    print "Please enter a valid value."

Best Python IDE on Linux

I haven't played around with it much but eclipse/pydev feels nice.

How to delete files recursively from an S3 bucket

I just removed all files from my bucket by using PowerShell:

Get-S3Object -BucketName YOUR_BUCKET | % { Remove-S3Object -BucketName YOUR_BUCKET -Key $_.Key -Force:$true }

Add Twitter Bootstrap icon to Input box

For bootstrap 4

        <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css" integrity="sha384-9gVQ4dYFwwWSjIDZnLEWnxCjeSWFphJiwGPXr1jddIhOegiu1FwO5qRGvFXOdJZ4" crossorigin="anonymous">

            <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
            <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.0/umd/popper.min.js" integrity="sha384-cs/chFZiN24E4KMATLdqdvsezGxaGsi4hLGOzlXwp5UZB1LY//20VyM2taTB4QvJ" crossorigin="anonymous"></script>
            <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js" integrity="sha384-uefMccjFJAIv6A+rW+L4AHf99KvxDjWSu1z9VI8SKNVmz4sk7buKt/6v9KI65qnm" crossorigin="anonymous"></script>
        <link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">
        <form class="form-inline my-2 my-lg-0">
                        <div class="input-group">
                            <input class="form-control" type="search" placeholder="Search">
                            <div class="input-group-append">
                                <div class="input-group-text"><i class="fa fa-search"></i></div>
                            </div>
                        </div>
                    </form>

Demo

How to do SELECT MAX in Django?

I've tested this for my project, it finds the max/min in O(n) time:

from django.db.models import Max

# Find the maximum value of the rating and then get the record with that rating. 
# Notice the double underscores in rating__max
max_rating = App.objects.aggregate(Max('rating'))['rating__max']
return App.objects.get(rating=max_rating)

This is guaranteed to get you one of the maximum elements efficiently, rather than sorting the whole table and getting the top (around O(n*logn)).

Jquery Smooth Scroll To DIV - Using ID value from Link

You can do this:

$('.searchbychar').click(function () {
    var divID = '#' + this.id;
    $('html, body').animate({
        scrollTop: $(divID).offset().top
    }, 2000);
});

F.Y.I.

  • You need to prefix a class name with a . (dot) like in your first line of code.
  • $( 'searchbychar' ).click(function() {
  • Also, your code $('.searchbychar').attr('id') will return a string ID not a jQuery object. Hence, you can not apply .offset() method to it.

AngularJs: How to set radio button checked based on model

Just do something like this,<input type="radio" ng-disabled="loading" name="dateRange" ng-model="filter.DateRange" value="1" ng-checked="(filter.DateRange == 1)"/>

How to remove only 0 (Zero) values from column in excel 2010

The easiest way of all is as follows: Click the office button (top left) Click "Excel Options" Click "Advanced" Scroll down to "Display options for this worksheet" Untick the box "Show a zero in cells that have zero value" Click "okay"

That's all there is to it.

:)

Convert Mercurial project to Git

You can try using fast-export:

cd ~
git clone https://github.com/frej/fast-export.git
git init git_repo
cd git_repo
~/fast-export/hg-fast-export.sh -r /path/to/old/mercurial_repo
git checkout HEAD

Also have a look at this SO question.


If you're using Mercurial version below 4.6, adrihanu got your back:

As he stated in his comment: "In case you use Mercurial < 4.6 and you got "revsymbol not found" error. You need to update your Mercurial or downgrade fast-export by running git checkout tags/v180317 inside ~/fast-export directory.".

How to write text on a image in windows using python opencv2

You can use cv2.FONT_HERSHEY_SIMPLEX instead of cv2.CV_FONT_HERSHEY_SIMPLEX in current opencv version

Opening port 80 EC2 Amazon web services

  1. Check what security group you are using for your instance. See value of Security Groups column in row of your instance. It's important - I changed rules for default group, but my instance was under quickstart-1 group when I had similar issue.
  2. Go to Security Groups tab, go to Inbound tab, select HTTP in Create a new rule combo-box, leave 0.0.0.0/0 in source field and click Add Rule, then Apply rule changes.

How to split a string at the first `/` (slash) and surround part of it in a `<span>`?

try

_x000D_
_x000D_
date.innerHTML= date.innerHTML.replace(/^(..)\//,'<span>$1</span></br>')
_x000D_
<div id="date">23/05/2013</div>
_x000D_
_x000D_
_x000D_

Definition of "downstream" and "upstream"

That's a bit of informal terminology.

As far as Git is concerned, every other repository is just a remote.

Generally speaking, upstream is where you cloned from (the origin). Downstream is any project that integrates your work with other works.

The terms are not restricted to Git repositories.

For instance, Ubuntu is a Debian derivative, so Debian is upstream for Ubuntu.

Android: How to change the ActionBar "Home" Icon to be something other than the app icon?

The ActionBar will use the android:logo attribute of your manifest, if one is provided. That lets you use separate drawable resources for the icon (Launcher) and the logo (ActionBar, among other things).

Downloading images with node.js

Building on the above, if anyone needs to handle errors in the write/read streams, I used this version. Note the stream.read() in case of a write error, it's required so we can finish reading and trigger close on the read stream.

var download = function(uri, filename, callback){
  request.head(uri, function(err, res, body){
    if (err) callback(err, filename);
    else {
        var stream = request(uri);
        stream.pipe(
            fs.createWriteStream(filename)
                .on('error', function(err){
                    callback(error, filename);
                    stream.read();
                })
            )
        .on('close', function() {
            callback(null, filename);
        });
    }
  });
};

How can I truncate a double to only two decimal places in Java?

This worked for me:

double input = 104.8695412  //For example

long roundedInt = Math.round(input * 100);
double result = (double) roundedInt/100;

//result == 104.87

I personally like this version because it actually performs the rounding numerically, rather than by converting it to a String (or similar) and then formatting it.

Writing numerical values on the plot with Matplotlib

Use pyplot.text() (import matplotlib.pyplot as plt)

import matplotlib.pyplot as plt

x=[1,2,3]
y=[9,8,7]

plt.plot(x,y)
for a,b in zip(x, y): 
    plt.text(a, b, str(b))
plt.show()

convert month from name to number

$monthname = date("F", strtotime($month));

F means full month name

Why do you need to put #!/bin/bash at the beginning of a script file?

To be more precise the shebang #!, when it is the first two bytes of an executable (x mode) file, is interpreted by the execve(2) system call (which execute programs). But POSIX specification for execve don't mention the shebang.

It must be followed by a file path of an interpreter executable (which BTW could even be relative, but most often is absolute).

A nice trick (or perhaps not so nice one) to find an interpreter (e.g. python) in the user's $PATH is to use the env program (always at /usr/bin/env on all Linux) like e.g.

 #!/usr/bin/env python

Any ELF executable can be an interpreter. You could even use #!/bin/cat or #!/bin/true if you wanted to! (but that would be often useless)

On duplicate key ignore?

Mysql has this handy UPDATE INTO command ;)

edit Looks like they renamed it to REPLACE

REPLACE works exactly like INSERT, except that if an old row in the table has the same value as a new row for a PRIMARY KEY or a UNIQUE index, the old row is deleted before the new row is inserted

How do you save/store objects in SharedPreferences on Android?

Store data in SharedPreference

SharedPreferences mprefs = getSharedPreferences(AppConstant.PREFS_NAME, MODE_PRIVATE)
mprefs.edit().putString(AppConstant.USER_ID, resUserID).apply();

Saving a Numpy array as an image

An answer using PIL (just in case it's useful).

given a numpy array "A":

from PIL import Image
im = Image.fromarray(A)
im.save("your_file.jpeg")

you can replace "jpeg" with almost any format you want. More details about the formats here

How do I 'overwrite', rather than 'merge', a branch on another branch in Git?

Other answers looked incomplete.
I have tried below in full, and it worked fine.

NOTE:
1. Make a copy of your repository before you try below, to be on safe side.

Details:
1. All development happens in dev branch
2. qa branch is just the same copy of dev
3. Time to time, dev code needs to be moved/overwrite to qa branch

so we need to overwrite qa branch, from dev branch

Part 1:
With below commands, old qa has been updated to newer dev:

git checkout dev
git merge -s ours qa
git checkout qa
git merge dev
git push

Automatic comment for last push gives below:

// Output:
//  *<MYNAME> Merge branch 'qa' into dev,*  

This comment looks reverse, because above sequence also looks reverse

Part 2:

Below are unexpected, new local commits in dev, the unnecessary ones
so, we need to throw away, and make dev untouched.

git checkout dev

// Output:
//  Switched to branch 'dev'  
//  Your branch is ahead of 'origin/dev' by 15 commits.  
//  (use "git push" to publish your local commits)


git reset --hard origin/dev  

//  Now we threw away the unexpected commits

Part 3:
Verify everything is as expected:

git status  

// Output:
//  *On branch dev  
//  Your branch is up-to-date with 'origin/dev'.  
//  nothing to commit, working tree clean*  

That's all.
1. old qa is now overwritten by new dev branch code
2. local is clean (remote origin/dev is untouched)

Getting RAW Soap Data from a Web Reference Client running in ASP.net

I made following changes in web.config to get the SOAP (Request/Response) Envelope. This will output all of the raw SOAP information to the file trace.log.

<system.diagnostics>
  <trace autoflush="true"/>
  <sources>
    <source name="System.Net" maxdatasize="1024">
      <listeners>
        <add name="TraceFile"/>
      </listeners>
    </source>
    <source name="System.Net.Sockets" maxdatasize="1024">
      <listeners>
        <add name="TraceFile"/>
      </listeners>
    </source>
  </sources>
  <sharedListeners>
    <add name="TraceFile" type="System.Diagnostics.TextWriterTraceListener"
      initializeData="trace.log"/>
  </sharedListeners>
  <switches>
    <add name="System.Net" value="Verbose"/>
    <add name="System.Net.Sockets" value="Verbose"/>
  </switches>
</system.diagnostics>

Image resolution for new iPhone 6 and 6+, @3x support added?

I have tested by making a sample project and all simulators seem to use @3x images , this is confusing.

Create different versions of an image in your asset catalog such that the image itself tells you what version it is:

enter image description here

Now run the app on each simulator in turn. You will see that the 3x image is used only on the iPhone 6 Plus.

The same thing is true if the images are drawn from the app bundle using their names (e.g. one.png, [email protected], and [email protected]) by calling imageNamed: and assigning into an image view.

(However, there's a difference if you assign the image to an image view in Interface Builder - the 2x version is ignored on double-resolution devices. This is presumably a bug, apparently a bug in pathForResource:ofType:.)

Access denied for user 'root'@'localhost' (using password: Yes) after password reset LINUX

You can try this solution :-

To have mysql asking you for a password, you also need to specify the -p-option: (try with space between -p and password)

mysql -u root -p new_password

MySQLl access denied

In the Second link someone has commented the same problem.

How to tell whether a point is to the right or left side of a line

I implemented this in java and ran a unit test (source below). None of the above solutions work. This code passes the unit test. If anyone finds a unit test that does not pass, please let me know.

Code: NOTE: nearlyEqual(double,double) returns true if the two numbers are very close.

/*
 * @return integer code for which side of the line ab c is on.  1 means
 * left turn, -1 means right turn.  Returns
 * 0 if all three are on a line
 */
public static int findSide(
        double ax, double ay, 
        double bx, double by,
        double cx, double cy) {
    if (nearlyEqual(bx-ax,0)) { // vertical line
        if (cx < bx) {
            return by > ay ? 1 : -1;
        }
        if (cx > bx) {
            return by > ay ? -1 : 1;
        } 
        return 0;
    }
    if (nearlyEqual(by-ay,0)) { // horizontal line
        if (cy < by) {
            return bx > ax ? -1 : 1;
        }
        if (cy > by) {
            return bx > ax ? 1 : -1;
        } 
        return 0;
    }
    double slope = (by - ay) / (bx - ax);
    double yIntercept = ay - ax * slope;
    double cSolution = (slope*cx) + yIntercept;
    if (slope != 0) {
        if (cy > cSolution) {
            return bx > ax ? 1 : -1;
        }
        if (cy < cSolution) {
            return bx > ax ? -1 : 1;
        }
        return 0;
    }
    return 0;
}

Here's the unit test:

@Test public void testFindSide() {
    assertTrue("1", 1 == Utility.findSide(1, 0, 0, 0, -1, -1));
    assertTrue("1.1", 1 == Utility.findSide(25, 0, 0, 0, -1, -14));
    assertTrue("1.2", 1 == Utility.findSide(25, 20, 0, 20, -1, 6));
    assertTrue("1.3", 1 == Utility.findSide(24, 20, -1, 20, -2, 6));

    assertTrue("-1", -1 == Utility.findSide(1, 0, 0, 0, 1, 1));
    assertTrue("-1.1", -1 == Utility.findSide(12, 0, 0, 0, 2, 1));
    assertTrue("-1.2", -1 == Utility.findSide(-25, 0, 0, 0, -1, -14));
    assertTrue("-1.3", -1 == Utility.findSide(1, 0.5, 0, 0, 1, 1));

    assertTrue("2.1", -1 == Utility.findSide(0,5, 1,10, 10,20));
    assertTrue("2.2", 1 == Utility.findSide(0,9.1, 1,10, 10,20));
    assertTrue("2.3", -1 == Utility.findSide(0,5, 1,10, 20,10));
    assertTrue("2.4", -1 == Utility.findSide(0,9.1, 1,10, 20,10));

    assertTrue("vertical 1", 1 == Utility.findSide(1,1, 1,10, 0,0));
    assertTrue("vertical 2", -1 == Utility.findSide(1,10, 1,1, 0,0));
    assertTrue("vertical 3", -1 == Utility.findSide(1,1, 1,10, 5,0));
    assertTrue("vertical 3", 1 == Utility.findSide(1,10, 1,1, 5,0));

    assertTrue("horizontal 1", 1 == Utility.findSide(1,-1, 10,-1, 0,0));
    assertTrue("horizontal 2", -1 == Utility.findSide(10,-1, 1,-1, 0,0));
    assertTrue("horizontal 3", -1 == Utility.findSide(1,-1, 10,-1, 0,-9));
    assertTrue("horizontal 4", 1 == Utility.findSide(10,-1, 1,-1, 0,-9));

    assertTrue("positive slope 1", 1 == Utility.findSide(0,0, 10,10, 1,2));
    assertTrue("positive slope 2", -1 == Utility.findSide(10,10, 0,0, 1,2));
    assertTrue("positive slope 3", -1 == Utility.findSide(0,0, 10,10, 1,0));
    assertTrue("positive slope 4", 1 == Utility.findSide(10,10, 0,0, 1,0));

    assertTrue("negative slope 1", -1 == Utility.findSide(0,0, -10,10, 1,2));
    assertTrue("negative slope 2", -1 == Utility.findSide(0,0, -10,10, 1,2));
    assertTrue("negative slope 3", 1 == Utility.findSide(0,0, -10,10, -1,-2));
    assertTrue("negative slope 4", -1 == Utility.findSide(-10,10, 0,0, -1,-2));

    assertTrue("0", 0 == Utility.findSide(1, 0, 0, 0, -1, 0));
    assertTrue("1", 0 == Utility.findSide(0,0, 0, 0, 0, 0));
    assertTrue("2", 0 == Utility.findSide(0,0, 0,1, 0,2));
    assertTrue("3", 0 == Utility.findSide(0,0, 2,0, 1,0));
    assertTrue("4", 0 == Utility.findSide(1, -2, 0, 0, -1, 2));
}

How can I get all sequences in an Oracle database?

select sequence_owner, sequence_name from dba_sequences;


DBA_SEQUENCES -- all sequences that exist 
ALL_SEQUENCES  -- all sequences that you have permission to see 
USER_SEQUENCES  -- all sequences that you own

Note that since you are, by definition, the owner of all the sequences returned from USER_SEQUENCES, there is no SEQUENCE_OWNER column in USER_SEQUENCES.

how do I change text in a label with swift?

swift solution

yourlabel.text = yourvariable

or self is use for when you are in async {brackets} or in some Extension

DispatchQueue.main.async{
    self.yourlabel.text = "typestring"
}

jQuery validate Uncaught TypeError: Cannot read property 'nodeName' of null

Extract from the oficial docs:

Requires that the parent form is validated, that is, $( "form" ).validate() is called first

more about... rules

jQuery Mobile - back button

You can try this script in the header of HTML code:

<script>
   $.extend(  $.mobile , {
   ajaxEnabled: false,
   hashListeningEnabled: false
   });
</script>

How do I check if a SQL Server text column is empty?

DECLARE @temp as nvarchar(20)

SET @temp = NULL
--SET @temp = ''
--SET @temp = 'Test'

SELECT IIF(ISNULL(@temp,'')='','[Empty]',@temp)

How to get image height and width using java?

This is a rewrite of the great post by @Kay, which throws IOException and provides an early exit:

/**
 * Gets image dimensions for given file 
 * @param imgFile image file
 * @return dimensions of image
 * @throws IOException if the file is not a known image
 */
public static Dimension getImageDimension(File imgFile) throws IOException {
  int pos = imgFile.getName().lastIndexOf(".");
  if (pos == -1)
    throw new IOException("No extension for file: " + imgFile.getAbsolutePath());
  String suffix = imgFile.getName().substring(pos + 1);
  Iterator<ImageReader> iter = ImageIO.getImageReadersBySuffix(suffix);
  while(iter.hasNext()) {
    ImageReader reader = iter.next();
    try {
      ImageInputStream stream = new FileImageInputStream(imgFile);
      reader.setInput(stream);
      int width = reader.getWidth(reader.getMinIndex());
      int height = reader.getHeight(reader.getMinIndex());
      return new Dimension(width, height);
    } catch (IOException e) {
      log.warn("Error reading: " + imgFile.getAbsolutePath(), e);
    } finally {
      reader.dispose();
    }
  }

  throw new IOException("Not a known image file: " + imgFile.getAbsolutePath());
}

I guess my rep is not high enough for my input to be considered worthy as a reply.

How to implement and do OCR in a C# project?

If anyone is looking into this, I've been trying different options and the following approach yields very good results. The following are the steps to get a working example:

  1. Add .NET Wrapper for tesseract to your project. It can be added via NuGet package Install-Package Tesseract(https://github.com/charlesw/tesseract).
  2. Go to the Downloads section of the official Tesseract project (https://code.google.com/p/tesseract-ocr/ EDIT: It's now located here: https://github.com/tesseract-ocr/langdata).
  3. Download the preferred language data, example: tesseract-ocr-3.02.eng.tar.gz English language data for Tesseract 3.02.
  4. Create tessdata directory in your project and place the language data files in it.
  5. Go to Properties of the newly added files and set them to copy on build.
  6. Add a reference to System.Drawing.
  7. From .NET Wrapper repository, in the Samples directory copy the sample phototest.tif file into your project directory and set it to copy on build.
  8. Create the following two files in your project (just to get started):

Program.cs

using System;
using Tesseract;
using System.Diagnostics;

namespace ConsoleApplication
{
    class Program
    {
        public static void Main(string[] args)
        {
            var testImagePath = "./phototest.tif";
            if (args.Length > 0)
            {
                testImagePath = args[0];
            }

            try
            {
                var logger = new FormattedConsoleLogger();
                var resultPrinter = new ResultPrinter(logger);
                using (var engine = new TesseractEngine(@"./tessdata", "eng", EngineMode.Default))
                {
                    using (var img = Pix.LoadFromFile(testImagePath))
                    {
                        using (logger.Begin("Process image"))
                        {
                            var i = 1;
                            using (var page = engine.Process(img))
                            {
                                var text = page.GetText();
                                logger.Log("Text: {0}", text);
                                logger.Log("Mean confidence: {0}", page.GetMeanConfidence());

                                using (var iter = page.GetIterator())
                                {
                                    iter.Begin();
                                    do
                                    {
                                        if (i % 2 == 0)
                                        {
                                            using (logger.Begin("Line {0}", i))
                                            {
                                                do
                                                {
                                                    using (logger.Begin("Word Iteration"))
                                                    {
                                                        if (iter.IsAtBeginningOf(PageIteratorLevel.Block))
                                                        {
                                                            logger.Log("New block");
                                                        }
                                                        if (iter.IsAtBeginningOf(PageIteratorLevel.Para))
                                                        {
                                                            logger.Log("New paragraph");
                                                        }
                                                        if (iter.IsAtBeginningOf(PageIteratorLevel.TextLine))
                                                        {
                                                            logger.Log("New line");
                                                        }
                                                        logger.Log("word: " + iter.GetText(PageIteratorLevel.Word));
                                                    }
                                                } while (iter.Next(PageIteratorLevel.TextLine, PageIteratorLevel.Word));
                                            }
                                        }
                                        i++;
                                    } while (iter.Next(PageIteratorLevel.Para, PageIteratorLevel.TextLine));
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception e)
            {
                Trace.TraceError(e.ToString());
                Console.WriteLine("Unexpected Error: " + e.Message);
                Console.WriteLine("Details: ");
                Console.WriteLine(e.ToString());
            }
            Console.Write("Press any key to continue . . . ");
            Console.ReadKey(true);
        }



        private class ResultPrinter
        {
            readonly FormattedConsoleLogger logger;

            public ResultPrinter(FormattedConsoleLogger logger)
            {
                this.logger = logger;
            }

            public void Print(ResultIterator iter)
            {
                logger.Log("Is beginning of block: {0}", iter.IsAtBeginningOf(PageIteratorLevel.Block));
                logger.Log("Is beginning of para: {0}", iter.IsAtBeginningOf(PageIteratorLevel.Para));
                logger.Log("Is beginning of text line: {0}", iter.IsAtBeginningOf(PageIteratorLevel.TextLine));
                logger.Log("Is beginning of word: {0}", iter.IsAtBeginningOf(PageIteratorLevel.Word));
                logger.Log("Is beginning of symbol: {0}", iter.IsAtBeginningOf(PageIteratorLevel.Symbol));

                logger.Log("Block text: \"{0}\"", iter.GetText(PageIteratorLevel.Block));
                logger.Log("Para text: \"{0}\"", iter.GetText(PageIteratorLevel.Para));
                logger.Log("TextLine text: \"{0}\"", iter.GetText(PageIteratorLevel.TextLine));
                logger.Log("Word text: \"{0}\"", iter.GetText(PageIteratorLevel.Word));
                logger.Log("Symbol text: \"{0}\"", iter.GetText(PageIteratorLevel.Symbol));
            }
        }
    }
}

FormattedConsoleLogger.cs

using System;
using System.Collections.Generic;
using System.Text;
using Tesseract;

namespace ConsoleApplication
{
    public class FormattedConsoleLogger
    {
        const string Tab = "    ";
        private class Scope : DisposableBase
        {
            private int indentLevel;
            private string indent;
            private FormattedConsoleLogger container;

            public Scope(FormattedConsoleLogger container, int indentLevel)
            {
                this.container = container;
                this.indentLevel = indentLevel;
                StringBuilder indent = new StringBuilder();
                for (int i = 0; i < indentLevel; i++)
                {
                    indent.Append(Tab);
                }
                this.indent = indent.ToString();
            }

            public void Log(string format, object[] args)
            {
                var message = String.Format(format, args);
                StringBuilder indentedMessage = new StringBuilder(message.Length + indent.Length * 10);
                int i = 0;
                bool isNewLine = true;
                while (i < message.Length)
                {
                    if (message.Length > i && message[i] == '\r' && message[i + 1] == '\n')
                    {
                        indentedMessage.AppendLine();
                        isNewLine = true;
                        i += 2;
                    }
                    else if (message[i] == '\r' || message[i] == '\n')
                    {
                        indentedMessage.AppendLine();
                        isNewLine = true;
                        i++;
                    }
                    else
                    {
                        if (isNewLine)
                        {
                            indentedMessage.Append(indent);
                            isNewLine = false;
                        }
                        indentedMessage.Append(message[i]);
                        i++;
                    }
                }

                Console.WriteLine(indentedMessage.ToString());

            }

            public Scope Begin()
            {
                return new Scope(container, indentLevel + 1);
            }

            protected override void Dispose(bool disposing)
            {
                if (disposing)
                {
                    var scope = container.scopes.Pop();
                    if (scope != this)
                    {
                        throw new InvalidOperationException("Format scope removed out of order.");
                    }
                }
            }
        }

        private Stack<Scope> scopes = new Stack<Scope>();

        public IDisposable Begin(string title = "", params object[] args)
        {
            Log(title, args);
            Scope scope;
            if (scopes.Count == 0)
            {
                scope = new Scope(this, 1);
            }
            else
            {
                scope = ActiveScope.Begin();
            }
            scopes.Push(scope);
            return scope;
        }

        public void Log(string format, params object[] args)
        {
            if (scopes.Count > 0)
            {
                ActiveScope.Log(format, args);
            }
            else
            {
                Console.WriteLine(String.Format(format, args));
            }
        }

        private Scope ActiveScope
        {
            get
            {
                var top = scopes.Peek();
                if (top == null) throw new InvalidOperationException("No current scope");
                return top;
            }
        }
    }
}

How can I convert string date to NSDate?

import Foundation

let now : String = "2014-07-16 03:03:34 PDT"
var date : NSDate
var dateFormatter : NSDateFormatter

date = dateFormatter.dateFromString(now)

date // $R6: __NSDate = 2014-07-16 03:03:34 PDT

https://developer.apple.com/library/prerelease/mac/documentation/Cocoa/Reference/Foundation/Classes/NSDateFormatter_Class/index.html#//apple_ref/doc/uid/20000447-SW32

Android, Java: HTTP POST Request

Here's an example previously found at androidsnippets.com (the site is currently not maintained anymore).

// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.yoursite.com/script.php");

try {
    // Add your data
    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
    nameValuePairs.add(new BasicNameValuePair("id", "12345"));
    nameValuePairs.add(new BasicNameValuePair("stringdata", "AndDev is Cool!"));
    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

    // Execute HTTP Post Request
    HttpResponse response = httpclient.execute(httppost);

} catch (ClientProtocolException e) {
    // TODO Auto-generated catch block
} catch (IOException e) {
    // TODO Auto-generated catch block
}

So, you can add your parameters as BasicNameValuePair.

An alternative is to use (Http)URLConnection. See also Using java.net.URLConnection to fire and handle HTTP requests. This is actually the preferred method in newer Android versions (Gingerbread+). See also this blog, this developer doc and Android's HttpURLConnection javadoc.

How to post raw body data with curl?

curl's --data will by default send Content-Type: application/x-www-form-urlencoded in the request header. However, when using Postman's raw body mode, Postman sends Content-Type: text/plain in the request header.

So to achieve the same thing as Postman, specify -H "Content-Type: text/plain" for curl:

curl -X POST -H "Content-Type: text/plain" --data "this is raw data" http://78.41.xx.xx:7778/

Note that if you want to watch the full request sent by Postman, you can enable debugging for packed app. Check this link for all instructions. Then you can inspect the app (right-click in Postman) and view all requests sent from Postman in the network tab :

enter image description here

How to use Morgan logger?

var express = require('express');

var fs = require('fs');

var morgan = require('morgan')

var app = express();

// create a write stream (in append mode)
var accessLogStream = fs.createWriteStream(__dirname + '/access.log',{flags: 'a'});


// setup the logger
app.use(morgan('combined', {stream: accessLogStream}))


app.get('/', function (req, res) {
  res.send('hello, world!')
});

example nodejs + express + morgan

How to manually send HTTP POST requests from Firefox or Chrome browser?

May not be directly related to browsers but fiddler is another good software.

Fiddler web debugger

How to filter multiple values (OR operation) in angularJS

Creating a custom filter might be overkill here, you can just pass in a custom comparator, if you have the multiples values like:

$scope.selectedGenres = "Action, Drama"; 

$scope.containsComparator = function(expected, actual){  
  return actual.indexOf(expected) > -1;
};

then in the filter:

filter:{name:selectedGenres}:containsComparator

Dynamically changing font size of UILabel

minimumFontSize has been deprecated with iOS 6. You can use minimumScaleFactor.

yourLabel.adjustsFontSizeToFitWidth=YES;
yourLabel.minimumScaleFactor=0.5;

This will take care of your font size according width of label and text.

Insert data through ajax into mysql database

Try this:

  $(document).on('click','#save',function(e) {
  var data = $("#form-search").serialize();
  $.ajax({
         data: data,
         type: "post",
         url: "insertmail.php",
         success: function(data){
              alert("Data Save: " + data);
         }
});
 });

and in insertmail.php:

<?php 
if(isset($_REQUEST))
{
        mysql_connect("localhost","root","");
mysql_select_db("eciticket_db");
error_reporting(E_ALL && ~E_NOTICE);

$email=$_POST['email'];
$sql="INSERT INTO newsletter_email(email) VALUES ('$email')";
$result=mysql_query($sql);
if($result){
echo "You have been successfully subscribed.";
}
}
?>

Don't use mysql_ it's deprecated.

another method:

Actually if your problem is null value inserted into the database then try this and here no need of ajax.

<?php
if($_POST['email']!="")
{
    mysql_connect("localhost","root","");
    mysql_select_db("eciticket_db");
    error_reporting(E_ALL && ~E_NOTICE);
    $email=$_POST['email'];
    $sql="INSERT INTO newsletter_email(email) VALUES ('$email')";
    $result=mysql_query($sql);
    if($result){
    //echo "You have been successfully subscribed.";
              setcookie("msg","You have been successfully subscribed.",time()+5,"/");
              header("location:yourphppage.php");
    }
     if(!$sql)
    die(mysql_error());
    mysql_close();
}
?>
    <?php if(isset($_COOKIE['msg'])){?>
       <span><?php echo $_COOKIE['msg'];setcookie("msg","",time()-5,"/");?></span> 
    <?php }?>
<form id="form-search" method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">
    <span><span class="style2">Enter you email here</span>:</span>
    <input name="email" type="email" id="email" required/>
    <input type="submit" value="subscribe" class="submit"/>
</form>

git submodule tracking latest

Edit (2020.12.28): GitHub change default master branch to main branch since October 2020. See https://github.com/github/renaming


Update March 2013

Git 1.8.2 added the possibility to track branches.

"git submodule" started learning a new mode to integrate with the tip of the remote branch (as opposed to integrating with the commit recorded in the superproject's gitlink).

# add submodule to track master branch
git submodule add -b master [URL to Git repo];

# update your submodule
git submodule update --remote 

If you had a submodule already present you now wish would track a branch, see "how to make an existing submodule track a branch".

Also see Vogella's tutorial on submodules for general information on submodules.

Note:

git submodule add -b . [URL to Git repo];
                    ^^^

See git submodule man page:

A special value of . is used to indicate that the name of the branch in the submodule should be the same name as the current branch in the current repository.


See commit b928922727d6691a3bdc28160f93f25712c565f6:

submodule add: If --branch is given, record it in .gitmodules

This allows you to easily record a submodule.<name>.branch option in .gitmodules when you add a new submodule. With this patch,

$ git submodule add -b <branch> <repository> [<path>]
$ git config -f .gitmodules submodule.<path>.branch <branch>

reduces to

$ git submodule add -b <branch> <repository> [<path>]

This means that future calls to

$ git submodule update --remote ...

will get updates from the same branch that you used to initialize the submodule, which is usually what you want.

Signed-off-by: W. Trevor King [email protected]


Original answer (February 2012):

A submodule is a single commit referenced by a parent repo.
Since it is a Git repo on its own, the "history of all commits" is accessible through a git log within that submodule.

So for a parent to track automatically the latest commit of a given branch of a submodule, it would need to:

  • cd in the submodule
  • git fetch/pull to make sure it has the latest commits on the right branch
  • cd back in the parent repo
  • add and commit in order to record the new commit of the submodule.

gitslave (that you already looked at) seems to be the best fit, including for the commit operation.

It is a little annoying to make changes to the submodule due to the requirement to check out onto the correct submodule branch, make the change, commit, and then go into the superproject and commit the commit (or at least record the new location of the submodule).

Other alternatives are detailed here.

LOAD DATA INFILE Error Code : 13

I have experienced same problem and applied the solutions above.

First of all my test environment are as follows

  • Ubuntu 14.04.3 64bit
  • mysql Ver 14.14 Distrib 5.5.47, for debian-linux-gnu (x86_64) using readline 6.3 (installed by just 'sudo apt-get install ...' command)

My testing results are

i) AppArmor solution only work for /tmp cases.

ii) Following solution works without AppArmor solution. I would like to appreciate Avnish Mehta for his answer.

$ mysql -u root -p --in-file=1
...
mysql> LOAD DATA LOCAL INFILE '/home/hongsoog/study/mysql/member.dat'
    -> INTO TABLE member_table;

Important three points are

  • start mysql client with --in-file=1 option
  • use LOAD DATA LOCAL INFILE instead of LOAD DATA INFILE
  • check all path element have world read permission from the / to data file path. For example, following subpath should be world readable or mysql group readable if INFILE is targeting for '/home/hongsoog/study/mysql/memer.dat'

    • /home
    • /home/hongsoog
    • /home/hongsoog/study/mysql
    • /home/hongsoog/study/mysql/member.data

When you start mysql client WITHOUT "--in-file=1" option and use

LOAD DATA LOCAL INFILE ...
, you will get

ERROR 1148 (42000): The used command is not allowed with this MySQL version


In summary, "--in-file=1" option in mysql client command and "LOAD DATA LOCAL INFILE ..." should go hand in hand.

Hope to helpful to anyone.

jQuery override default validation error message display (Css) Popup/Tooltip like

If you could provide some reason as to why you need to replace the label with a div, that would certainly help...

Also, could you paste a sample that'd be helpful ( http://dpaste.com/ or http://pastebin.com/)

java.lang.ClassNotFoundException: sun.jdbc.odbc.JdbcOdbcDriver Exception occurring. Why?

For Java 7 you can simply omit the Class.forName() statement as it is not really required.

For Java 8 you cannot use the JDBC-ODBC Bridge because it has been removed. You will need to use something like UCanAccess instead. For more information, see

Manipulating an Access database from Java without ODBC

Using routes in Express-js

So, after I created my question, I got this related list on the right with a similar issue: Organize routes in Node.js.

The answer in that post linked to the Express repo on GitHub and suggests to look at the 'route-separation' example.

This helped me change my code, and I now have it working. - Thanks for your comments.

My implementation ended up looking like this;

I require my routes in the app.js:

var express = require('express')
  , site = require('./site')
  , wiki = require('./wiki');

And I add my routes like this:

app.get('/', site.index);
app.get('/wiki/:id', wiki.show);
app.get('/wiki/:id/edit', wiki.edit);

I have two files called wiki.js and site.js in the root of my app, containing this:

exports.edit = function(req, res) {

    var wiki_entry = req.params.id;

    res.render('wiki/edit', {
        title: 'Editing Wiki',
        wiki: wiki_entry
    })
}

SQL Bulk Insert with FIRSTROW parameter skips the following line

Given how mangled some data can look after BCP importing into SQL Server from non-SQL data sources, I'd suggest doing all the BCP import into some scratch tables first.

For example

truncate table Address_Import_tbl

BULK INSERT dbo.Address_Import_tbl FROM 'E:\external\SomeDataSource\Address.csv' WITH ( FIELDTERMINATOR = '|', ROWTERMINATOR = '\n', MAXERRORS = 10 )

Make sure all the columns in Address_Import_tbl are nvarchar(), to make it as agnostic as possible, and avoid type conversion errors.

Then apply whatever fixes you need to Address_Import_tbl. Like deleting the unwanted header.

Then run a INSERT SELECT query, to copy from Address_Import_tbl to Address_tbl, along with any datatype conversions you need. For example, to cast imported dates to SQL DATETIME.

Set Response Status Code

I don't think you're setting the header correctly, try this:

header('HTTP/1.0 401 Unauthorized');

Find out where MySQL is installed on Mac OS X

To check MySQL version of MAMP , use the following command in Terminal:

/Applications/MAMP/Library/bin/mysql --version

Assume you have started MAMP .

Example output:

./mysql  Ver 14.14 Distrib 5.1.44, for apple-darwin8.11.1 (i386) using  EditLine wrapper

UPDATE: Moreover, if you want to find where does mysql installed in system, use the following command:

type -a mysql

type -a is an equivalent of tclsh built-in command where in OS X bash shell. If MySQL is found, it will show :

mysql is /usr/bin/mysql

If not found, it will show:

-bash: type: mysql: not found

By default , MySQL is not installed in Mac OS X.

Sidenote: For XAMPP, the command should be:

/Applications/XAMPP/xamppfiles/bin/mysql --version

adb command not found

If you don't want to edit PATH variable, go to the platform-tools directory where the SDK is installed, and the command is there.

You can use it like this:

  1. Go to the directory where you placed the SDK:

    cd /Users/mansour/Library/Developer/Android/sdk/platform-tools

  2. Type the adb command with ./ to use it from the current directory.

    ./adb tcpip 5555

    ./adb devices

    ./adb connect 192.168.XXX.XXX

What's the difference between RANK() and DENSE_RANK() functions in oracle?

The only difference between the RANK() and DENSE_RANK() functions is in cases where there is a “tie”; i.e., in cases where multiple values in a set have the same ranking. In such cases, RANK() will assign non-consecutive “ranks” to the values in the set (resulting in gaps between the integer ranking values when there is a tie), whereas DENSE_RANK() will assign consecutive ranks to the values in the set (so there will be no gaps between the integer ranking values in the case of a tie).

For example, consider the set {25, 25, 50, 75, 75, 100}. For such a set, RANK() will return {1, 1, 3, 4, 4, 6} (note that the values 2 and 5 are skipped), whereas DENSE_RANK() will return {1,1,2,3,3,4}.

Bulk create model objects in django

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

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

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

Check object empty

This can be done with java reflection,This method returns false if any one attribute value is present for the object ,hope it helps some one

public boolean isEmpty()  {

    for (Field field : this.getClass().getDeclaredFields()) {
        try {
            field.setAccessible(true);
            if (field.get(this)!=null) {
                return false;
            }
        } catch (Exception e) {
          System.out.println("Exception occured in processing");
        }
    }
    return true;
}

How to use querySelectorAll only for elements that have a specific attribute set?

You can use querySelectorAll() like this:

var test = document.querySelectorAll('input[value][type="checkbox"]:not([value=""])');

This translates to:

get all inputs with the attribute "value" and has the attribute "value" that is not blank.

In this demo, it disables the checkbox with a non-blank value.

HTML Form Redirect After Submit

Try this Javascript (jquery) code. Its an ajax request to an external URL. Use the callback function to fire any code:

<script type="text/javascript">
$(function() {
  $('form').submit(function(){
    $.post('http://example.com/upload', function() {
      window.location = 'http://google.com';
    });
    return false;
  });
});
</script>

Multiple FROMs - what it means

The first answer is too complex, historic, and uninformative for my tastes.


It's actually rather simple. Docker provides for a functionality called multi-stage builds the basic idea here is to,

  • Free you from having to manually remove what you don't want, by forcing you to whitelist what you do want,
  • Free resources that would otherwise be taken up because of Docker's implementation.

Let's start with the first. Very often with something like Debian you'll see.

RUN apt-get update \ 
  && apt-get dist-upgrade \
  && apt-get install <whatever> \
  && apt-get clean

We can explain all of this in terms of the above. The above command is chained together so it represents a single change with no intermediate Images required. If it was written like this,

RUN apt-get update ;
RUN apt-get dist-upgrade;
RUN apt-get install <whatever>;
RUN apt-get clean;

It would result in 3 more temporary intermediate Images. Having it reduced to one image, there is one remaining problem: apt-get clean doesn't clean up artifacts used in the install. If a Debian maintainer includes in his install a script that modifies the system that modification will also be present in the final solution (see something like pepperflashplugin-nonfree for an example of that).

By using a multi-stage build you get all the benefits of a single changed action, but it will require you to manually whitelist and copy over files that were introduced in the temporary image using the COPY --from syntax documented here. Moreover, it's a great solution where there is no alternative (like an apt-get clean), and you would otherwise have lots of un-needed files in your final image.

See also

What is setBounds and how do I use it?

setBounds is used to define the bounding rectangle of a component. This includes it's position and size.

The is used in a number of places within the framework.

  • It is used by the layout manager's to define the position and size of a component within it's parent container.
  • It is used by the paint sub system to define clipping bounds when painting the component.

For the most part, you should never call it. Instead, you should use appropriate layout managers and let them determine the best way to provide information to this method.

How to find out what group a given user has?

or just study /etc/groups (ok this does probably not work if it uses pam with ldap)

Is it possible to make desktop GUI application in .NET Core?

If you are using .NET Core 3.0 and above, do the following steps and you are good to go: (I'm going to use .NET Core CLI, but you can use Visual Studio too):

  1. md MyWinFormsApp optional step
  2. cd MyWinFormsApp optional step
  3. dotnet new sln -n MyWinFormsApp optional step, but it's a good idea
  4. dotnet new winforms -n MyWinFormsApp I'm sorry, this is not optional
  5. dotnet sln add MyWinFormsApp do this if you did step #3

Okay, you can stop reading my answer and start adding code to the MyWinFormsApp project. But if you want to work with Form Designer, keep reading.

  1. Open up MyWinFormsApp.csproj file and change <TargetFramework>netcoreapp3.1<TargetFramework> to <TargetFrameworks>net472;netcoreapp3.1</TargetFrameworks> (if you are using netcoreapp3.0 don't worry. Change it to <TargetFrameworks>net472;netcoreapp3.0</TargetFrameworks>)
  2. Then add the following ItemGroup
  <ItemGroup Condition="'$(TargetFramework)' == 'net472'">
    <Compile Update="Form1.cs">
      <SubType>Form</SubType>
    </Compile>
    <Compile Update="Form1.Designer.cs">
      <DependentUpon>Form1.cs</DependentUpon>
    </Compile>
  </ItemGroup>

After doing these steps, this is what you should end up with:

<Project Sdk="Microsoft.NET.Sdk.WindowsDesktop">

  <PropertyGroup>
    <OutputType>WinExe</OutputType>
    <TargetFrameworks>net472;netcoreapp3.1</TargetFrameworks>
    <UseWindowsForms>true</UseWindowsForms>
  </PropertyGroup>

  <ItemGroup Condition="'$(TargetFramework)' == 'net472'">
    <Compile Update="Form1.cs">
      <SubType>Form</SubType>
    </Compile>
    <Compile Update="Form1.Designer.cs">
      <DependentUpon>Form1.cs</DependentUpon>
    </Compile>
  </ItemGroup>

</Project>
  1. Open up file Program.cs and add the following preprocessor-if
#if NETCOREAPP3_1
    Application.SetHighDpiMode(HighDpiMode.SystemAware);
#endif

Now you can open the MyWinFormsApp project using Visual Studio 2019 (I think you can use Visual Studio 2017 too, but I'm not sure) and double click on Form1.cs and you should see this:

Enter image description here

Okay, open up Toolbox (Ctrl + W, X) and start adding controls to your application and make it pretty.

You can read more about designer at Windows Forms .NET Core Designer.

Install pip in docker

This command worked fine for me:

RUN apt-get -y install python3-pip

Untrack files from git temporarily

Use following command to untrack files

git rm --cached <file path>

How to create my json string by using C#?

No real need for the JSON.NET package. You could use JavaScriptSerializer. The Serialize method will turn a managed type instance into a JSON string.

var serializer = new JavaScriptSerializer();
var json = serializer.Serialize(instanceOfThing);

MySQL - Using If Then Else in MySQL UPDATE or SELECT Queries

Whilst you certainly can use MySQL's IF() control flow function as demonstrated by dbemerlin's answer, I suspect it might be a little clearer to the reader (i.e. yourself, and any future developers who might pick up your code in the future) to use a CASE expression instead:

UPDATE Table
SET    A = CASE
         WHEN A > 0 AND A < 1 THEN 1
         WHEN A > 1 AND A < 2 THEN 2
         ELSE A
       END
WHERE  A IS NOT NULL

Of course, in this specific example it's a little wasteful to set A to itself in the ELSE clause—better entirely to filter such conditions from the UPDATE, via the WHERE clause:

UPDATE Table
SET    A = CASE
         WHEN A > 0 AND A < 1 THEN 1
         WHEN A > 1 AND A < 2 THEN 2
       END
WHERE  (A > 0 AND A < 1) OR (A > 1 AND A < 2)

(The inequalities entail A IS NOT NULL).

Or, if you want the intervals to be closed rather than open (note that this would set values of 0 to 1—if that is undesirable, one could explicitly filter such cases in the WHERE clause, or else add a higher precedence WHEN condition):

UPDATE Table
SET    A = CASE
         WHEN A BETWEEN 0 AND 1 THEN 1
         WHEN A BETWEEN 1 AND 2 THEN 2
       END
WHERE  A BETWEEN 0 AND 2

Though, as dbmerlin also pointed out, for this specific situation you could consider using CEIL() instead:

UPDATE Table SET A = CEIL(A) WHERE A BETWEEN 0 AND 2

Function or sub to add new row and data to table

Minor variation on Geoff's answer.

New Data in Array:

Sub AddDataRow(tableName As String, NewData As Variant)
    Dim sheet As Worksheet
    Dim table As ListObject
    Dim col As Integer
    Dim lastRow As Range

    Set sheet = Range(tableName).Parent
    Set table = sheet.ListObjects.Item(tableName)

    'First check if the last row is empty; if not, add a row
    If table.ListRows.Count > 0 Then
        Set lastRow = table.ListRows(table.ListRows.Count).Range
        If Application.CountBlank(lastRow) < lastRow.Columns.Count Then
            table.ListRows.Add
        End If
    End If

    'Iterate through the last row and populate it with the entries from values()
    Set lastRow = table.ListRows(table.ListRows.Count).Range
    For col = 1 To lastRow.Columns.Count
        If col <= UBound(NewData) + 1 Then lastRow.Cells(1, col) = NewData(col - 1)
    Next col
End Sub

New Data in Horizontal Range:

Sub AddDataRow(tableName As String, NewData As Range)
    Dim sheet As Worksheet
    Dim table As ListObject
    Dim col As Integer
    Dim lastRow As Range

    Set sheet = Range(tableName).Parent
    Set table = sheet.ListObjects.Item(tableName)

    'First check if the last table row is empty; if not, add a row
    If table.ListRows.Count > 0 Then
        Set lastRow = table.ListRows(table.ListRows.Count).Range
        If Application.CountBlank(lastRow) < lastRow.Columns.Count Then
            table.ListRows.Add
        End If
    End If

    'Copy NewData to new table record
    Set lastRow = table.ListRows(table.ListRows.Count).Range
    lastRow.Value = NewData.Value
End Sub

java - iterating a linked list

Each java.util.List implementation is required to preserve the order so either you are using ArrayList, LinkedList, Vector, etc. each of them are ordered collections and each of them preserve the order of insertion (see http://download.oracle.com/javase/1.4.2/docs/api/java/util/List.html)

Parsing string as JSON with single quotes?

The JSON standard requires double quotes and will not accept single quotes, nor will the parser.

If you have a simple case with no escaped single quotes in your strings (which would normally be impossible, but this isn't JSON), you can simple str.replace(/'/g, '"') and you should end up with valid JSON.

MySQL SELECT last few days?

Use for a date three days ago:

WHERE t.date >= DATE_ADD(CURDATE(), INTERVAL -3 DAY);

Check the DATE_ADD documentation.

Or you can use:

WHERE t.date >= ( CURDATE() - INTERVAL 3 DAY )

Responsive Images with CSS

the best way i found was to set the image you want to view responsively as a background image and sent a css property for the div as cover.

background-image : url('YOUR URL');
background-size : cover

Is <div style="width: ;height: ;background: "> CSS?

1)Yes it is, when there is style then it is styling your code(css).2) is belong to html it is like a container that keep your css.

Find object by id in an array of JavaScript objects

Underscore.js has a nice method for that:

myArray = [{'id':'73','foo':'bar'},{'id':'45','foo':'bar'},etc.]
obj = _.find(myArray, function(obj) { return obj.id == '45' })

How to declare or mark a Java method as deprecated?

since some minor explanations were missing

Use @Deprecated annotation on the method like this

 /**
 * @param basePrice
 * 
 * @deprecated  reason this method is deprecated <br/>
 *              {will be removed in next version} <br/>
 *              use {@link #setPurchasePrice()} instead like this: 
 * 
 * 
 * <blockquote><pre>
 * getProduct().setPurchasePrice(200) 
 * </pre></blockquote>
 * 
 */
@Deprecated
public void setBaseprice(int basePrice) {
}

remember to explain:

  1. Why is this method no longer recommended. What problems arise when using it. Provide a link to the discussion on the matter if any. (remember to separate lines for readability <br/>
  2. When it will be removed. (let your users know how much they can still rely on this method if they decide to stick to the old way)
  3. Provide a solution or link to the method you recommend {@link #setPurchasePrice()}

Java Timer vs ExecutorService?

Here's some more good practices around Timer use:

http://tech.puredanger.com/2008/09/22/timer-rules/

In general, I'd use Timer for quick and dirty stuff and Executor for more robust usage.

JSTL if tag for equal strings

<c:if test="${ansokanInfo.pSystem eq 'NAT'}">

AngularJs ReferenceError: $http is not defined

Just to complete Amit Garg answer, there are several ways to inject dependencies in AngularJS.


You can also use $inject to add a dependency:

var MyController = function($scope, $http) {
  // ...
}
MyController.$inject = ['$scope', '$http'];

Swift - Split string over multiple lines

Swift 4 has addressed this issue by giving Multi line string literal support.To begin string literal add three double quotes marks (”””) and press return key, After pressing return key start writing strings with any variables , line breaks and double quotes just like you would write in notepad or any text editor. To end multi line string literal again write (”””) in new line.

See Below Example

     let multiLineStringLiteral = """
    This is one of the best feature add in Swift 4
    It let’s you write “Double Quotes” without any escaping
    and new lines without need of “\n”
    """

print(multiLineStringLiteral)

PHP, pass array through POST

You could put it in the session:

session_start();
$_SESSION['array_name'] = $array_name;

Or if you want to send it via a form you can serialize it:

<input type='hidden' name='input_name' value="<?php echo htmlentities(serialize($array_name)); ?>" />

$passed_array = unserialize($_POST['input_name']);

Note that to work with serialized arrays, you need to use POST as the form's transmission method, as GET has a size limit somewhere around 1024 characters.

I'd use sessions wherever possible.

How do I start PowerShell from Windows Explorer?

I created a fully automated solution to add PS and CMD context items. Just run set_registry.cmd and it will update registry to add two buttons when click RMB on folder or inside some opened folder: enter image description here

This will change owner of registry keys to admin and add context menus
Change registry to enable PS and CWD context menus

How to use adb pull command?

I don't think adb pull handles wildcards for multiple files. I ran into the same problem and did this by moving the files to a folder and then pulling the folder.

I found a link doing the same thing. Try following these steps.

How to copy selected files from Android with adb pull

How can I use pointers in Java?

As others have said, the short answer is "No".

Sure, you could write JNI code that plays with Java pointers. Depending on what you're trying to accomplish, maybe that would get you somewhere and maybe it wouldn't.

You could always simulate pointes by creating an array and working with indexes into the array. Again, depending on what you're trying to accomplish, that might or might not be useful.

How to append rows in a pandas dataframe in a for loop?

Suppose your data looks like this:

import pandas as pd
import numpy as np

np.random.seed(2015)
df = pd.DataFrame([])
for i in range(5):
    data = dict(zip(np.random.choice(10, replace=False, size=5),
                    np.random.randint(10, size=5)))
    data = pd.DataFrame(data.items())
    data = data.transpose()
    data.columns = data.iloc[0]
    data = data.drop(data.index[[0]])
    df = df.append(data)
print('{}\n'.format(df))
# 0   0   1   2   3   4   5   6   7   8   9
# 1   6 NaN NaN   8   5 NaN NaN   7   0 NaN
# 1 NaN   9   6 NaN   2 NaN   1 NaN NaN   2
# 1 NaN   2   2   1   2 NaN   1 NaN NaN NaN
# 1   6 NaN   6 NaN   4   4   0 NaN NaN NaN
# 1 NaN   9 NaN   9 NaN   7   1   9 NaN NaN

Then it could be replaced with

np.random.seed(2015)
data = []
for i in range(5):
    data.append(dict(zip(np.random.choice(10, replace=False, size=5),
                         np.random.randint(10, size=5))))
df = pd.DataFrame(data)
print(df)

In other words, do not form a new DataFrame for each row. Instead, collect all the data in a list of dicts, and then call df = pd.DataFrame(data) once at the end, outside the loop.

Each call to df.append requires allocating space for a new DataFrame with one extra row, copying all the data from the original DataFrame into the new DataFrame, and then copying data into the new row. All that allocation and copying makes calling df.append in a loop very inefficient. The time cost of copying grows quadratically with the number of rows. Not only is the call-DataFrame-once code easier to write, it's performance will be much better -- the time cost of copying grows linearly with the number of rows.

Using global variables in a function

You're not actually storing the global in a local variable, just creating a local reference to the same object that your original global reference refers to. Remember that pretty much everything in Python is a name referring to an object, and nothing gets copied in usual operation.

If you didn't have to explicitly specify when an identifier was to refer to a predefined global, then you'd presumably have to explicitly specify when an identifier is a new local variable instead (for example, with something like the 'var' command seen in JavaScript). Since local variables are more common than global variables in any serious and non-trivial system, Python's system makes more sense in most cases.

You could have a language which attempted to guess, using a global variable if it existed or creating a local variable if it didn't. However, that would be very error-prone. For example, importing another module could inadvertently introduce a global variable by that name, changing the behaviour of your program.

Remove old Fragment from fragment manager

If you want to replace a fragment with another, you should have added them dynamically, first of all. Fragments that are hard coded in XML, cannot be replaced.

// Create new fragment and transaction
Fragment newFragment = new ExampleFragment();
FragmentTransaction transaction = getFragmentManager().beginTransaction();

// Replace whatever is in the fragment_container view with this fragment,
// and add the transaction to the back stack
transaction.replace(R.id.fragment_container, newFragment);
transaction.addToBackStack(null);

// Commit the transaction
transaction.commit();

Refer this post: Replacing a fragment with another fragment inside activity group

Refer1: Replace a fragment programmatically

How to insert &nbsp; in XSLT

One can also do this :

<xsl:text disable-output-escaping="yes"><![CDATA[&nbsp;]]></xsl:text>

Regex to match 2 digits, optional decimal, two digits

Following is Very Good Regular expression for Two digits and two decimal points.

[RegularExpression(@"\d{0,2}(\.\d{1,2})?", ErrorMessage = "{0} must be a Decimal Number.")]

Token based authentication in Web API without any user interface

ASP.Net Web API has Authorization Server build-in already. You can see it inside Startup.cs when you create a new ASP.Net Web Application with Web API template.

OAuthOptions = new OAuthAuthorizationServerOptions
{
    TokenEndpointPath = new PathString("/Token"),
    Provider = new ApplicationOAuthProvider(PublicClientId),
    AuthorizeEndpointPath = new PathString("/api/Account/ExternalLogin"),
    AccessTokenExpireTimeSpan = TimeSpan.FromDays(14),
    // In production mode set AllowInsecureHttp = false
    AllowInsecureHttp = true
};

All you have to do is to post URL encoded username and password inside query string.

/Token/userName=johndoe%40example.com&password=1234&grant_type=password

If you want to know more detail, you can watch User Registration and Login - Angular Front to Back with Web API by Deborah Kurata.

How to fetch the dropdown values from database and display in jsp

I made this in my code to do that

note: I am a beginner.

It is my jsp code.

<%
java.sql.Connection Conn = DBconnector.SetDBConnection(); /* make connector as you make in your code */
Statement st = null;
ResultSet rs = null;
st = Conn.createStatement();
rs = st.executeQuery("select * from department"); %>
<tr> 
    <td> 
        Student Major  : <select name ="Major">
        <%while(rs.next()){ %>
        <option value="<%=rs.getString(1)%>"><%=rs.getString(1)%></option>
                        <%}%>           
                         </select> 
   </td> 

How to split a dos path into its components in Python

The problem here starts with how you're creating the string in the first place.

a = "d:\stuff\morestuff\furtherdown\THEFILE.txt"

Done this way, Python is trying to special case these: \s, \m, \f, and \T. In your case, \f is being treated as a formfeed (0x0C) while the other backslashes are handled correctly. What you need to do is one of these:

b = "d:\\stuff\\morestuff\\furtherdown\\THEFILE.txt"      # doubled backslashes
c = r"d:\stuff\morestuff\furtherdown\THEFILE.txt"         # raw string, no doubling necessary

Then once you split either of these, you'll get the result you want.