Programs & Examples On #Insert iterator

xlrd.biffh.XLRDError: Excel xlsx file; not supported

The previous version, xlrd 1.2.0, may appear to work, but it could also expose you to potential security vulnerabilities. With that warning out of the way, if you still want to give it a go, type the following command:

pip install xlrd==1.2.0

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

(function(){
    var special = jQuery.event.special,
        uid1 = 'D' + (+new Date()),
        uid2 = 'D' + (+new Date() + 1);

    special.resizestart = {
        setup: function() {
            var timer,
                handler =  function(evt) {
                    var _self = this,
                        _args = arguments;
                    if (timer) {
                        clearTimeout(timer);
                    } else {
                        evt.type = 'resizestart';
                        jQuery.event.handle.apply(_self, _args);
                    }

                    timer = setTimeout( function(){
                        timer = null;
                    }, special.resizestop.latency);
                };
            jQuery(this).bind('resize', handler).data(uid1, handler);
        },
        teardown: function(){
            jQuery(this).unbind( 'resize', jQuery(this).data(uid1) );
        }
    };

    special.resizestop = {
        latency: 200,
        setup: function() {
            var timer,
                handler = function(evt) {
                    var _self = this,
                        _args = arguments;
                    if (timer) {
                        clearTimeout(timer);
                    }
                    timer = setTimeout( function(){
                        timer = null;
                        evt.type = 'resizestop';
                        jQuery.event.handle.apply(_self, _args);
                    }, special.resizestop.latency);
                };

            jQuery(this).bind('resize', handler).data(uid2, handler);
        },
        teardown: function() {
            jQuery(this).unbind( 'resize', jQuery(this).data(uid2) );
        }
    };
})();

$(window).bind('resizestop',function(){
    //...
});

Include .so library in apk in android studio

I had the same problem. Check out the comment in https://gist.github.com/khernyo/4226923#comment-812526

It says:

for gradle android plugin v0.3 use "com.android.build.gradle.tasks.PackageApplication"

That should fix your problem.

Google Play app description formatting

Currently (June 2016) typing in the link as http://www.example.com will only produce plain text.

You can now however put in an html anchor :

<a href="http://www.example.com">My Example Site</a>

Guid is all 0's (zeros)?

Lessons to learn from this:

1) Guid is a value type, not a reference type.

2) Calling the default constructor new S() on any value type always gives you back the all-zero form of that value type, whatever it is. It is logically the same as default(S).

Jenkins, specifying JAVA_HOME

In Ubuntu 12.04 I had to install openjdk-7-jdk

then javac was working !

then I could use

/usr/lib/jvm/java-7-openjdk-amd64

as path and jenkins didn't complain anymore.

Merge unequal dataframes and replace missing rows with 0

Take a look at the help page for merge. The all parameter lets you specify different types of merges. Here we want to set all = TRUE. This will make merge return NA for the values that don't match, which we can update to 0 with is.na():

zz <- merge(df1, df2, all = TRUE)
zz[is.na(zz)] <- 0

> zz
  x y
1 a 0
2 b 1
3 c 0
4 d 0
5 e 0

Updated many years later to address follow up question

You need to identify the variable names in the second data table that you aren't merging on - I use setdiff() for this. Check out the following:

df1 = data.frame(x=c('a', 'b', 'c', 'd', 'e', NA))
df2 = data.frame(x=c('a', 'b', 'c'),y1 = c(0,1,0), y2 = c(0,1,0))

#merge as before
df3 <- merge(df1, df2, all = TRUE)
#columns in df2 not in df1
unique_df2_names <- setdiff(names(df2), names(df1))
df3[unique_df2_names][is.na(df3[, unique_df2_names])] <- 0 

Created on 2019-01-03 by the reprex package (v0.2.1)

How to set UITextField height?

CGRect frameRect = textField.frame;
frameRect.size.height = 100; // <-- Specify the height you want here.
textField.frame = frameRect;

Convert float to std::string in C++

This tutorial gives a simple, yet elegant, solution, which i transcribe:

#include <sstream>
#include <string>
#include <stdexcept>

class BadConversion : public std::runtime_error {
public:
  BadConversion(std::string const& s)
    : std::runtime_error(s)
    { }
};

inline std::string stringify(double x)
{
  std::ostringstream o;
  if (!(o << x))
    throw BadConversion("stringify(double)");
  return o.str();
}
...
std::string my_val = stringify(val);

How does Spring autowire by name when more than one matching bean is found?

in some case you can use annotation @Primary.

@Primary
class USA implements Country {}

This way it will be selected as the default autowire candididate, with no need to autowire-candidate on the other bean.

for mo deatils look at Autowiring two beans implementing same interface - how to set default bean to autowire?

Angularjs ng-model doesn't work inside ng-if

The ng-if directive, like other directives creates a child scope. See the script below (or this jsfiddle)

_x000D_
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0rc1/angular.min.js"></script>_x000D_
_x000D_
<script>_x000D_
    function main($scope) {_x000D_
        $scope.testa = false;_x000D_
        $scope.testb = false;_x000D_
        $scope.testc = false;_x000D_
        $scope.obj = {test: false};_x000D_
    }_x000D_
</script>_x000D_
_x000D_
<div ng-app >_x000D_
    <div ng-controller="main">_x000D_
        _x000D_
        Test A: {{testa}}<br />_x000D_
        Test B: {{testb}}<br />_x000D_
        Test C: {{testc}}<br />_x000D_
        {{obj.test}}_x000D_
        _x000D_
        <div>_x000D_
            testa (without ng-if): <input type="checkbox" ng-model="testa" />_x000D_
        </div>_x000D_
        <div ng-if="!testa">_x000D_
            testb (with ng-if): <input type="checkbox" ng-model="testb" /> {{testb}}_x000D_
        </div>_x000D_
        <div ng-if="!someothervar">_x000D_
            testc (with ng-if): <input type="checkbox" ng-model="testc" />_x000D_
        </div>_x000D_
        <div ng-if="!someothervar">_x000D_
            object (with ng-if): <input type="checkbox" ng-model="obj.test" />_x000D_
        </div>_x000D_
        _x000D_
    </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

So, your checkbox changes the testb inside of the child scope, but not the outer parent scope.

Note, that if you want to modify the data in the parent scope, you'll need to modify the internal properties of an object like in the last div that I added.

How to set text size of textview dynamically for different screens

float currentSize = textEdit.getTextSize(); // default size
float newSize = currentSize * 2.0F; // new size is twice bigger than default one
textEdit.setTextSize(newSize);

C++ string to double conversion

If you are reading from a file then you should hear the advice given and just put it into a double.

On the other hand, if you do have, say, a string you could use boost's lexical_cast.

Here is a (very simple) example:

int Foo(std::string anInt)
{
   return lexical_cast<int>(anInt);
}

std::string formatting like sprintf

I usually use this:

std::string myformat(const char *const fmt, ...)
{
        char *buffer = NULL;
        va_list ap;

        va_start(ap, fmt);
        (void)vasprintf(&buffer, fmt, ap);
        va_end(ap);

        std::string result = buffer;
        free(buffer);

        return result;
}

Disadvantage: not all systems support vasprint

JavaScriptSerializer.Deserialize - how to change field names

My requirements included:

  • must honor the dataContracts
  • must deserialize dates in the format received in service
  • must handle colelctions
  • must target 3.5
  • must NOT add an external dependency, especially not Newtonsoft (I'm creating a distributable package myself)
  • must not be deserialized by hand

My solution in the end was to use SimpleJson(https://github.com/facebook-csharp-sdk/simple-json).

Although you can install it via a nuget package, I included just that single SimpleJson.cs file (with the MIT license) in my project and referenced it.

I hope this helps someone.

How may I sort a list alphabetically using jQuery?

improvement based on Jeetendra Chauhan's answer

$('ul.menu').each(function(){
    $(this).children('li').sort((a,b)=>a.innerText.localeCompare(b.innerText)).appendTo(this);
});

why i consider it an improvement:

  1. using each to support running on more than one ul

  2. using children('li') instead of ('ul li') is important because we only want to process direct children and not descendants

  3. using the arrow function (a,b)=> just looks better (IE not supported)

  4. using vanilla innerText instead of $(a).text() for speed improvement

  5. using vanilla localeCompare improves speed in case of equal elements (rare in real life usage)

  6. using appendTo(this) instead of using another selector will make sure that even if the selector catches more than one ul still nothing breaks

Uninstalling an MSI file from the command line without using msiexec

The msi file extension is mapped to msiexec (same way typing a .txt filename on a command prompt launches Notepad/default .txt file handler to display the file).

Thus typing in a filename with an .msi extension really runs msiexec with the MSI file as argument and takes the default action, install. For that reason, uninstalling requires you to invoke msiexec with uninstall switch to unstall it.

Removing certain characters from a string in R

This should work

gsub('\u009c','','\u009cYes yes for ever for ever the boys ')
"Yes yes for ever for ever the boys "

Here 009c is the hexadecimal number of unicode. You must always specify 4 hexadecimal digits. If you have many , one solution is to separate them by a pipe:

gsub('\u009c|\u00F0','','\u009cYes yes \u00F0for ever for ever the boys and the girls')

"Yes yes for ever for ever the boys and the girls"

How can I scroll a web page using selenium webdriver in python?

None of these answers worked for me, at least not for scrolling down a facebook search result page, but I found after a lot of testing this solution:

while driver.find_element_by_tag_name('div'):
    driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
    Divs=driver.find_element_by_tag_name('div').text
    if 'End of Results' in Divs:
        print 'end'
        break
    else:
        continue

Appending an element to the end of a list in Scala

This is similar to one of the answers but in different way :

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

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

Warning: #1265 Data truncated for column 'pdd' at row 1

You are most likely pushing a string 'NULL' to the table, rather then an actual NULL, but other things may be going on as well, an illustration:

mysql> CREATE TABLE date_test (pdd DATE NOT NULL);
Query OK, 0 rows affected (0.11 sec)

mysql> INSERT INTO date_test VALUES (NULL);
ERROR 1048 (23000): Column 'pdd' cannot be null
mysql> INSERT INTO date_test VALUES ('NULL');
Query OK, 1 row affected, 1 warning (0.05 sec)

mysql> show warnings;
+---------+------+------------------------------------------+
| Level   | Code | Message                                  |
+---------+------+------------------------------------------+
| Warning | 1265 | Data truncated for column 'pdd' at row 1 |
+---------+------+------------------------------------------+
1 row in set (0.00 sec)

mysql> SELECT * FROM date_test;
+------------+
| pdd        |
+------------+
| 0000-00-00 |
+------------+
1 row in set (0.00 sec)

mysql> ALTER TABLE date_test MODIFY COLUMN pdd DATE NULL;
Query OK, 1 row affected (0.15 sec)
Records: 1  Duplicates: 0  Warnings: 0

mysql> INSERT INTO date_test VALUES (NULL);
Query OK, 1 row affected (0.06 sec)

mysql> SELECT * FROM date_test;
+------------+
| pdd        |
+------------+
| 0000-00-00 |
| NULL       |
+------------+
2 rows in set (0.00 sec)

Convert HTML to NSAttributedString in iOS

The above solution is correct.

[[NSAttributedString alloc] initWithData:[htmlString dataUsingEncoding:NSUTF8StringEncoding] 
                                 options:@{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType,
                                           NSCharacterEncodingDocumentAttribute: @(NSUTF8StringEncoding)} 
                      documentAttributes:nil error:nil];

But the app wioll crash if you are running it on ios 8.1,2 or 3.

To avoid the crash what you can do is : run this in a queue. So that it always be on main thread.

Http Servlet request lose params from POST body after read it once

First of all we should not read parameters within the filter. Usually the headers are read in the filter to do few authentication tasks. Having said that one can read the HttpRequest body completely in the Filter or Interceptor by using the CharStreams:

String body = com.google.common.io.CharStreams.toString(request.getReader());

This does not affect the subsequent reads at all.

Minimum and maximum value of z-index?

Conclusion Maximum z-index value is 2,147,483,647 and more than this convert to 2,147,483,647

?Browser Maximum More Than Maximum
Chrome >= 29 2,147,483,647 2,147,483,647
Opera >= 9 2,147,483,647 2,147,483,647
IE >= 6 2,147,483,647 2,147,483,647
Safari >= 4 2,147,483,647 2,147,483,647
Safari = 3 16,777,271 16,777,271
Firefox >= 4 2,147,483,647 2,147,483,647
Firefox = 3 2,147,483,647 0
Firefox = 2 2,147,483,647 Bug: tag hidden

All Values tested in BrowserStack.

How might I force a floating DIV to match the height of another floating DIV?

Here is a jQuery plugin to set the heights of multiple divs to be the same. And below is the actual code of the plugin.

$.fn.equalHeights = function(px) {
$(this).each(function(){
var currentTallest = 0;
$(this).children().each(function(i){
    if ($(this).height() > currentTallest) { currentTallest = $(this).height(); }
        });
    if (!px || !Number.prototype.pxToEm) currentTallest = currentTallest.pxToEm(); //use ems unless px is specified
        // for ie6, set height since min-height isn't supported
    if ($.browser.msie && $.browser.version == 6.0) { $(this).children().css({'height': currentTallest}); }
        $(this).children().css({'min-height': currentTallest}); 
    });
    return this;
};

How do you format the day of the month to say "11th", "21st" or "23rd" (ordinal indicator)?

Using the new java.time package and the newer Java switch statement, the following easily allows an ordinal to be placed on a day of the month. One drawback is that this does not lend itself to canned formats specified in the DateFormatter class.

Simply create a day of some format but include %s%s to add the day and ordinal later.

ZonedDateTime ldt = ZonedDateTime.now();
String format = ldt.format(DateTimeFormatter
        .ofPattern("EEEE, MMMM '%s%s,' yyyy hh:mm:ss a zzz"));

Now pass the day of the week and the just formatted date to a helper method to add the ordinal day.


int day = ldt.getDayOfMonth();
System.out.println(applyOrdinalDaySuffix(format, day));

Prints

Tuesday, October 6th, 2020 11:38:23 AM EDT

Here is the helper method.

Using the Java 14 switch expressions makes getting the ordinal very easy.

public static String applyOrdinalDaySuffix(String format,
        int day) {
    if (day < 1 || day > 31)
        throw new IllegalArgumentException(
                String.format("Bad day of month (%s)", day));
    String ord = switch (day) {
        case 1, 21, 31 -> "st";
        case 2, 22 -> "nd";
        case 3, 23 -> "rd";
        default -> "th";
    };
    
    return String.format(format, day, ord);
}

@UniqueConstraint and @Column(unique = true) in hibernate annotation

In addition to Boaz's answer ....

@UniqueConstraint allows you to name the constraint, while @Column(unique = true) generates a random name (e.g. UK_3u5h7y36qqa13y3mauc5xxayq).

Sometimes it can be helpful to know what table a constraint is associated with. E.g.:

@Table(
   name = "product_serial_group_mask", 
   uniqueConstraints = {
      @UniqueConstraint(
          columnNames = {"mask", "group"},
          name="uk_product_serial_group_mask"
      )
   }
)

Remove DEFINER clause from MySQL Dumps

I don't think there is a way to ignore adding DEFINERs to the dump. But there are ways to remove them after the dump file is created.

  1. Open the dump file in a text editor and replace all occurrences of DEFINER=root@localhost with an empty string ""

  2. Edit the dump (or pipe the output) using perl:

    perl -p -i.bak -e "s/DEFINER=\`\w.*\`@\`\d[0-3].*[0-3]\`//g" mydatabase.sql
    
  3. Pipe the output through sed:

    mysqldump ... | sed -e 's/DEFINER[ ]*=[ ]*[^*]*\*/\*/' > triggers_backup.sql
    

Filtering Pandas Dataframe using OR statement

You can do like below to achieve your result:

import seaborn as sns
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
....
....
#use filter with plot
#or
fg=sns.factorplot('Retailer country', data=df1[(df1['Retailer country']=='United States') | (df1['Retailer country']=='France')], kind='count')

fg.set_xlabels('Retailer country')
plt.show()


#also
#and
fg=sns.factorplot('Retailer country', data=df1[(df1['Retailer country']=='United States') & (df1['Year']=='2013')], kind='count')

fg.set_xlabels('Retailer country')
plt.show()

How to convert string to string[]?

zerkms told you the difference. If you like you can "convert" a string to an array of strings with length of 1.

If you want to send the string as a argument for example you can do like this:

var myString = "Test";

MethodThatRequiresStringArrayAsParameter( new[]{myString} );

I honestly can't see any other reason of doing the conversion than to satisty a method argument, but if it's another reason you will have to provide some information as to what you are trying to accomplish since there is probably a better solution.

How to check status of PostgreSQL server Mac OS X

You can use brew to start/stop pgsql. I've following short cuts in my ~/.bashrc file

alias start-pg='brew services start postgresql'
alias stop-pg='brew services stop postgresql'
alias restart-pg='brew services restart postgresql'

How do I load a PHP file into a variable?

Theoretically you could just use fopen, then use stream_get_contents.

$stream = fopen("file.php","r");
$string = stream_get_contents($stream);
fclose($stream);

That should read the entire file into $string for you, and should not evaluate it. Though I'm surprised that file_get_contents didn't work when you specified the local path....

Forking vs. Branching in GitHub

Here are the high-level differences:

Forking

Pros

  • Keeps branches separated by user
  • Reduces clutter in the primary repository
  • Your team process reflects the external contributor process

Cons

  • Makes it more difficult to see all of the branches that are active (or inactive, for that matter)
  • Collaborating on a branch is trickier (the fork owner needs to add the person as a collaborator)
  • You need to understand the concept of multiple remotes in Git
    • Requires additional mental bookkeeping
    • This will make the workflow more difficult for people who aren't super comfortable with Git

Branching

Pros

  • Keeps all of the work being done around a project in one place
  • All collaborators can push to the same branch to collaborate on it
  • There's only one Git remote to deal with

Cons

  • Branches that get abandoned can pile up more easily
  • Your team contribution process doesn't match the external contributor process
  • You need to add team members as contributors before they can branch

How to get a file or blob from an object URL?

See Getting BLOB data from XHR request which points out that BlobBuilder doesn't work in Chrome so you need to use:

xhr.responseType = 'arraybuffer';

NullPointerException in Java with no StackTrace

As you mentioned in a comment, you're using log4j. I discovered (inadvertently) a place where I had written

LOG.error(exc);

instead of the typical

LOG.error("Some informative message", e);

through laziness or perhaps just not thinking about it. The unfortunate part of this is that it doesn't behave as you expect. The logger API actually takes Object as the first argument, not a string - and then it calls toString() on the argument. So instead of getting the nice pretty stack trace, it just prints out the toString - which in the case of NPE is pretty useless.

Perhaps this is what you're experiencing?

Storing JSON in database vs. having a new column for each key

Like most things "it depends". It's not right or wrong/good or bad in and of itself to store data in columns or JSON. It depends on what you need to do with it later. What is your predicted way of accessing this data? Will you need to cross reference other data?

Other people have answered pretty well what the technical trade-off are.

Not many people have discussed that your app and features evolve over time and how this data storage decision impacts your team.

Because one of the temptations of using JSON is to avoid migrating schema and so if the team is not disciplined, it's very easy to stick yet another key/value pair into a JSON field. There's no migration for it, no one remembers what it's for. There is no validation on it.

My team used JSON along side traditional columns in postgres and at first it was the best thing since sliced bread. JSON was attractive and powerful, until one day we realized that flexibility came at a cost and it's suddenly a real pain point. Sometimes that point creeps up really quickly and then it becomes hard to change because we've built so many other things on top of this design decision.

Overtime, adding new features, having the data in JSON led to more complicated looking queries than what might have been added if we stuck to traditional columns. So then we started fishing certain key values back out into columns so that we could make joins and make comparisons between values. Bad idea. Now we had duplication. A new developer would come on board and be confused? Which is the value I should be saving back into? The JSON one or the column?

The JSON fields became junk drawers for little pieces of this and that. No data validation on the database level, no consistency or integrity between documents. That pushed all that responsibility into the app instead of getting hard type and constraint checking from traditional columns.

Looking back, JSON allowed us to iterate very quickly and get something out the door. It was great. However after we reached a certain team size it's flexibility also allowed us to hang ourselves with a long rope of technical debt which then slowed down subsequent feature evolution progress. Use with caution.

Think long and hard about what the nature of your data is. It's the foundation of your app. How will the data be used over time. And how is it likely TO CHANGE?

How to add smooth scrolling to Bootstrap's scroll spy function

with this code, the id will not appear on the link

    document.querySelectorAll('a[href^="#"]').forEach(anchor => {
        anchor.addEventListener('click', function (e) {
            e.preventDefault();

            document.querySelector(this.getAttribute('href')).scrollIntoView({
                behavior: 'smooth'
            });
        });
    });

Timeout function if it takes too long to finish

I rewrote David's answer using the with statement, it allows you do do this:

with timeout(seconds=3):
    time.sleep(4)

Which will raise a TimeoutError.

The code is still using signal and thus UNIX only:

import signal

class timeout:
    def __init__(self, seconds=1, error_message='Timeout'):
        self.seconds = seconds
        self.error_message = error_message
    def handle_timeout(self, signum, frame):
        raise TimeoutError(self.error_message)
    def __enter__(self):
        signal.signal(signal.SIGALRM, self.handle_timeout)
        signal.alarm(self.seconds)
    def __exit__(self, type, value, traceback):
        signal.alarm(0)

C++ STL Vectors: Get iterator from index?

Or you can use std::advance

vector<int>::iterator i = L.begin();
advance(i, 2);

How to execute a command in a remote computer?

IMO, in your case you can try this:

  1. Map the shared folder to a drive or folder on your machine. (here's how)
  2. Access the mapped drive/folder as you normally would local files.

Nothing needs to be installed. No services need to be running except those that enable folder sharing.

If you can access the shared folder and maps it on your machine, most things should work just like local files, including command prompts and all explorer-enhancement tools.

This is different from using PsExec (or RDP-ing in) in that you do not need to have administrative rights and/or remote desktop/terminal services connection rights on the remote server, you just need to be able to access those shared folders.

Also make sure you have all the necessary security permissions to run whatever commands/tools you want to run on those shared folders as well.


If, however you wish the processing to be done on the target machine, then you can try PsExec as @divo and @recursive pointed out, something alongs:

PsExec \\yourServerName -u yourUserName cmd.exe

Which will brings gives you a command prompt at the remote machine. And from there you can execute whatever you want.

I am not sure but I think you need either the Server (lanmanserver) or the Terminal Services (TermService) service to be running (which should have already be running).

How to get the current location in Google Maps Android API v2?

try this

LocationManager service = (LocationManager) getSystemService(LOCATION_SERVICE);
Criteria criteria = new Criteria();
String provider = service.getBestProvider(criteria, false);
Location location = service.getLastKnownLocation(provider);
LatLng userLocation = new LatLng(location.getLatitude(),location.getLongitude());

Passing parameters in rails redirect_to

Just append them to the options:

redirect_to controller: 'thing', action: 'edit', id: 3, something: 'else'

Would yield /thing/3/edit?something=else

Generate UML Class Diagram from Java Project

I use eUML2 plugin from Soyatec, under Eclipse and it works fine for the generation of UML giving the source code. This tool is useful up to Eclipse 4.4.x

What are some great online database modeling tools?

I've used DBDesigner before. It is an open source tool. You might check that out. Not sure if it fits your needs.

Best of luck!

Composer killed while updating

You can try setting preferred-install to "dist" in Composer config.

jQuery function after .append

Yes you can add a callback function to any DOM insertion:
$myDiv.append( function(index_myDiv, HTML_myDiv){ //.... return child })

Check on JQuery documentation: http://api.jquery.com/append/
And here's a practical, similar, example: http://www.w3schools.com/jquery/tryit.asp?filename=tryjquery_html_prepend_func

How do I seed a random class to avoid getting duplicate random values

In case you can't for some reason use the same Random again and again, try initializing it with something that changes all the time, like the time itself.

new Random(new System.DateTime().Millisecond).Next();

Remember this is bad practice though.

EDIT: The default constructor already takes its seed from the clock, and probably better than we would. Quoting from MSDN:

Random() : Initializes a new instance of the Random class, using a time-dependent default seed value.

The code below is probably your best option:

new Random().Next();

Properties private set;

while(dr.read())
{
    returnPersonList.add( 
        new Person(dr.GetInt32(1), dr.GetInt32(0), dr.GetString(2)));
}

where:

public class Person
{
    public Person(int age, int id, string name) 
    {
        Age = age;
        Id = id;
        Name = name;
    }
}

Creating a 3D sphere in Opengl using Visual C++

I like the answer of coin. It's simple to understand and works with triangles. However the indexes of his program are sometimes over the bounds. So I post here his code with two tiny corrections:

inline void push_indices(vector<GLushort>& indices, int sectors, int r, int s) {
    int curRow = r * sectors;
    int nextRow = (r+1) * sectors;
    int nextS = (s+1) % sectors;

    indices.push_back(curRow + s);
    indices.push_back(nextRow + s);
    indices.push_back(nextRow + nextS);

    indices.push_back(curRow + s);
    indices.push_back(nextRow + nextS);
    indices.push_back(curRow + nextS);
}

void createSphere(vector<vec3>& vertices, vector<GLushort>& indices, vector<vec2>& texcoords,
                  float radius, unsigned int rings, unsigned int sectors)
{
    float const R = 1./(float)(rings-1);
    float const S = 1./(float)(sectors-1);

    for(int r = 0; r < rings; ++r) {
        for(int s = 0; s < sectors; ++s) {
            float const y = sin( -M_PI_2 + M_PI * r * R );
            float const x = cos(2*M_PI * s * S) * sin( M_PI * r * R );
            float const z = sin(2*M_PI * s * S) * sin( M_PI * r * R );

            texcoords.push_back(vec2(s*S, r*R));
            vertices.push_back(vec3(x,y,z) * radius);
            if(r < rings-1)
                push_indices(indices, sectors, r, s);
        }
    }
}

Sorting Characters Of A C++ String

There is a sorting algorithm in the standard library, in the header <algorithm>. It sorts inplace, so if you do the following, your original word will become sorted.

std::sort(word.begin(), word.end());

If you don't want to lose the original, make a copy first.

std::string sortedWord = word;
std::sort(sortedWord.begin(), sortedWord.end());

Style the first <td> column of a table differently

To select the first column of a table you can use this syntax

tr td:nth-child(1n + 2){
  padding-left: 10px;
}

bool to int conversion

You tagged your question [C] and [C++] at the same time. The results will be consistent between the languages, but the structure of the the answer is different for each of these languages.

In C language your examples has no relation to bool whatsoever (that applies to C99 as well). In C language relational operators do not produce bool results. Both 4 > 5 and 4 < 5 are expressions that produce results of type int with values 0 or 1. So, there's no "bool to int conversion" of any kind taking place in your examples in C.

In C++ relational operators do indeed produce bool results. bool values are convertible to int type, with true converting to 1 and false converting to 0. This is guaranteed by the language.

P.S. C language also has a dedicated boolean type _Bool (macro-aliased as bool), and its integral conversion rules are essentially the same as in C++. But nevertheless this is not relevant to your specific examples in C. Once again, relational operators in C always produce int (not bool) results regardless of the version of the language specification.

Inserting image into IPython notebook markdown

I am using ipython 2.0, so just two line.

from IPython.display import Image
Image(filename='output1.png')

PyCharm shows unresolved references error for valid code

Tested with PyCharm 4.0.6 (OSX 10.10.3) following this steps:

  1. Click PyCharm menu.
  2. Select Project Interpreter.
  3. Select Gear icon.
  4. Select More button.
  5. Select Project Interpreter you are in.
  6. Select Directory Tree button.
  7. Select Reload list of paths.

Problem solved!

Looping through GridView rows and Checking Checkbox Control

you have to iterate gridview Rows

for (int count = 0; count < grd.Rows.Count; count++)
{
    if (((CheckBox)grd.Rows[count].FindControl("yourCheckboxID")).Checked)
    {     
      ((Label)grd.Rows[count].FindControl("labelID")).Text
    }
}

How to check if an integer is within a range?

Using comparison operators is way, way faster than calling any function. I'm not 100% sure if this exists, but I think it doesn't.

How to POST JSON data with Python Requests?

The better way is:

url = "http://xxx.xxxx.xx"
data = {
    "cardno": "6248889874650987",
    "systemIdentify": "s08",
    "sourceChannel": 12
}
resp = requests.post(url, json=data)

How to check if type of a variable is string?

This is how I do it:

if type(x) == type(str()):

How can I recover a lost commit in Git?

Try this, This will show all commits recorded in git for a period of time

git reflog

Find the commit you want with

git log HEAD@{3}

or

git log -p HEAD@{3}    

Then check it out if it's the right one:

git checkout HEAD@{3}

This will create a detached head for that commit. Add and commit any changes if needed

git status 
git add
git commit -m "temp_work" 

Now if want to restore commit back to a branch lets say master you will need to name this branch switch to master then merge to master.

git branch temp
git checkout master
git merge temp

Here's also a link specifically for reflog on a Git tutorial site: Atlassian Git Tutorial

How to run a program in Atom Editor?

For C/C++ programs there's very good package gpp-compiler.

Shortcuts:

  • To compile and run: F5
  • To debug: F6

How to install Python MySQLdb module using pip?

Many of the given answers here are quite confusing so I will try to put it simply. It helped me to install this

pip install pymysql

and then use the following command in the python file

import pymysql as MySQLdb

This way you can use MySQLdb without any problems.

How to add leading zeros for for-loop in shell?

I'm not interested in outputting it to the screen (that's what printf is mainly used for, right?) The variable $num is going to be used as a parameter for another program but let me see what I can do with this.

You can still use printf:

for num in {1..5}
do
   value=$(printf "%02d" $num)
   ... Use $value for your purposes
done

How to clear all input fields in a specific div with jQuery?

Just had to delete all inputs within a div & using the colon in front of the input when targeting gets most everything.

$('#divId').find(':input').val('');

Javascript change color of text and background to input value

Things seems a little confused in the code in your question, so I am going to give you an example of what I think you are try to do.

First considerations are about mixing HTML, Javascript and CSS:

Why is using onClick() in HTML a bad practice?

Unobtrusive Javascript

Inline Styles vs Classes

I will be removing inline content and splitting these into their appropriate files.

Next, I am going to go with the "click" event and displose of the "change" event, as it is not clear that you want or need both.

Your function changeBackground sets both the backround color and the text color to the same value (your text will not be seen), so I am caching the color value as we don't need to look it up in the DOM twice.

CSS

#TheForm {
    margin-left: 396px;
}
#submitColor {
    margin-left: 48px;
    margin-top: 5px;
}

HTML

<form id="TheForm">
    <input id="color" type="text" />
    <br/>
    <input id="submitColor" value="Submit" type="button" />
</form>
<span id="coltext">This text should have the same color as you put in the text box</span>

Javascript

function changeBackground() {
    var color = document.getElementById("color").value; // cached

    // The working function for changing background color.
    document.bgColor = color;

    // The code I'd like to use for changing the text simultaneously - however it does not work.
    document.getElementById("coltext").style.color = color;
}

document.getElementById("submitColor").addEventListener("click", changeBackground, false);

On jsfiddle

Source: w3schools

Color Values

CSS colors are defined using a hexadecimal (hex) notation for the combination of Red, Green, and Blue color values (RGB). The lowest value that can be given to one of the light sources is 0 (hex 00). The highest value is 255 (hex FF).

Hex values are written as 3 double digit numbers, starting with a # sign.

Update: as pointed out by @Ian

Hex can be either 3 or 6 characters long

Source: W3C

Numerical color values

The format of an RGB value in hexadecimal notation is a ‘#’ immediately followed by either three or six hexadecimal characters. The three-digit RGB notation (#rgb) is converted into six-digit form (#rrggbb) by replicating digits, not by adding zeros. For example, #fb0 expands to #ffbb00. This ensures that white (#ffffff) can be specified with the short notation (#fff) and removes any dependencies on the color depth of the display.

Here is an alternative function that will check that your input is a valid CSS Hex Color, it will set the text color only or throw an alert if it is not valid.

For regex testing, I will use this pattern

/^#(?:[0-9a-f]{3}){1,2}$/i

but if you were regex matching and wanted to break the numbers into groups then you would require a different pattern

function changeBackground() {
    var color = document.getElementById("color").value.trim(),
        rxValidHex = /^#(?:[0-9a-f]{3}){1,2}$/i;

    if (rxValidHex.test(color)) {
        document.getElementById("coltext").style.color = color;
    } else {
        alert("Invalid CSS Hex Color");
    }
}

document.getElementById("submitColor").addEventListener("click", changeBackground, false);

On jsfiddle

Here is a further modification that will allow colours by name along with by hex.

function changeBackground() {
    var names = ["AliceBlue", "AntiqueWhite", "Aqua", "Aquamarine", "Azure", "Beige", "Bisque", "Black", "BlanchedAlmond", "Blue", "BlueViolet", "Brown", "BurlyWood", "CadetBlue", "Chartreuse", "Chocolate", "Coral", "CornflowerBlue", "Cornsilk", "Crimson", "Cyan", "DarkBlue", "DarkCyan", "DarkGoldenRod", "DarkGray", "DarkGrey", "DarkGreen", "DarkKhaki", "DarkMagenta", "DarkOliveGreen", "Darkorange", "DarkOrchid", "DarkRed", "DarkSalmon", "DarkSeaGreen", "DarkSlateBlue", "DarkSlateGray", "DarkSlateGrey", "DarkTurquoise", "DarkViolet", "DeepPink", "DeepSkyBlue", "DimGray", "DimGrey", "DodgerBlue", "FireBrick", "FloralWhite", "ForestGreen", "Fuchsia", "Gainsboro", "GhostWhite", "Gold", "GoldenRod", "Gray", "Grey", "Green", "GreenYellow", "HoneyDew", "HotPink", "IndianRed", "Indigo", "Ivory", "Khaki", "Lavender", "LavenderBlush", "LawnGreen", "LemonChiffon", "LightBlue", "LightCoral", "LightCyan", "LightGoldenRodYellow", "LightGray", "LightGrey", "LightGreen", "LightPink", "LightSalmon", "LightSeaGreen", "LightSkyBlue", "LightSlateGray", "LightSlateGrey", "LightSteelBlue", "LightYellow", "Lime", "LimeGreen", "Linen", "Magenta", "Maroon", "MediumAquaMarine", "MediumBlue", "MediumOrchid", "MediumPurple", "MediumSeaGreen", "MediumSlateBlue", "MediumSpringGreen", "MediumTurquoise", "MediumVioletRed", "MidnightBlue", "MintCream", "MistyRose", "Moccasin", "NavajoWhite", "Navy", "OldLace", "Olive", "OliveDrab", "Orange", "OrangeRed", "Orchid", "PaleGoldenRod", "PaleGreen", "PaleTurquoise", "PaleVioletRed", "PapayaWhip", "PeachPuff", "Peru", "Pink", "Plum", "PowderBlue", "Purple", "Red", "RosyBrown", "RoyalBlue", "SaddleBrown", "Salmon", "SandyBrown", "SeaGreen", "SeaShell", "Sienna", "Silver", "SkyBlue", "SlateBlue", "SlateGray", "SlateGrey", "Snow", "SpringGreen", "SteelBlue", "Tan", "Teal", "Thistle", "Tomato", "Turquoise", "Violet", "Wheat", "White", "WhiteSmoke", "Yellow", "YellowGreen"],
        color = document.getElementById("color").value.trim(),
        rxValidHex = /^#(?:[0-9a-f]{3}){1,2}$/i,
        formattedName = color.charAt(0).toUpperCase() + color.slice(1).toLowerCase();

    if (names.indexOf(formattedName) !== -1 || rxValidHex.test(color)) {
        document.getElementById("coltext").style.color = color;
    } else {
        alert("Invalid CSS Color");
    }
}

document.getElementById("submitColor").addEventListener("click", changeBackground, false);

On jsfiddle

I am getting an "Invalid Host header" message when connecting to webpack-dev-server remotely

If you are running webpack-dev-server in a container and are sending requests to it via its container name, you will get this error. To allow requests from other containers on the same network, simply provide the container name (or whatever name is used to resolve the container) using the --public option. This is better than disabling the security check entirely.

In my case, I was running webpack-dev-server in a container named assets with docker-compose. I changed the start command to this:

webpack-dev-server --mode development --host 0.0.0.0 --public assets

And the other container was now able to make requests via http://assets:5000.

Socket File "/var/pgsql_socket/.s.PGSQL.5432" Missing In Mountain Lion (OS X Server)

apt-get install postgres-xc-client
apt-get install postgres-xc

Run .php file in Windows Command Prompt (cmd)

you can for example: set your environment variable path with php.exe folder e.g c:\program files\php

create a script file in d:\ with filename as a.php

open cmd: go to d: drive using d: command

type following command

php -f a.php

you will see the output

Basic CSS - how to overlay a DIV with semi-transparent DIV on top

.foo {
   position : relative;
}
.foo .wrapper {
    background-image : url('semi-trans.png');
    z-index : 10;
    position : absolute;
    top : 0;
    left : 0;
}

<div class="foo">
   <img src="example.png" />
   <div class="wrapper">&nbsp;</div>
</div>

How do I check whether a file exists without exceptions?

TL;DR To quickly check the existence of a file or a folder, use the Path module. Here is a single line code (after import)!

from pathlib import Path
if Path("myfile.txt").exists(): # works for both file and folders
    # do stuffs...

The pathlib module was introduced in Python 3.4, so you need to have Python 3.4+, this lib makes your life much easier and it is pretty to use, here is more doc about it (https://docs.python.org/3/library/pathlib.html).

BTW, if you are going to reuse the path, then it is better to assign it to a variable

so will become

from pathlib import Path
p = Path("loc/of/myfile.txt")
if p.exists(): # works for both file and folders
    # do stuffs...

Kotlin Error : Could not find org.jetbrains.kotlin:kotlin-stdlib-jre7:1.0.7

This is what worked for me: Using Gradle 4.8.1

buildscript {
    ext.kotlin_version = '1.1.1' 
repositories {
    jcenter()
    google()
}
dependencies {
    classpath 'com.android.tools.build:gradle:3.1.0'}
}
allprojects {
    repositories {
        mavenLocal()
        jcenter()
        google()
        maven {
            url "$rootDir/../node_modules/react-native/android"
        }
    maven {
            url 'https://dl.bintray.com/kotlin/kotlin-dev/'
    }
  }
}   

"Conversion to Dalvik format failed with error 1" on external JAR

I cleaned my main App Project AND the Android Library Project which it uses. Solved the issue

Recursive query in SQL Server

Something like this (not tested)

with match_groups as (

  select product_id, 
         matching_product_id,
         product_id as group_id
  from matches
  where product_id not in (select matching_product_id from matches)

  union all

  select m.product_id, m.matching_product_id, p.group_id
  from matches m
    join match_groups p on m.product_id = p.matching_product_id
)
select group_id, product_id
from match_groups
order by group_id;

How do you follow an HTTP Redirect in Node.js?

Update:

Now you can follow all redirects with var request = require('request'); using the followAllRedirects param.

request({
  followAllRedirects: true,
  url: url
}, function (error, response, body) {
  if (!error) {
    console.log(response);
  }
});

Zoom to fit: PDF Embedded in HTML

This method uses "object", it also has "embed". Either method works:

<div id="pdf">
    <object id="pdf_content" width="100%" height="1500px" type="application/pdf" trusted="yes" application="yes" title="Assembly" data="Assembly.pdf?#zoom=100&scrollbar=1&toolbar=1&navpanes=1">
    <!-- <embed src="Assembly.pdf" width="100%" height="100%" type="application/x-pdf" trusted="yes" application="yes" title="Assembly">
    </embed> -->
    <p>System Error - This PDF cannot be displayed, please contact IT.</p>
    </object>
</div>

Does Java support structs?

Actually a struct in C++ is a class (e.g. you can define methods there, it can be extended, it works exactly like a class), the only difference is that the default access modfiers are set to public (for classes they are set to private by default).

This is really the only difference in C++, many people don't know that. ; )

MVC Razor @foreach

The answer will not work when using the overload to indicate the template @Html.DisplayFor(x => x.Foos, "YourTemplateName) .

Seems to be designed that way, see this case. Also the exception the framework gives (about the type not been as expected) is quite misleading and fooled me on the first try (thanks @CodeCaster)

In this case you have to use @foreach

@foreach (var item in Model.Foos)
{
    @Html.DisplayFor(x => item, "FooTemplate")
}

Transposing a 1D NumPy array

For 1D arrays:

a = np.array([1, 2, 3, 4])
a = a.reshape((-1, 1)) # <--- THIS IS IT

print a
array([[1],
       [2],
       [3],
       [4]])

Once you understand that -1 here means "as many rows as needed", I find this to be the most readable way of "transposing" an array. If your array is of higher dimensionality simply use a.T.

Get the selected value in a dropdown using jQuery.

Try:

jQuery("#availability option:selected").val();

Or to get the text of the option, use text():

jQuery("#availability option:selected").text();

More Info:

java.net.UnknownHostException: Unable to resolve host "<url>": No address associated with hostname and End of input at character 0 of

I had the same problem. java.net.UnknownHostException: Unable to resolve host “”...

I'm running Visual Studio 2019 and Xamarin.

I also switched back to my WiFi but was on a hot spot.

I solved this by clean swiping the emulator. Restore to factory settings. Then re-running visual studio xamarin app which wil redeploy your app again to the fresh emulator.

It worked. I thought I was going to battle for days to solve this. Luckily this post pointed me in the right direction.

I could not understand how it worked perfectly before and then stopped with no code change.

This is my code for reference:

using var response = await httpClient.GetAsync(sb.ToString());
string apiResponse = await response.Content.ReadAsStringAsync();

Can Mockito capture arguments of a method called multiple times?

First of all: you should always import mockito static, this way the code will be much more readable (and intuitive) - the code samples below require it to work:

import static org.mockito.Mockito.*;

In the verify() method you can pass the ArgumentCaptor to assure execution in the test and the ArgumentCaptor to evaluate the arguments:

ArgumentCaptor<MyExampleClass> argument = ArgumentCaptor.forClass(MyExampleClass.class);
verify(yourmock, atleast(2)).myMethod(argument.capture());

List<MyExampleClass> passedArguments = argument.getAllValues();

for (MyExampleClass data : passedArguments){
    //assertSometing ...
    System.out.println(data.getFoo());
}

The list of all passed arguments during your test is accessible via the argument.getAllValues() method.

The single (last called) argument's value is accessible via the argument.getValue() for further manipulation / checking or whatever you wish to do.

The differences between initialize, define, declare a variable

"So does it mean definition equals declaration plus initialization."

Not necessarily, your declaration might be without any variable being initialized like:

 void helloWorld(); //declaration or Prototype.

 void helloWorld()
 {
    std::cout << "Hello World\n";
 } 

How to detect READ_COMMITTED_SNAPSHOT is enabled?

SELECT is_read_committed_snapshot_on FROM sys.databases 
WHERE name= 'YourDatabase'

Return value:

  • 1: READ_COMMITTED_SNAPSHOT option is ON. Read operations under the READ COMMITTED isolation level are based on snapshot scans and do not acquire locks.
  • 0 (default): READ_COMMITTED_SNAPSHOT option is OFF. Read operations under the READ COMMITTED isolation level use Shared (S) locks.

Batch file to move files to another directory

/q isn't a valid parameter. /y: Suppresses prompting to confirm overwriting

Also ..\txt means directory txt under the parent directory, not the root directory. The root directory would be: \ And please mention the error you get

Try:

move files\*.txt \ 

Edit: Try:

move \files\*.txt \ 

Edit 2:

move C:\files\*.txt C:\txt

ERROR 1064 (42000): You have an error in your SQL syntax; Want to configure a password as root being the user

On MySQL 8.0.15 (maybe earlier than this too): the PASSWORD() function does not work anymore, so you have to do:

Make sure you have stopped MySQL first (Go to: 'System Preferences' >> 'MySQL' and stop MySQL).

Run the server in safe mode with privilege bypass:

sudo mysqld_safe --skip-grant-tables
mysql -u root
UPDATE mysql.user SET authentication_string=null WHERE User='root';
FLUSH PRIVILEGES;
exit;

Then

mysql -u root
ALTER USER 'root'@'localhost' IDENTIFIED WITH caching_sha2_password BY 'yourpasswd';

Finally, start your MySQL again.

Enlighten by @OlatunjiYso in this GitHub issue.

Generating Random Number In Each Row In Oracle Query

At first I thought that this would work:

select DBMS_Random.Value(1,9) output
from   ...

However, this does not generate an even distribution of output values:

select output,
       count(*)
from   (
       select round(dbms_random.value(1,9)) output
       from   dual
       connect by level <= 1000000)
group by output
order by 1

1   62423
2   125302
3   125038
4   125207
5   124892
6   124235
7   124832
8   125514
9   62557

The reasons are pretty obvious I think.

I'd suggest using something like:

floor(dbms_random.value(1,10))

Hence:

select output,
       count(*)
from   (
       select floor(dbms_random.value(1,10)) output
       from   dual
       connect by level <= 1000000)
group by output
order by 1

1   111038
2   110912
3   111155
4   111125
5   111084
6   111328
7   110873
8   111532
9   110953

Array vs ArrayList in performance

From here:

ArrayList is internally backed by Array in Java, any resize operation in ArrayList will slow down performance as it involves creating new Array and copying content from old array to new array.


In terms of performance Array and ArrayList provides similar performance in terms of constant time for adding or getting element if you know index. Though automatic resize of ArrayList may slow down insertion a bit Both Array and ArrayList is core concept of Java and any serious Java programmer must be familiar with these differences between Array and ArrayList or in more general Array vs List.

Best way to parseDouble with comma as decimal separator?

In the case where you don't know the locale of the string value received and it is not necessarily the same locale as the current default locale you can use this :

private static double parseDouble(String price){
    String parsedStringDouble;
    if (price.contains(",") && price.contains(".")){
        int indexOfComma = price.indexOf(",");
        int indexOfDot = price.indexOf(".");
        String beforeDigitSeparator;
        String afterDigitSeparator;
        if (indexOfComma < indexOfDot){
            String[] splittedNumber = price.split("\\.");
            beforeDigitSeparator = splittedNumber[0];
            afterDigitSeparator = splittedNumber[1];
        }
        else {
            String[] splittedNumber = price.split(",");
            beforeDigitSeparator = splittedNumber[0];
            afterDigitSeparator = splittedNumber[1];
        }
        beforeDigitSeparator = beforeDigitSeparator.replace(",", "").replace(".", "");
        parsedStringDouble = beforeDigitSeparator+"."+afterDigitSeparator;
    }
    else {
        parsedStringDouble = price.replace(",", "");
    }

    return Double.parseDouble(parsedStringDouble);

}

It will return a double no matter what the locale of the string is. And no matter how many commas or points there are. So passing 1,000,000.54 will work so will 1.000.000,54 so you don't have to rely on the default locale for parsing the string anymore. The code isn't as optimized as it can be so any suggestions are welcome. I tried to test most of the cases to make sure it solves the problem but I am not sure it covers all. If you find a breaking value let me know.

Why doesn't the height of a container element increase if it contains floated elements?

Its because of the float of the div. Add overflow: hidden on the outside element.

<div style="overflow:hidden; margin:0 auto;width: 960px; min-height: 100px; background-color:orange;">
    <div style="width:500px; height:200px; background-color:black; float:right">
    </div>
</div>

Demo

Angular 1 - get current URL parameters

To get parameters from URL with ngRoute . It means that you will need to include angular-route.js in your application as a dependency. More information how to do this on official ngRoute documentation.

The solution for the question:

// You need to add 'ngRoute' as a dependency in your app
angular.module('ngApp', ['ngRoute'])
    .config(function ($routeProvider, $locationProvider) {
        // configure the routing rules here
        $routeProvider.when('/backend/:type/:id', {
            controller: 'PagesCtrl'
        });

        // enable HTML5mode to disable hashbang urls
        $locationProvider.html5Mode(true);
    })
    .controller('PagesCtrl', function ($routeParams) {
        console.log($routeParams.id, $routeParams.type);
    });

If you don't enable the $locationProvider.html5Mode(true);. Urls will use hashbang(/#/).

More information about routing can be found on official angular $route API documentation.


Side note: This question is answering how to achieve this using ng-Route however I would recommend using the ui-Router for routing. It is more flexible, offers more functionality, the documentations is great and it is considered the best routing library for angular.

How to replace NaNs by preceding values in pandas DataFrame?

In my case, we have time series from different devices but some devices could not send any value during some period. So we should create NA values for every device and time period and after that do fillna.

df = pd.DataFrame([["device1", 1, 'first val of device1'], ["device2", 2, 'first val of device2'], ["device3", 3, 'first val of device3']])
df.pivot(index=1, columns=0, values=2).fillna(method='ffill').unstack().reset_index(name='value')

Result:

        0   1   value
0   device1     1   first val of device1
1   device1     2   first val of device1
2   device1     3   first val of device1
3   device2     1   None
4   device2     2   first val of device2
5   device2     3   first val of device2
6   device3     1   None
7   device3     2   None
8   device3     3   first val of device3

Read all files in a folder and apply a function to each data frame

usually i don't use for loop in R, but here is my solution using for loops and two packages : plyr and dostats

plyr is on cran and you can download dostats on https://github.com/halpo/dostats (may be using install_github from Hadley devtools package)

Assuming that i have your first two data.frame (Df.1 and Df.2) in csv files, you can do something like this.

require(plyr)
require(dostats)

files <- list.files(pattern = ".csv")


for (i in seq_along(files)) {

    assign(paste("Df", i, sep = "."), read.csv(files[i]))

    assign(paste(paste("Df", i, sep = ""), "summary", sep = "."), 
           ldply(get(paste("Df", i, sep = ".")), dostats, sum, min, mean, median, max))

}

Here is the output

R> Df1.summary
  .id sum min   mean median max
1   A  34   4 5.6667    5.5   8
2   B  22   1 3.6667    3.0   9
R> Df2.summary
  .id sum min   mean median max
1   A  21   1 3.5000    3.5   6
2   B  16   1 2.6667    2.5   5

How to convert Blob to String and String to Blob in java

try this (a2 is BLOB col)

PreparedStatement ps1 = conn.prepareStatement("update t1 set a2=? where id=1");
Blob blob = conn.createBlob();
blob.setBytes(1, str.getBytes());
ps1.setBlob(1, blob);
ps1.executeUpdate();

it may work even without BLOB, driver will transform types automatically:

   ps1.setBytes(1, str.getBytes);
   ps1.setString(1, str);

Besides if you work with text CLOB seems to be a more natural col type

Eclipse returns error message "Java was started but returned exit code = 1"

I had this issue recently, but I hadn't changed any java or updated the java version, May be this issue happened because of crash shutdown of the system.

And after reading a couple of answers here I decided to change the java version from 1.6 to 1.7 in the eclipse.ini file.

-vmargs
-Dosgi.requiredJavaVersion=1.6  

After this change the Eclipse started well and it worked. Since I didnt had changed anything i decided to change it back to 1.6 to what it was originally.

Then I started eclipse and guess what it worked. So Looks like in my case just touching/modifiying the eclipse.ini file worked.

I hope this answer is helpful to somebody.

RestSharp simple complete example

Pawel Sawicz .NET blog has a real good explanation and example code, explaining how to call the library;

GET:

var client = new RestClient("192.168.0.1");
var request = new RestRequest("api/item/", Method.GET);
var queryResult = client.Execute<List<Items>>(request).Data;

POST:

var client = new RestClient("http://192.168.0.1");
var request = new RestRequest("api/item/", Method.POST);
request.RequestFormat = DataFormat.Json;
request.AddBody(new Item
{
   ItemName = someName,
   Price = 19.99
});
client.Execute(request);

DELETE:

var item = new Item(){//body};
var client = new RestClient("http://192.168.0.1");
var request = new RestRequest("api/item/{id}", Method.DELETE);
request.AddParameter("id", idItem);
 
client.Execute(request)

The RestSharp GitHub page has quite an exhaustive sample halfway down the page. To get started install the RestSharp NuGet package in your project, then include the necessary namespace references in your code, then above code should work (possibly negating your need for a full example application).

NuGet RestSharp

How to remove all the occurrences of a char in c++ string

I guess the method std:remove works but it was giving some compatibility issue with the includes so I ended up writing this little function:

string removeCharsFromString(const string str, char* charsToRemove )
{
    char c[str.length()+1]; // + terminating char
    const char *p = str.c_str();
    unsigned int z=0, size = str.length();
    unsigned int x;
    bool rem=false;

    for(x=0; x<size; x++)
    {
        rem = false;
        for (unsigned int i = 0; charsToRemove[i] != 0; i++)
        {
            if (charsToRemove[i] == p[x])
            {
                rem = true;
                break;
            }
        }
        if (rem == false) c[z++] = p[x];
    }

    c[z] = '\0';
    return string(c);
}

Just use as

myString = removeCharsFromString(myString, "abc\r");

and it will remove all the occurrence of the given char list.

This might also be a bit more efficient as the loop returns after the first match, so we actually do less comparison.

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

The reason for this error is very simple. Your AJAX is trying to call over HTTP whereas your server is running over HTTPS, so your server is denying calling your AJAX. This can be fixed by adding the following line inside the head tag of your main HTML file:

<meta http-equiv="Content-Security-Policy" content="upgrade-insecure-requests"> 

Convert string to decimal, keeping fractions

The value is the same even though the printed representation is not what you expect:

decimal d = (decimal )1200.00;
Console.WriteLine(Decimal.Parse("1200") == d); //True

Storing Images in PostgreSQL

Update from 10 years later In 2008 the hard drives you would run a database on would have much different characteristics and much higher cost than the disks you would store files on. These days there are much better solutions for storing files that didn't exist 10 years ago and I would revoke this advice and advise readers to look at some of the other answers in this thread.

Original

Don't store in images in the database unless you absolutely have to. I understand that this is not a web application, but if there isn't a shared file location that you can point to save the location of the file in the database.

//linuxserver/images/imagexxx.jpg

then perhaps you can quickly set up a webserver and store the web urls in the database (as well as the local path). While databases can handle LOB's and 3000 images (4-6 Megapixels, assuming 500K an image) 1.5 Gigs isn't a lot of space file systems are much better designed for storing large files than a database is.

Bootstrap Navbar toggle button not working

Wasted several hours only to realize that viewport meta was missing from my code. Adding here just in case some one else misses it out.

As soon as I added this, the toggle started working fine.

<meta name="viewport" content="width=device-width, initial-scale=1">

Get all column names of a DataTable into string array using (LINQ/Predicate)

List<String> lsColumns = new List<string>();

if(dt.Rows.Count>0)
{
    var count = dt.Rows[0].Table.Columns.Count;

    for (int i = 0; i < count;i++ )
    {
        lsColumns.Add(Convert.ToString(dt.Rows[0][i]));
    }
}

What does this symbol mean in IntelliJ? (red circle on bottom-left corner of file name, with 'J' in it)

First mark the directory as the source root. Then go to the pom excel and right click on it. select add as maven project .

How to support placeholder attribute in IE8 and 9

I use thisone, it's only Javascript.

I simply have an input element with a value, and when the user clicks on the input element, it changes it to an input element without a value.

You can easily change the color of the text using CSS. The color of the placeholder is the color in the id #IEinput, and the color your typed text will be is the color in the id #email. Don't use getElementsByClassName, because the versions of IE that don't support a placeholder, don't support getElementsByClassName either!

You can use a placeholder in a password input by setting the type of the original password input to text.

Tinker: http://tinker.io/4f7c5/1 - JSfiddle servers are down!

*sorry for my bad english

JAVASCRIPT

function removeValue() {
    document.getElementById('mailcontainer')
        .innerHTML = "<input id=\"email\" type=\"text\" name=\"mail\">";
    document.getElementById('email').focus(); }

HTML

<span id="mailcontainer">
    <input id="IEinput" onfocus="removeValue()" type="text" name="mail" value="mail">
</span>

Inheritance with base class constructor with parameters

The problem is that the base class foo has no parameterless constructor. So you must call constructor of the base class with parameters from constructor of the derived class:

public bar(int a, int b) : base(a, b)
{
    c = a * b;
}

getCurrentPosition() and watchPosition() are deprecated on insecure origins

Use FireFox or any other browser instead of Chrome if you want to test it on your development environment, for production there is no way except using https.

For development environment just open http://localhost:8100/ on FireFox and alas no such error.

How to set variable from a SQL query?

I prefer just setting it from the declare statement

DECLARE @ModelID uniqueidentifer = (SELECT modelid 
                                    FROM models
                                    WHERE areaid = 'South Coast')

Enter key press behaves like a Tab in Javascript

Easiest way to solve this problem with the focus function of JavaScript as follows:

You can copy and try it @ home!

<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title></title>
  </head>
  <body>

    <input id="input1" type="text" onkeypress="pressEnter()" />
    <input id="input2" type="text" onkeypress="pressEnter2()" />
    <input id="input3" type="text"/>

    <script type="text/javascript">
    function pressEnter() {
      // Key Code for ENTER = 13
      if ((event.keyCode == 13)) {
        document.getElementById("input2").focus({preventScroll:false});
      }
    }
    function pressEnter2() {
      if ((event.keyCode == 13)) {
        document.getElementById("input3").focus({preventScroll:false});
      }
    }
    </script>

  </body>
</html>

Undefined index with $_POST

Related question: What is the best way to access unknown array elements without generating PHP notice?

Using the answer from the question above, you can safely get a value from $_POST without generating PHP notice if the key does not exists.

echo _arr($_POST, 'username', 'no username supplied');  
// will print $_POST['username'] or 'no username supplied'

Is there an equivalent to background-size: cover and contain for image elements?

Solution #1 - The object-fit property (Lacks IE support)

Just set object-fit: cover; on the img .

_x000D_
_x000D_
body {
  margin: 0;
}
img {
  display: block;
  width: 100vw;
  height: 100vh;
  object-fit: cover; /* or object-fit: contain; */
}
_x000D_
<img src="http://lorempixel.com/1500/1000" />
_x000D_
_x000D_
_x000D_

See MDN - regarding object-fit: cover:

The replaced content is sized to maintain its aspect ratio while filling the element’s entire content box. If the object's aspect ratio does not match the aspect ratio of its box, then the object will be clipped to fit.

And for object-fit: contain:

The replaced content is scaled to maintain its aspect ratio while fitting within the element’s content box. The entire object is made to fill the box, while preserving its aspect ratio, so the object will be "letterboxed" if its aspect ratio does not match the aspect ratio of the box.

Also, see this Codepen demo which compares object-fit: cover applied to an image with background-size: cover applied to a background image


Solution #2 - Replace the img with a background image with css

_x000D_
_x000D_
body {
  margin: 0;
}
img {
  position: fixed;
  width: 0;
  height: 0;
  padding: 50vh 50vw;
  background: url(http://lorempixel.com/1500/1000/city/Dummy-Text) no-repeat;
  background-size: cover;
}
_x000D_
<img src="http://placehold.it/1500x1000" />
_x000D_
_x000D_
_x000D_

What is the preferred/idiomatic way to insert into a map?

The first version:

function[0] = 42; // version 1

may or may not insert the value 42 into the map. If the key 0 exists, then it will assign 42 to that key, overwriting whatever value that key had. Otherwise it inserts the key/value pair.

The insert functions:

function.insert(std::map<int, int>::value_type(0, 42));  // version 2
function.insert(std::pair<int, int>(0, 42));             // version 3
function.insert(std::make_pair(0, 42));                  // version 4

on the other hand, don't do anything if the key 0 already exists in the map. If the key doesn't exist, it inserts the key/value pair.

The three insert functions are almost identical. std::map<int, int>::value_type is the typedef for std::pair<const int, int>, and std::make_pair() obviously produces a std::pair<> via template deduction magic. The end result, however, should be the same for versions 2, 3, and 4.

Which one would I use? I personally prefer version 1; it's concise and "natural". Of course, if its overwriting behavior is not desired, then I would prefer version 4, since it requires less typing than versions 2 and 3. I don't know if there is a single de facto way of inserting key/value pairs into a std::map.

Another way to insert values into a map via one of its constructors:

std::map<int, int> quadratic_func;

quadratic_func[0] = 0;
quadratic_func[1] = 1;
quadratic_func[2] = 4;
quadratic_func[3] = 9;

std::map<int, int> my_func(quadratic_func.begin(), quadratic_func.end());

What does the "On Error Resume Next" statement do?

It basically tells the program when you encounter an error just continue at the next line.

Wait 5 seconds before executing next line

You really shouldn't be doing this, the correct use of timeout is the right tool for the OP's problem and any other occasion where you just want to run something after a period of time. Joseph Silber has demonstrated that well in his answer. However, if in some non-production case you really want to hang the main thread for a period of time, this will do it.

function wait(ms){
   var start = new Date().getTime();
   var end = start;
   while(end < start + ms) {
     end = new Date().getTime();
  }
}

With execution in the form:

console.log('before');
wait(7000);  //7 seconds in milliseconds
console.log('after');

I've arrived here because I was building a simple test case for sequencing a mix of asynchronous operations around long-running blocking operations (i.e. expensive DOM manipulation) and this is my simulated blocking operation. It suits that job fine, so I thought I post it for anyone else who arrives here with a similar use case. Even so, it's creating a Date() object in a while loop, which might very overwhelm the GC if it runs long enough. But I can't emphasize enough, this is only suitable for testing, for building any actual functionality you should refer to Joseph Silber's answer.

Enforcing the type of the indexed members of a Typescript object?

Define interface

interface Settings {
  lang: 'en' | 'da';
  welcome: boolean;
}

Enforce key to be a specific key of Settings interface

private setSettings(key: keyof Settings, value: any) {
   // Update settings key
}

How do I drop a function if it already exists?

You have two options to drop and recreate the procedure in SQL Server 2016.

Starting from SQL Server 2016 - use IF EXISTS

DROP FUNCTION [ IF EXISTS ] { [ schema_name. ] function_name } [ ,...n ]   [;]

Starting from SQL Server 2016 SP1 - use OR ALTER

CREATE [ OR ALTER ] FUNCTION [ schema_name. ] function_name   

How to connect to LocalDB in Visual Studio Server Explorer?

OK, answering to my own question.

Steps to connect LocalDB to Visual Studio Server Explorer

  1. Open command prompt
  2. Run SqlLocalDB.exe start v11.0
  3. Run SqlLocalDB.exe info v11.0
  4. Copy the Instance pipe name that starts with np:\...
  5. In Visual Studio select TOOLS > Connect to Database...
  6. For Server Name enter (localdb)\v11.0. If it didn't work, use the Instance pipe name that you copied earlier. You can also use this to connect with SQL Management Studio.
  7. Select the database on next dropdown list
  8. Click OK

enter image description here

Convert base64 string to image

In the server, do something like this:

Suppose

String data = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAPAAAADwCAYAAAA+VemSAAAgAEl...=='

Then:

String base64Image = data.split(",")[1];
byte[] imageBytes = javax.xml.bind.DatatypeConverter.parseBase64Binary(base64Image);

Then you can do whatever you like with the bytes like:

BufferedImage img = ImageIO.read(new ByteArrayInputStream(imageBytes));

Initialize empty vector in structure - c++

The default vector constructor will create an empty vector. As such, you should be able to write:

struct user r = { string(), vector<unsigned char>() };

Note, I've also used the default string constructor instead of "".

You might want to consider making user a class and adding a default constructor that does this for you:

class User {
  User() {}
  string username;
  vector<unsigned char> password;
};

Then just writing:

User r;

Will result in a correctly initialized user.

Date query with ISODate in mongodb doesn't seem to work

Old question, but still first google hit, so i post it here so i find it again more easily...

Using Mongo 4.2 and an aggregate():

db.collection.aggregate(
    [
     { $match: { "end_time": { "$gt": ISODate("2020-01-01T00:00:00.000Z")  } } },
     { $project: {
          "end_day": { $dateFromParts: { 'year' : {$year:"$end_time"}, 'month' : {$month:"$end_time"}, 'day': {$dayOfMonth:"$end_time"}, 'hour' : 0  } }
     }}, 
     {$group:{
        _id:   "$end_day",
        "count":{$sum:1},
    }}
   ]
)

This one give you the groupby variable as a date, sometimes better to hande as the components itself.

The listener supports no services

You need to add your ORACLE_HOME definition in your listener.ora file. Right now its not registered with any ORACLE_HOME.

Sample listener.ora

abc =
  (DESCRIPTION_LIST =
    (DESCRIPTION =
      (ADDRESS = (PROTOCOL = TCP)(HOST = abc.kma.com)(PORT = 1521))
    )
  )

SID_LIST_abc =
  (SID_LIST =
    (SID_DESC =
      (ORACLE_HOME= /abc/DbTier/11.2.0)
      (SID_NAME = abc)
    )
  )

Apache default VirtualHost

The NameVirtualHost option would be a good option.

PHP append one array to another (not array_push or +)

foreach loop is faster than array_merge to append values to an existing array, so choose the loop instead if you want to add an array to the end of another.

// Create an array of arrays
$chars = [];
for ($i = 0; $i < 15000; $i++) {
    $chars[] = array_fill(0, 10, 'a');
}

// test array_merge
$new = [];
$start = microtime(TRUE);
foreach ($chars as $splitArray) {
    $new = array_merge($new, $splitArray);
}
echo microtime(true) - $start; // => 14.61776 sec

// test foreach
$new = [];
$start = microtime(TRUE);
foreach ($chars as $splitArray) {
    foreach ($splitArray as $value) {
        $new[] = $value;
    }
}
echo microtime(true) - $start; // => 0.00900101 sec
// ==> 1600 times faster

How to store arbitrary data for some HTML tags

As long as you're actual work is done serverside, why would you need custom information in the html tags in the output anyway? all you need to know back on the server is an index into whatever kind of list of structures with your custom info. I think you're looking to store the information in the wrong place.

I will recognize, however unfortunate, that in lots of cases the right solution isn't the right solution. In which case I would strongly suggest generating some javascript to hold the extra information.

Many years later:

This question was posted roughly three years before data-... attributes became a valid option with the advent of html 5 so the truth has shifted and the original answer I gave is no longer relevant. Now I'd suggest to use data attributes instead.

<a data-articleId="5" href="link/for/non-js-users.html">

<script>
    let anchors = document.getElementsByTagName('a');
    for (let anchor of anchors) {
        let articleId = anchor.dataset.articleId;
    }
</script>

How do I create a HTTP Client Request with a cookie?

This answer is deprecated, please see @ankitjaininfo's answer below for a more modern solution


Here's how I think you make a POST request with data and a cookie using just the node http library. This example is posting JSON, set your content-type and content-length accordingly if you post different data.

// NB:- node's http client API has changed since this was written
// this code is for 0.4.x
// for 0.6.5+ see http://nodejs.org/docs/v0.6.5/api/http.html#http.request

var http = require('http');

var data = JSON.stringify({ 'important': 'data' });
var cookie = 'something=anything'

var client = http.createClient(80, 'www.example.com');

var headers = {
    'Host': 'www.example.com',
    'Cookie': cookie,
    'Content-Type': 'application/json',
    'Content-Length': Buffer.byteLength(data,'utf8')
};

var request = client.request('POST', '/', headers);

// listening to the response is optional, I suppose
request.on('response', function(response) {
  response.on('data', function(chunk) {
    // do what you do
  });
  response.on('end', function() {
    // do what you do
  });
});
// you'd also want to listen for errors in production

request.write(data);

request.end();

What you send in the Cookie value should really depend on what you received from the server. Wikipedia's write-up of this stuff is pretty good: http://en.wikipedia.org/wiki/HTTP_cookie#Cookie_attributes

How to use environment variables in docker compose

add env to .env file

Such as

VERSION=1.0.0

then save it to deploy.sh

INPUTFILE=docker-compose.yml
RESULT_NAME=docker-compose.product.yml
NAME=test

prepare() {
        local inFile=$(pwd)/$INPUTFILE
        local outFile=$(pwd)/$RESULT_NAME
        cp $inFile $outFile
        while read -r line; do
            OLD_IFS="$IFS"
            IFS="="
            pair=($line)
            IFS="$OLD_IFS"
               sed -i -e "s/\${${pair[0]}}/${pair[1]}/g" $outFile
            done <.env
     }
       
deploy() {
        docker stack deploy -c $outFile $NAME
}

        
prepare
deploy
    

Get the current date and time

Get Current DateTime

Now.ToShortDateString()
DateTime.Now
Today.Now

How to use apply a custom drawable to RadioButton?

Give your radiobutton a custom style:

<style name="MyRadioButtonStyle" parent="@android:style/Widget.CompoundButton.RadioButton">
    <item name="android:button">@drawable/custom_btn_radio</item>
</style>

custom_btn_radio.xml

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_checked="true" android:state_window_focused="false"
          android:drawable="@drawable/btn_radio_on" />
    <item android:state_checked="false" android:state_window_focused="false"
          android:drawable="@drawable/btn_radio_off" />

    <item android:state_checked="true" android:state_pressed="true"
          android:drawable="@drawable/btn_radio_on_pressed" />
    <item android:state_checked="false" android:state_pressed="true"
          android:drawable="@drawable/btn_radio_off_pressed" />

    <item android:state_checked="true" android:state_focused="true"
          android:drawable="@drawable/btn_radio_on_selected" />
    <item android:state_checked="false" android:state_focused="true"
          android:drawable="@drawable/btn_radio_off_selected" />

    <item android:state_checked="false" android:drawable="@drawable/btn_radio_off" />
    <item android:state_checked="true" android:drawable="@drawable/btn_radio_on" />
</selector>

Replace the drawables with your own.

C++: Where to initialize variables in constructor

In short, always prefer initialization lists when possible. 2 reasons:

  • If you do not mention a variable in a class's initialization list, the constructor will default initialize it before entering the body of the constructor you've written. This means that option 2 will lead to each variable being written to twice, once for the default initialization and once for the assignment in the constructor body.

  • Also, as mentioned by mwigdahl and avada in other answers, const members and reference members can only be initialized in an initialization list.

Also note that variables are always initialized on the order they are declared in the class declaration, not in the order they are listed in an initialization list (with proper warnings enabled a compiler will warn you if a list is written out of order). Similarly, destructors will call member destructors in the opposite order, last to first in the class declaration, after the code in your class's destructor has executed.

How to put attributes via XElement

Add XAttribute in the constructor of the XElement, like

new XElement("Conn", new XAttribute("Server", comboBox1.Text));

You can also add multiple attributes or elements via the constructor

new XElement("Conn", new XAttribute("Server", comboBox1.Text), new XAttribute("Database", combobox2.Text));

or you can use the Add-Method of the XElement to add attributes

XElement element = new XElement("Conn");
XAttribute attribute = new XAttribute("Server", comboBox1.Text);
element.Add(attribute);

Oracle: How to filter by date and time in a where clause

Try:

To_Date (SESSION_START_DATE_TIME, 'MM/DD/YYYY hh24:mi') > 
To_Date ('12-Jan-2012 16:00', 'DD-MON-YYYY hh24:mi' )

git commit error: pathspec 'commit' did not match any file(s) known to git

Please try adding the double quotes git commit -m "initial commit". This will solve your problem.

Problems when trying to load a package in R due to rJava

I had a similar problem what worked for me was to set JAVA_HOME. I tired it first in R:

Sys.setenv(JAVA_HOME = "C:/Program Files/Java/jdk1.8.0_101/")

And when it actually worked I set it in

System Properties -> Advanced -> Environment Variables

by adding a new System variable. I then restarted R/RStudio and everything worked.

How can I set the focus (and display the keyboard) on my EditText programmatically

I finally figured out a solution and create a Kotlin class for it

object KeyboardUtils {

    fun showKeyboard(editText: EditText) {
        editText.requestFocus()
        val imm = editText.context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
        imm.showSoftInput(editText, 0)
    }

    fun hideKeyboard(editText: EditText) {
        val imm = editText.context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
        imm.hideSoftInputFromWindow(editText.windowToken, 0)
    }

}

Apply CSS styles to an element depending on its child elements

As far as I'm aware, styling a parent element based on the child element is not an available feature of CSS. You'll likely need scripting for this.

It'd be wonderful if you could do something like div[div.a] or div:containing[div.a] as you said, but this isn't possible.

You may want to consider looking at jQuery. Its selectors work very well with 'containing' types. You can select the div, based on its child contents and then apply a CSS class to the parent all in one line.

If you use jQuery, something along the lines of this would may work (untested but the theory is there):

$('div:has(div.a)').css('border', '1px solid red');

or

$('div:has(div.a)').addClass('redBorder');

combined with a CSS class:

.redBorder
{
    border: 1px solid red;
}

Here's the documentation for the jQuery "has" selector.

How to write a Unit Test?

This is a very generic question and there is a lot of ways it can be answered.

If you want to use JUnit to create the tests, you need to create your testcase class, then create individual test methods that test specific functionality of your class/module under tests (single testcase classes are usually associated with a single "production" class that is being tested) and inside these methods execute various operations and compare the results with what would be correct. It is especially important to try and cover as many corner cases as possible.

In your specific example, you could for example test the following:

  1. A simple addition between two positive numbers. Add them, then verify the result is what you would expect.
  2. An addition between a positive and a negative number (which returns a result with the sign of the first argument).
  3. An addition between a positive and a negative number (which returns a result with the sign of the second argument).
  4. An addition between two negative numbers.
  5. An addition that results in an overflow.

To verify the results, you can use various assertXXX methods from the org.junit.Assert class (for convenience, you can do 'import static org.junit.Assert.*'). These methods test a particular condition and fail the test if it does not validate (with a specific message, optionally).

Example testcase class in your case (without the methods contents defined):

import static org.junit.Assert.*;

public class AdditionTests {
    @Test
    public void testSimpleAddition() { ... }


    @Test
    public void testPositiveNegativeAddition() { ... }


    @Test
    public void testNegativePositiveAddition() { ... }


    @Test
    public void testNegativeAddition() { ... }


    @Test
    public void testOverflow() { ... }
}

If you are not used to writing unit tests but instead test your code by writing ad-hoc tests that you then validate "visually" (for example, you write a simple main method that accepts arguments entered using the keyboard and then prints out the results - and then you keep entering values and validating yourself if the results are correct), then you can start by writing such tests in the format above and validating the results with the correct assertXXX method instead of doing it manually. This way, you can re-run the test much easier then if you had to do manual tests.

MongoDB: How To Delete All Records Of A Collection in MongoDB Shell?

The argument to remove() is a filter document, so passing in an empty document means 'remove all':

db.user.remove({})

However, if you definitely want to remove everything you might be better off dropping the collection. Though that probably depends on whether you have user defined indexes on the collection i.e. whether the cost of preparing the collection after dropping it outweighs the longer duration of the remove() call vs the drop() call.

More details in the docs.

Can the jQuery UI Datepicker be made to disable Saturdays and Sundays (and holidays)?

$("#selector").datepicker({ beforeShowDay: highlightDays });

...

var dates = [new Date("1/1/2011"), new Date("1/2/2011")];

function highlightDays(date) {

    for (var i = 0; i < dates.length; i++) {
        if (date - dates[i] == 0) {
            return [true,'', 'TOOLTIP'];
        }
    }
    return [false];

}

batch file to copy files to another location?

@echo off
xcopy ...

Replace ... with the appropriate xcopy arguments to copy what you want copied.

Phone number formatting an EditText in Android

Maybe below sample project helps you;

https://github.com/reinaldoarrosi/MaskedEditText

That project contains a view class call MaskedEditText. As first, you should add it in your project.

Then you add below xml part in res/values/attrs.xml file of project;

<resources>
    <declare-styleable name="MaskedEditText">
        <attr name="mask" format="string" />
        <attr name="placeholder" format="string" />
    </declare-styleable>
</resources>

Then you will be ready to use MaskedEditText view.

As last, you should add MaskedEditText in your xml file what you want like below;

<packagename.currentfolder.MaskedEditText
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/maskedEditText"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:ems="10"
    android:text="5"
    app:mask="(999) 999-9999"
    app:placeholder="_" >

Of course that, you can use it programmatically.

After those steps, adding MaskedEditText will appear like below;

enter image description here

As programmatically, if you want to take it's text value as unmasked, you may use below row;

maskedEditText.getText(true);

To take masked value, you may send false value instead of true value in the getText method.

How to Install Windows Phone 8 SDK on Windows 7

You can install it by first extracting all the files from the ISO and then overwriting those files with the files from the ZIP. Then you can run the batch file as administrator to do the installation. Most of the packages install on windows 7, but I haven't tested yet how well they work.

How do I set headers using python's urllib?

For both Python 3 and Python 2, this works:

try:
    from urllib.request import Request, urlopen  # Python 3
except ImportError:
    from urllib2 import Request, urlopen  # Python 2

req = Request('http://api.company.com/items/details?country=US&language=en')
req.add_header('apikey', 'xxx')
content = urlopen(req).read()

print(content)

Proper MIME type for .woff2 fonts

http://dev.w3.org/webfonts/WOFF2/spec/#IMT

It seem that w3c switched it to font/woff2

I see there is some discussion about the proper mime type. In the link we read:

This document defines a top-level MIME type "font" ...

... the officially defined IANA subtypes such as "application/font-woff" ...

The members of the W3C WebFonts WG believe the use of "application" top-level type is not ideal.

and later

6.5. WOFF 2.0

    Type name:

        font
    Subtype name:

        woff2

So proposition from W3C differs from IANA.

We can see that it also differs from woff type: http://dev.w3.org/webfonts/WOFF/spec/#IMT where we read:

Type name:

    application
Subtype name:

    font-woff

which is

application/font-woff

http://www.w3.org/TR/WOFF/#appendix-b

How to show the text on a ImageButton?

You can use a LinearLayout instead of using Button it's an arrangement i used in my app

 <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="20dp"
        android:background="@color/mainColor"
        android:orientation="horizontal"
        android:padding="10dp">

        <ImageView
            android:layout_width="50dp"
            android:layout_height="50dp"
            android:background="@drawable/ic_cv"
            android:textColor="@color/offBack"
            android:textSize="20dp" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="10dp"
            android:text="@string/cartyCv"
            android:textColor="@color/offBack"
            android:textSize="25dp" />

    </LinearLayout>

XML Parser for C

Expat is pretty decent. It's hard to give good recommendations without more information though.

What is the difference between printf() and puts() in C?

When comparing puts() and printf(), even though their memory consumption is almost the same, puts() takes more time compared to printf().

How do I get this javascript to run every second?

Use setInterval(func, delay) to run the func every delay milliseconds.

setTimeout() runs your function once after delay milliseconds -- it does not run it repeatedly. A common strategy is to run your code with setTimeout and call setTimeout again at the end of your code.

How to add an auto-incrementing primary key to an existing table, in PostgreSQL?

I landed here because I was looking for something like that too. In my case, I was copying the data from a set of staging tables with many columns into one table while also assigning row ids to the target table. Here is a variant of the above approaches that I used. I added the serial column at the end of my target table. That way I don't have to have a placeholder for it in the Insert statement. Then a simple select * into the target table auto populated this column. Here are the two SQL statements that I used on PostgreSQL 9.6.4.

ALTER TABLE target ADD COLUMN some_column SERIAL;
INSERT INTO target SELECT * from source;

SQL Server - Case Statement

We can use case statement Like this

select Name,EmailId,gender=case 
when gender='M' then 'F'
when gender='F' then 'M'
end
 from [dbo].[Employees]

WE can also it as follow.

select Name,EmailId,case gender
when 'M' then 'F'
when 'F' then 'M'
end
 from [dbo].[Employees]

How to get records randomly from the oracle database?

SELECT column FROM
( SELECT column, dbms_random.value FROM table ORDER BY 2 )
where rownum <= 20;

How to retrieve SQL result column value using column name in Python?

This post is old but may come up via searching.

Now you can use mysql.connector to retrive a dictionary as shown here: https://dev.mysql.com/doc/connector-python/en/connector-python-api-mysqlcursordict.html

Here is the example on the mysql site:

cnx = mysql.connector.connect(database='world')
cursor = cnx.cursor(dictionary=True)
cursor.execute("SELECT * FROM country WHERE Continent = 'Europe'")

print("Countries in Europe:")
for row in cursor:
    print("* {Name}".format(Name=row['Name']))

Setting background color for a JFrame

This is the simplest and the correct method. All you have to do is to add this code after initComponents();

getContentPane().setBackground(new java.awt.Color(204, 166, 166));

That is an example RGB color, you can replace that with your desired color. If you dont know the codes of RGB colors, please search on internet... there are a lot of sites that provide custom colors like this.

Stopping a CSS3 Animation on last frame

If you want to add this behaviour to a shorthand animation property definition, the order of sub-properties is as follows

animation-name - default none

animation-duration - default 0s

animation-timing-function - default ease

animation-delay - default 0s

animation-iteration-count - default 1

animation-direction - default normal

animation-fill-mode - you need to set this to forwards

animation-play-state - default running

Therefore in the most common case, the result will be something like this

animation: colorchange 1s ease 0s 1 normal forwards;

See the MDN documentation here

Facebook Graph API error code list

Facebook Developer Wiki (unofficial) contain not only list of FQL error codes but others too it's somehow updated but not contain full list of possible error codes.

There is no any official or updated (I mean really updated) list of error codes returned by Graph API. Every list that can be found online is outdated and not help that much...

There is official list describing some of API Errors and basic recovery tactics. Also there is couple of offcial lists for specific codes:

How to move text up using CSS when nothing is working

footerText {
    line-height: 20px;
}

you don't need to start playing with position or even layout of other elements... use this simple solution

$(form).ajaxSubmit is not a function

Ajax Submit form with out page refresh by using jquery ajax method first include library jquery.js and jquery-form.js then create form in html:

<form action="postpage.php" method="POST" id="postForm" >

<div id="flash_success"></div>

name:
<input type="text" name="name" />
password:
<input type="password" name="pass" />
Email:
<input type="text" name="email" />

<input type="submit" name="btn" value="Submit" />
</form>

<script>
  var options = { 
        target:        '#flash_success',  // your response show in this ID
        beforeSubmit:  callValidationFunction,
        success:       YourResponseFunction  
    };
    // bind to the form's submit event
        jQuery('#postForm').submit(function() { 
            jQuery(this).ajaxSubmit(options); 
            return false; 
        }); 


});
function callValidationFunction()
{
 //  validation code for your form HERE
}

function YourResponseFunction(responseText, statusText, xhr, $form)
{
    if(responseText=='success')
    {
        $('#flash_success').html('Your Success Message Here!!!');
        $('body,html').animate({scrollTop: 0}, 800);

    }else
    {
        $('#flash_success').html('Error Msg Here');

    }
}
</script>

"commence before first target. Stop." error

if you have added a new line, Make sure you have added next line syntax in previous line. typically if "\" is missing in your previous line of changes, you will get this error.

Closing Bootstrap modal onclick

If the button tag is inside the div element who contains the modal, you can do something like:

<button class="btn btn-default" data-dismiss="modal" aria-label="Close">Cancel</button>

is there a require for json in node.js

No. Either use readFile or readFileSync (The latter only at startup time).

Or use an existing library like

Alternatively write your config in a js file rather then a json file like

module.exports = {
  // json
}

How to calculate the CPU usage of a process by PID in Linux from C?

Install psacct or acct package. Then use the sa command to display CPU time used for various commands. sa man page

A nice howto from the nixCraft site.

Assign value from successful promise resolve to external variable

This is one "trick" you can do since your out of an async function so can't use await keywork

Do what you want to do with vm.feed inside a setTimeout

vm.feed = getFeed().then(function(data) {return data;});

 setTimeout(() => {
    // do you stuf here
    // after the time you promise will be revolved or rejected
    // if you need some of the values in here immediately out of settimeout
    // might occur an error if promise wore not yet resolved or rejected
    console.log("vm.feed",vm.feed);
 }, 100);

Subtracting 1 day from a timestamp date

Use the INTERVAL type to it. E.g:

--yesterday
SELECT NOW() - INTERVAL '1 DAY';

--Unrelated to the question, but PostgreSQL also supports some shortcuts:
SELECT 'yesterday'::TIMESTAMP, 'tomorrow'::TIMESTAMP, 'allballs'::TIME;

Then you can do the following on your query:

SELECT 
    org_id,
    count(accounts) AS COUNT,
    ((date_at) - INTERVAL '1 DAY') AS dateat
FROM 
    sourcetable
WHERE 
    date_at <= now() - INTERVAL '130 DAYS'
GROUP BY 
    org_id,
    dateat;


TIPS

Tip 1

You can append multiple operands. E.g.: how to get last day of current month?

SELECT date_trunc('MONTH', CURRENT_DATE) + INTERVAL '1 MONTH - 1 DAY';

Tip 2

You can also create an interval using make_interval function, useful when you need to create it at runtime (not using literals):

SELECT make_interval(days => 10 + 2);
SELECT make_interval(days => 1, hours => 2);
SELECT make_interval(0, 1, 0, 5, 0, 0, 0.0);


More info:

Date/Time Functions and Operators

datatype-datetime (Especial values).

How to use HttpWebRequest (.NET) asynchronously?

By far the easiest way is by using TaskFactory.FromAsync from the TPL. It's literally a couple of lines of code when used in conjunction with the new async/await keywords:

var request = WebRequest.Create("http://www.stackoverflow.com");
var response = (HttpWebResponse) await Task.Factory
    .FromAsync<WebResponse>(request.BeginGetResponse,
                            request.EndGetResponse,
                            null);
Debug.Assert(response.StatusCode == HttpStatusCode.OK);

If you can't use the C#5 compiler then the above can be accomplished using the Task.ContinueWith method:

Task.Factory.FromAsync<WebResponse>(request.BeginGetResponse,
                                    request.EndGetResponse,
                                    null)
    .ContinueWith(task =>
    {
        var response = (HttpWebResponse) task.Result;
        Debug.Assert(response.StatusCode == HttpStatusCode.OK);
    });

Better way to cast object to int

Strange, but the accepted answer seems wrong about the cast and the Convert in the mean that from my tests and reading the documentation too it should not take into account implicit or explicit operators.

So, if I have a variable of type object and the "boxed" class has some implicit operators defined they won't work.

Instead another simple way, but really performance costing is to cast before in dynamic.

(int)(dynamic)myObject.

You can try it in the Interactive window of VS.

public class Test
{
  public static implicit operator int(Test v)
  {
    return 12;
  }
}

(int)(object)new Test() //this will fail
Convert.ToInt32((object)new Test()) //this will fail
(int)(dynamic)(object)new Test() //this will pass

Folder is locked and I can't unlock it

I had this issue and i have done below steps to resolve it:

  1. Go to parent folder instead of child folder
  2. Select SVN cleanup
  3. Click on OK.

Do this step on parent folder instead of child folder!

It worked for me !

Styles.Render in MVC4

Watch out for case sensitivity. If you have a file

/Content/bootstrap.css

and you redirect in your Bundle.config to

.Include("~/Content/Bootstrap.css")

it will not load the css.

Concatenating bits in VHDL

Here is an example of concatenation operator:

architecture EXAMPLE of CONCATENATION is
   signal Z_BUS : bit_vector (3 downto 0);
   signal A_BIT, B_BIT, C_BIT, D_BIT : bit;
begin
   Z_BUS <= A_BIT & B_BIT & C_BIT & D_BIT;
end EXAMPLE;

C# Checking if button was clicked

button1, button2 and button3 have same even handler

private void button1_Click(Object sender, EventArgs e)
    {
        Button btnSender = (Button)sender;
        if (btnSender == button1 || btnSender == button2)
        {
            //some code here
        }
        else if (btnSender == button3)
            //some code here
    }

How do I set <table> border width with CSS?

<table style="border: 5px solid black">

This only adds a border around the table.

If you want same border through CSS then add this rule:

table tr td { border: 5px solid black; }

and one thing for HTML table to avoid spaces

<table cellspacing="0" cellpadding="0">

getElementById returns null?

There could be many reason why document.getElementById doesn't work

  • You have an invalid ID

    ID and NAME tokens must begin with a letter ([A-Za-z]) and may be followed by any number of letters, digits ([0-9]), hyphens ("-"), underscores ("_"), colons (":"), and periods ("."). (resource: What are valid values for the id attribute in HTML?)

  • you used some id that you already used as <meta> name in your header (e.g. copyright, author... ) it looks weird but happened to me: if your 're using IE take a look at (resource: http://www.phpied.com/getelementbyid-description-in-ie/)

  • you're targeting an element inside a frame or iframe. In this case if the iframe loads a page within the same domain of the parent you should target the contentdocument before looking for the element (resource: Calling a specific id inside a frame)

  • you're simply looking to an element when the node is not effectively loaded in the DOM, or maybe it's a simple misspelling

I doubt you used same ID twice or more: in that case document.getElementById should return at least the first element

What do Clustered and Non clustered index actually mean?

Clustered Index

Clustered indexes sort and store the data rows in the table or view based on their key values. These are the columns included in the index definition. There can be only one clustered index per table, because the data rows themselves can be sorted in only one order.

The only time the data rows in a table are stored in sorted order is when the table contains a clustered index. When a table has a clustered index, the table is called a clustered table. If a table has no clustered index, its data rows are stored in an unordered structure called a heap.

Nonclustered

Nonclustered indexes have a structure separate from the data rows. A nonclustered index contains the nonclustered index key values and each key value entry has a pointer to the data row that contains the key value. The pointer from an index row in a nonclustered index to a data row is called a row locator. The structure of the row locator depends on whether the data pages are stored in a heap or a clustered table. For a heap, a row locator is a pointer to the row. For a clustered table, the row locator is the clustered index key.

You can add nonkey columns to the leaf level of the nonclustered index to by-pass existing index key limits, and execute fully covered, indexed, queries. For more information, see Create Indexes with Included Columns. For details about index key limits see Maximum Capacity Specifications for SQL Server.

Reference: https://docs.microsoft.com/en-us/sql/relational-databases/indexes/clustered-and-nonclustered-indexes-described

gcc error: wrong ELF class: ELFCLASS64

It looks like the object file was compiled on a 64-bit toolchain, and you're using a 32-bit toolchain. Have you tried recompiling the object file in 32-bit mode?

How can I use grep to show just filenames on Linux?

For a simple file search you could use grep's -l and -r options:

grep -rl "mystring"

All the search is done by grep. Of course, if you need to select files on some other parameter, find is the correct solution:

find . -iname "*.php" -execdir grep -l "mystring" {} +

The execdir option builds each grep command per each directory, and concatenates filenames into only one command (+).

Converting milliseconds to minutes and seconds with Javascript

const Minutes = ((123456/60000).toFixed(2)).replace('.',':');

//Result = 2:06

We divide the number in milliseconds (123456) by 60000 to give us the same number in minutes, which here would be 2.0576.

toFixed(2) - Rounds the number to nearest two decimal places, which in this example gives an answer of 2.06.

You then use replace to swap the period for a colon.

Format number to 2 decimal places

How about CAST(2229.999 AS DECIMAL(6,2)) to get a decimal with 2 decimal places

Amazon Linux: apt-get: command not found

Check the Linux distribution, apt-get works in Debian based distro whereas yum works in Fedora based distro.

Ref: How to know distro name, execute command cat /etc/*-release

It is also possible your system administrator does not permit you (or did not put you in the group of users who have sudo permissions) to execute apt-get but if you have sudo access try to execute with sudo apt-get <package_name> if debian or yum install <package_name> if you are using Fedora.

MySQL timezone change?

While Bryon's answer is helpful, I'd just add that his link is for PHP timezone names, which are not the same as MySQL timezone names.

If you want to set your timezone for an individual session to GMT+1 (UTC+1 to be precise) just use the string '+01:00' in that command. I.e.:

SET time_zone = '+01:00';

To see what timezone your MySQL session is using, just execute this:

SELECT @@global.time_zone, @@session.time_zone;

This is a great reference with more details: MySQL 5.5 Reference on Time Zones

Handling the window closing event with WPF / MVVM Light Toolkit

I haven't done much testing with this but it seems to work. Here's what I came up with:

namespace OrtzIRC.WPF
{
    using System;
    using System.Windows;
    using OrtzIRC.WPF.ViewModels;

    /// <summary>
    /// Interaction logic for App.xaml
    /// </summary>
    public partial class App : Application
    {
        private MainViewModel viewModel = new MainViewModel();
        private MainWindow window = new MainWindow();

        protected override void OnStartup(StartupEventArgs e)
        {
            base.OnStartup(e);

            viewModel.RequestClose += ViewModelRequestClose;

            window.DataContext = viewModel;
            window.Closing += Window_Closing;
            window.Show();
        }

        private void ViewModelRequestClose(object sender, EventArgs e)
        {
            viewModel.RequestClose -= ViewModelRequestClose;
            window.Close();
        }

        private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            window.Closing -= Window_Closing;
            viewModel.RequestClose -= ViewModelRequestClose; //Otherwise Close gets called again
            viewModel.CloseCommand.Execute(null);
        }
    }
}

Two arrays in foreach loop

if(isset($_POST['doors'])=== true){
$doors = $_POST['doors'];
}else{$doors = 0;}

if(isset($_POST['windows'])=== true){
$windows = $_POST['windows'];
}else{$windows = 0;}

foreach($doors as $a => $b){

Now you can use $a for each array....

$doors[$a]
$windows[$a]
....
}

Draw on HTML5 Canvas using a mouse

Googled this ("html5 canvas paint program"). Looks like what you need.

http://dev.opera.com/articles/view/html5-canvas-painting/

Requests (Caused by SSLError("Can't connect to HTTPS URL because the SSL module is not available.") Error in PyCharm requesting website

this issue was driving me insane until i found this post which said to do

brew upgrade python3 

(not using pycharm, using sublime)

Error when importing ssl in Python 3.7.4 on macOS 10.14.6

Correct format specifier to print pointer or address?

The simplest answer, assuming you don't mind the vagaries and variations in format between different platforms, is the standard %p notation.

The C99 standard (ISO/IEC 9899:1999) says in §7.19.6.1 ¶8:

p The argument shall be a pointer to void. The value of the pointer is converted to a sequence of printing characters, in an implementation-defined manner.

(In C11 — ISO/IEC 9899:2011 — the information is in §7.21.6.1 ¶8.)

On some platforms, that will include a leading 0x and on others it won't, and the letters could be in lower-case or upper-case, and the C standard doesn't even define that it shall be hexadecimal output though I know of no implementation where it is not.

It is somewhat open to debate whether you should explicitly convert the pointers with a (void *) cast. It is being explicit, which is usually good (so it is what I do), and the standard says 'the argument shall be a pointer to void'. On most machines, you would get away with omitting an explicit cast. However, it would matter on a machine where the bit representation of a char * address for a given memory location is different from the 'anything else pointer' address for the same memory location. This would be a word-addressed, instead of byte-addressed, machine. Such machines are not common (probably not available) these days, but the first machine I worked on after university was one such (ICL Perq).

If you aren't happy with the implementation-defined behaviour of %p, then use C99 <inttypes.h> and uintptr_t instead:

printf("0x%" PRIXPTR "\n", (uintptr_t)your_pointer);

This allows you to fine-tune the representation to suit yourself. I chose to have the hex digits in upper-case so that the number is uniformly the same height and the characteristic dip at the start of 0xA1B2CDEF appears thus, not like 0xa1b2cdef which dips up and down along the number too. Your choice though, within very broad limits. The (uintptr_t) cast is unambiguously recommended by GCC when it can read the format string at compile time. I think it is correct to request the cast, though I'm sure there are some who would ignore the warning and get away with it most of the time.


Kerrek asks in the comments:

I'm a bit confused about standard promotions and variadic arguments. Do all pointers get standard-promoted to void*? Otherwise, if int* were, say, two bytes, and void* were 4 bytes, then it'd clearly be an error to read four bytes from the argument, non?

I was under the illusion that the C standard says that all object pointers must be the same size, so void * and int * cannot be different sizes. However, what I think is the relevant section of the C99 standard is not so emphatic (though I don't know of an implementation where what I suggested is true is actually false):

§6.2.5 Types

¶26 A pointer to void shall have the same representation and alignment requirements as a pointer to a character type.39) Similarly, pointers to qualified or unqualified versions of compatible types shall have the same representation and alignment requirements. All pointers to structure types shall have the same representation and alignment requirements as each other. All pointers to union types shall have the same representation and alignment requirements as each other. Pointers to other types need not have the same representation or alignment requirements.

39) The same representation and alignment requirements are meant to imply interchangeability as arguments to functions, return values from functions, and members of unions.

(C11 says exactly the same in the section §6.2.5, ¶28, and footnote 48.)

So, all pointers to structures must be the same size as each other, and must share the same alignment requirements, even though the structures the pointers point at may have different alignment requirements. Similarly for unions. Character pointers and void pointers must have the same size and alignment requirements. Pointers to variations on int (meaning unsigned int and signed int) must have the same size and alignment requirements as each other; similarly for other types. But the C standard doesn't formally say that sizeof(int *) == sizeof(void *). Oh well, SO is good for making you inspect your assumptions.

The C standard definitively does not require function pointers to be the same size as object pointers. That was necessary not to break the different memory models on DOS-like systems. There you could have 16-bit data pointers but 32-bit function pointers, or vice versa. This is why the C standard does not mandate that function pointers can be converted to object pointers and vice versa.

Fortunately (for programmers targetting POSIX), POSIX steps into the breach and does mandate that function pointers and data pointers are the same size:

§2.12.3 Pointer Types

All function pointer types shall have the same representation as the type pointer to void. Conversion of a function pointer to void * shall not alter the representation. A void * value resulting from such a conversion can be converted back to the original function pointer type, using an explicit cast, without loss of information.

Note: The ISO C standard does not require this, but it is required for POSIX conformance.

So, it does seem that explicit casts to void * are strongly advisable for maximum reliability in the code when passing a pointer to a variadic function such as printf(). On POSIX systems, it is safe to cast a function pointer to a void pointer for printing. On other systems, it is not necessarily safe to do that, nor is it necessarily safe to pass pointers other than void * without a cast.

Stop form from submitting , Using Jquery

use this too :

if(e.preventDefault) 
   e.preventDefault(); 
else 
   e.returnValue = false;

Becoz e.preventDefault() is not supported in IE( some versions ). In IE it is e.returnValue = false

groovy.lang.MissingPropertyException: No such property: jenkins for class: groovy.lang.Binding

For me this problem occurred because I had a some invalid character in my Groovy script. In our case this was an extra blank line after the closing bracket of the script.

center aligning a fixed position div

If you know the width is 400px this would be the easiest way to do it I guess.

 left: calc(50% - 200px);

Inserting multiple rows in mysql

If you have your data in a text-file, you can use LOAD DATA INFILE.

When loading a table from a text file, use LOAD DATA INFILE. This is usually 20 times faster than using INSERT statements.

Optimizing INSERT Statements

You can find more tips on how to speed up your insert statements on the link above.

Why AVD Manager options are not showing in Android Studio

I had the same issue on my React Native Project. Was not just that ADV Manager didn't show up on the menu but other tools where missing as well.

Everything was back to normal when I opened the project using Import project option instead of Open an Existing Android Studio project.

enter image description here

PHP removing a character in a string

I think that it's better to use simply str_replace, like the manual says:

If you don't need fancy replacing rules (like regular expressions), you should always use this function instead of ereg_replace() or preg_replace().

<?
$badUrl = "http://www.site.com/backend.php?/c=crud&m=index&t=care";
$goodUrl = str_replace('?/', '?', $badUrl);

Substring with reverse index

here is my custom function

function reverse_substring(str,from,to){
  var temp="";
  var i=0;
  var pos = 0;
  var append;      
  for(i=str.length-1;i>=0;i--){
    //alert("inside loop " + str[i]);
    if(pos == from){
         append=true;
    }

    if(pos == to){
         append=false;
         break;
    }
    if(append){
         temp = str[i] + temp;
    }
    pos++;
  }
  alert("bottom loop " + temp);
}

var str = "bala_123";
reverse_substring(str,0,3);

This function works for reverse index.

What does this error mean: "error: expected specifier-qualifier-list before 'type_name'"?

You have to name your struct like that:

typedef struct car_t {

   char

   wheel_t

} car_t;

Trigger an action after selection select2

There was made some changes to the select2 events names (I think on v. 4 and later) so the '-' is changed into this ':'.
See the next examples:

$('#select').on("select2:select", function(e) { 
    //Do stuff
});

You can check all the events at the 'select2' plugin site: select2 Events

How to set initial value and auto increment in MySQL?

You could also set it in the create table statement.

`CREATE TABLE(...) AUTO_INCREMENT=1000`

How do I execute external program within C code in linux with arguments?

Here's the way to extend to variable args when you don't have the args hard coded (although they are still technically hard coded in this example, but should be easy to figure out how to extend...):

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

int argcount = 3;
const char* args[] = {"1", "2", "3"};
const char* binary_name = "mybinaryname";
char myoutput_array[5000];

sprintf(myoutput_array, "%s", binary_name);
for(int i = 0; i < argcount; ++i)
{
    strcat(myoutput_array, " ");
    strcat(myoutput_array, args[i]);
}
system(myoutput_array);

How do you round a number to two decimal places in C#?

Wikipedia has a nice page on rounding in general.

All .NET (managed) languages can use any of the common language run time's (the CLR) rounding mechanisms. For example, the Math.Round() (as mentioned above) method allows the developer to specify the type of rounding (Round-to-even or Away-from-zero). The Convert.ToInt32() method and its variations use round-to-even. The Ceiling() and Floor() methods are related.

You can round with custom numeric formatting as well.

Note that Decimal.Round() uses a different method than Math.Round();

Here is a useful post on the banker's rounding algorithm. See one of Raymond's humorous posts here about rounding...

Can I create a One-Time-Use Function in a Script or Stored Procedure?

You can call CREATE Function near the beginning of your script and DROP Function near the end.

cin and getline skipping input

Here, the '\n' left by cin, is creating issues.

do {
    system("cls");
    manageCustomerMenu();
    cin >> choice;               #This cin is leaving a trailing \n
    system("cls");

    switch (choice) {
        case '1':
            createNewCustomer();
            break;

This \n is being consumed by next getline in createNewCustomer(). You should use getline instead -

do {
    system("cls");
    manageCustomerMenu();
    getline(cin, choice)               
    system("cls");

    switch (choice) {
        case '1':
            createNewCustomer();
            break;

I think this would resolve the issue.

How to install sshpass on mac?

Solution provided by lukesUbuntu from github works for me:

Just use brew

$ brew install http://git.io/sshpass.rb