Programs & Examples On #Performancepoint

a business intelligence server integrated with SharePoint. Includes PerformancePoint Server 2007, which was an addition to SharePoint 2007, and PerformancePoint Services 2010 and 2013, which is included with SharePoint.

What is an optional value in Swift?

Here is an equivalent optional declaration in Swift:

var middleName: String?

This declaration creates a variable named middleName of type String. The question mark (?) after the String variable type indicates that the middleName variable can contain a value that can either be a String or nil. Anyone looking at this code immediately knows that middleName can be nil. It's self-documenting!

If you don't specify an initial value for an optional constant or variable (as shown above) the value is automatically set to nil for you. If you prefer, you can explicitly set the initial value to nil:

var middleName: String? = nil

for more detail for optional read below link

http://www.iphonelife.com/blog/31369/swift-101-working-swifts-new-optional-values

Why am I getting 'Assembly '*.dll' must be strong signed in order to be marked as a prerequisite.'?

When I had this problem I fixed it by turning off the 'Enable ClickOnce security settings'.

Menu: Project | 'Project name' Properties... | Security tab | 'Enable ClickOnce security settings' check box.

How to read a text file into a string variable and strip newlines?

I don't feel that anyone addressed the [ ] part of your question. When you read each line into your variable, because there were multiple lines before you replaced the \n with '' you ended up creating a list. If you have a variable of x and print it out just by

x

or print(x)

or str(x)

You will see the entire list with the brackets. If you call each element of the (array of sorts)

x[0] then it omits the brackets. If you use the str() function you will see just the data and not the '' either. str(x[0])

Enzyme - How to access and set <input> value?

Got it. (updated/improved version)

  it('cancels changes when user presses esc', done => {
    const wrapper = mount(<EditableText defaultValue="Hello" />);
    const input = wrapper.find('input');

    input.simulate('focus');
    input.simulate('change', { target: { value: 'Changed' } });
    input.simulate('keyDown', {
      which: 27,
      target: {
        blur() {
          // Needed since <EditableText /> calls target.blur()
          input.simulate('blur');
        },
      },
    });
    expect(input.get(0).value).to.equal('Hello');

    done();
  });

Calculating how many minutes there are between two times

You just need to query the TotalMinutes property like this varTime.TotalMinutes

Rails 4 - passing variable to partial

ou are able to create local variables once you call the render function on a partial, therefore if you want to customize a partial you can for example render the partial _form.html.erb by:

<%= render 'form', button_label: "Create New Event", url: new_event_url %>
<%= render 'form', button_label: "Update Event", url: edit_event_url %>

this way you can access in the partial to the label for the button and the URL, those are different if you try to create or update a record. finally, for accessing to this local variables you have to put in your code local_assigns[:button_label] (local_assigns[:name_of_your_variable])

<%=form_for(@event, url: local_assigns[:url]) do |f|  %>
<%= render 'shared/error_messages_events' %>
<%= f.label :title ,"Title"%>
  <%= f.text_field :title, class: 'form-control'%>
  <%=f.label :date, "Date"%>
  <%=f.date_field :date, class: 'form-control'  %>
  <%=f.label :description, "Description"%>
  <%=f.text_area :description, class: 'form-control'  %>
  <%= f.submit local_assigns[:button_label], class:"btn btn-primary"%>
<%end%>

Using json_encode on objects in PHP (regardless of scope)

All the properties of your object are private. aka... not available outside their class's scope.

Solution for PHP >= 5.4

Use the new JsonSerializable Interface to provide your own json representation to be used by json_encode

class Thing implements JsonSerializable {
    ...
    public function jsonSerialize() {
        return [
            'something' => $this->something,
            'protected_something' => $this->get_protected_something(),
            'private_something' => $this->get_private_something()
        ];
    }
    ...
}

Solution for PHP < 5.4

If you do want to serialize your private and protected object properties, you have to implement a JSON encoding function inside your Class that utilizes json_encode() on a data structure you create for this purpose.

class Thing {
    ...
    public function to_json() {
        return json_encode(array(
            'something' => $this->something,
            'protected_something' => $this->get_protected_something(),
            'private_something' => $this->get_private_something()                
        ));
    }
    ...
}

A more detailed writeup

Why I am getting Cannot pass parameter 2 by reference error when I am using bindParam with a constant value?

When using bindParam() you must pass in a variable, not a constant. So before that line you need to create a variable and set it to null

$myNull = null;
$stmt->bindParam(':v1', $myNull, PDO::PARAM_NULL);

You would get the same error message if you tried:

$stmt->bindParam(':v1', 5, PDO::PARAM_NULL);

Header and footer in CodeIgniter

Yes.

Create a file called template.php in your views folder.

The contents of template.php:

$this->load->view('templates/header');
$this->load->view($v);
$this->load->view('templates/footer');

Then from your controller you can do something like:

$d['v'] = 'body';
$this->load->view('template', $d);

This is actually a very simplistic version of how I personally load all of my views. If you take this idea to the extreme, you can make some interesting modular layouts:

Consider if you create a view called init.php that contains the single line:

$this->load->view('html');

Now create the view html.php with contents:

<!DOCTYPE html>
<html lang="en">
    <? $this->load->view('head'); ?>
    <? $this->load->view('body'); ?>
</html>

Now create a view head.php with contents:

<head>
<title><?= $title;?></title>
<base href="<?= site_url();?>">
<link rel="shortcut icon" href='favicon.ico'>
<script type='text/javascript'>//Put global scripts here...</script>
<!-- ETC ETC... DO A BUNCH OF OTHER <HEAD> STUFF... -->
</head>

And a body.php view with contents:

<body>
    <div id="mainWrap">
        <? $this->load->view('header'); ?>
        <? //FINALLY LOAD THE VIEW!!! ?>
        <? $this->load->view($v); ?>
        <? $this->load->view('footer'); ?>
    </div>
</body>

And create header.php and footer.php views as appropriate.

Now when you call the init from the controller all the heavy lifting is done and your views will be wrapped inside <html> and <body> tags, your headers and footers will be loaded in.

$d['v'] = 'fooview'
$this->load->view('init', $d);

Python: Passing variables between functions

Read up the concept of a name space. When you assign a variable in a function, you only assign it in the namespace of this function. But clearly you want to use it between all functions.

def defineAList():
    #list = ['1','2','3'] this creates a new list, named list in the current namespace.
    #same name, different list!

    list.extend['1', '2', '3', '4'] #this uses a method of the existing list, which is in an outer namespace
    print "For checking purposes: in defineAList, list is",list
    return list

Alternatively, you can pass it around:

def main():
    new_list = defineAList()
    useTheList(new_list)

Git mergetool generates unwanted .orig files

I simply use the command

git clean -n *.orig

check to make sure only file I want remove are listed then

git clean -f *.orig

AccessDenied for ListObjects for S3 bucket when permissions are s3:*

I had this issue my requirement i wanted to allow user to write to specific path

{
            "Sid": "raspiiotallowspecificBucket",
            "Effect": "Allow",
            "Action": [
                "s3:GetObject",
                "s3:PutObject",
                "s3:ListBucket"
            ],
            "Resource": [
                "arn:aws:s3:::<bucketname>/scripts",
                "arn:aws:s3:::<bucketname>/scripts/*"
            ]
        },

and problem was solved with this change

{
            "Sid": "raspiiotallowspecificBucket",
            "Effect": "Allow",
            "Action": [
                "s3:GetObject",
                "s3:PutObject",
                "s3:ListBucket"
            ],
            "Resource": [
                "arn:aws:s3:::<bucketname>",
                "arn:aws:s3:::<bucketname>/*"
            ]
        },

Clear listview content?

It's simple .First you should clear your collection and after clear list like this code :

 yourCollection.clear();
 setListAdapter(null);

How can the default node version be set using NVM?

You can also like this:

$ nvm alias default lts/fermium

Cannot instantiate the type List<Product>

List is an interface. You need a specific class in the end so either try

List l = new ArrayList();

or

List l = new LinkedList();

Whichever suit your needs.

Spring Bean Scopes

According to the documentation of Spring-Cloud-Config there is one extra scope next to the existing five. It is @RefreshScope.

This is the short description of RefreshScope:

When there is a configuration change, a Spring @Bean that is marked as @RefreshScope gets special treatment. This feature addresses the problem of stateful beans that only get their configuration injected when they are initialized. For instance, if a DataSource has open connections when the database URL is changed via the Environment, you probably want the holders of those connections to be able to complete what they are doing. Then, the next time something borrows a connection from the pool, it gets one with the new URL.

Sometimes, it might even be mandatory to apply the @RefreshScope annotation on some beans which can be only initialized once. If a bean is "immutable", you will have to either annotate the bean with @RefreshScope or specify the classname under the property key spring.cloud.refresh.extra-refreshable.

Refresh scope beans are lazy proxies that initialize when they are used (that is, when a method is called), and the scope acts as a cache of initialized values. To force a bean to re-initialize on the next method call, you must invalidate its cache entry.

The RefreshScope is a bean in the context and has a public refreshAll() method to refresh all beans in the scope by clearing the target cache. The /refresh endpoint exposes this functionality (over HTTP or JMX). To refresh an individual bean by name, there is also a refresh(String) method.

Get Filename Without Extension in Python

In most cases, you shouldn't use a regex for that.

os.path.splitext(filename)[0]

This will also handle a filename like .bashrc correctly by keeping the whole name.

Can I run multiple programs in a Docker container?

I had similar requirement of running a LAMP stack, Mongo DB and my own services

Docker is OS based virtualisation, which is why it isolates its container around a running process, hence it requires least one process running in FOREGROUND.

So you provide your own startup script as the entry point, thus your startup script becomes an extended Docker image script, in which you can stack any number of the services as far as AT LEAST ONE FOREGROUND SERVICE IS STARTED, WHICH TOO TOWARDS THE END

So my Docker image file has two line below in the very end:

COPY myStartupScript.sh /usr/local/myscripts/myStartupScript.sh
CMD ["/bin/bash", "/usr/local/myscripts/myStartupScript.sh"]

In my script I run all MySQL, MongoDB, Tomcat etc. In the end I run my Apache as a foreground thread.

source /etc/apache2/envvars
/usr/sbin/apache2 -DFOREGROUND

This enables me to start all my services and keep the container alive with the last service started being in the foreground

Hope it helps

UPDATE: Since I last answered this question, new things have come up like Docker compose, which can help you run each service on its own container, yet bind all of them together as dependencies among those services, try knowing more about docker-compose and use it, it is more elegant way unless your need does not match with it.

cannot convert data (type interface {}) to type string: need type assertion

As asked for by @??s???? an explanation can be found at https://golang.org/pkg/fmt/#Sprint. Related explanations can be found at https://stackoverflow.com/a/44027953/12817546 and at https://stackoverflow.com/a/42302709/12817546. Here is @Yuanbo's answer in full.

package main

import "fmt"

func main() {
    var data interface{} = 2
    str := fmt.Sprint(data)
    fmt.Println(str)
}

How to remove leading zeros from alphanumeric text?

Use this:

String x = "00123".replaceAll("^0*", ""); // -> 123

Calculate AUC in R?

Combining code from ISL 9.6.3 ROC Curves, along with @J. Won.'s answer to this question and a few more places, the following plots the ROC curve and prints the AUC in the bottom right on the plot.

Below probs is a numeric vector of predicted probabilities for binary classification and test$label contains the true labels of the test data.

require(ROCR)
require(pROC)

rocplot <- function(pred, truth, ...) {
  predob = prediction(pred, truth)
  perf = performance(predob, "tpr", "fpr")
  plot(perf, ...)
  area <- auc(truth, pred)
  area <- format(round(area, 4), nsmall = 4)
  text(x=0.8, y=0.1, labels = paste("AUC =", area))

  # the reference x=y line
  segments(x0=0, y0=0, x1=1, y1=1, col="gray", lty=2)
}

rocplot(probs, test$label, col="blue")

This gives a plot like this:

enter image description here

Can't update data-attribute value

I had the same problem of the html data tag not updating when i was using jquery But changing the code that does the actual work from jquery to javascript worked.

Try using this when the button is clicked: (Note that the main code is Javascripts setAttribute() function.)

function increment(q) {

    //increment current num by adding with 1
    q = q+1;

    //change data attribute using JS setAttribute function
    div.setAttribute('data-num',q);

    //refresh data-num value (get data-num value again using JS getAttribute function)
    num = parseInt(div.getAttribute('data-num'));

    //show values
    console.log("(After Increment) Current Num: "+num);

}

//get variables, set as global vars
var div = document.getElementById('foo');
var num = parseInt(div.getAttribute('data-num'));

//increment values using click
$("#changeData").on('click',function(){

    //pass current data-num as parameter
    increment(num);

});

UUID max character length

Most databases have a native UUID type these days to make working with them easier. If yours doesn't, they're just 128-bit numbers, so you can use BINARY(16), and if you need the text format frequently, e.g. for troubleshooting, then add a calculated column to generate it automatically from the binary column. There is no good reason to store the (much larger) text form.

How to fix a Div to top of page with CSS only

Yes, there are a number of ways that you can do this. The "fastest" way would be to add CSS to the div similar to the following

#term-defs {
height: 300px;
overflow: scroll; }

This will force the div to be scrollable, but this might not get the best effect. Another route would be to absolute fix the position of the items at the top, you can play with this by doing something like this.

#top {
  position: fixed;
  top: 0;
  left: 0;
  z-index: 999;
  width: 100%;
  height: 23px;
}

This will fix it to the top, on top of other content with a height of 23px.

The final implementation will depend on what effect you really want.

JAXB Exception: Class not known to this context

I had this error because I registered the wrong class in this line of code:

JAXBContext context = JAXBContext.newInstance(MyRootXmlClass.class);

Right HTTP status code to wrong input

We had the same problem when making our API as well. We were looking for an HTTP status code equivalent to an InvalidArgumentException. After reading the source article below, we ended up using 422 Unprocessable Entity which states:

The 422 (Unprocessable Entity) status code means the server understands the content type of the request entity (hence a 415 (Unsupported Media Type) status code is inappropriate), and the syntax of the request entity is correct (thus a 400 (Bad Request) status code is inappropriate) but was unable to process the contained instructions. For example, this error condition may occur if an XML request body contains well-formed (i.e., syntactically correct), but semantically erroneous, XML instructions.

source: https://www.bennadel.com/blog/2434-http-status-codes-for-invalid-data-400-vs-422.htm

Declaring and initializing a string array in VB.NET

Public Function TestError() As String()
     Return {"foo", "bar"}
End Function

Works fine for me and should work for you, but you may need allow using implicit declarations in your project. I believe this is turning off Options strict in the Compile section of the program settings.

Since you are using VS 2008 (VB.NET 9.0) you have to declare create the new instance

New String() {"foo", "Bar"}

Apache 2.4 - Request exceeded the limit of 10 internal redirects due to probable configuration error

This problem can be caused by requests for certain files that don't exist. For example, requests for files in wp-content/uploads/ where the file does not exist.

If this is the situation you're seeing, you can solve the problem by going to .htaccess and changing this line:

RewriteRule ^(wp-(content|admin|includes).*) $1 [L]

to:

RewriteRule ^(wp-(content|admin|includes).*) - [L]

The underlying issue is that the rule above triggers a rewrite to the exact same url with a slash in front and because there was a rewrite, the newly rewritten request goes back through the rules again and the same rule is triggered. By changing that line's "$1" to "-", no rewrite happens and so the rewriting process does not start over again with the same URL.

It's possible that there's a difference in how apache 2.2 and 2.4 handle this situation of only-difference-is-a-slash-in-front and that's why the default rules provided by WordPress aren't working perfectly.

Writing .csv files from C++

Change

Morison_File << t;                                 //Printing to file
Morison_File << F;

To

Morison_File << t << ";" << F << endl;                                 //Printing to file

a , would also do instead of ;

Quick easy way to migrate SQLite3 to MySQL?

I wrote this simple script in Python3. It can be used as an included class or standalone script invoked via a terminal shell. By default it imports all integers as int(11)and strings as varchar(300), but all that can be adjusted in the constructor or script arguments respectively.

NOTE: It requires MySQL Connector/Python 2.0.4 or higher

Here's a link to the source on GitHub if you find the code below hard to read: https://github.com/techouse/sqlite3-to-mysql

#!/usr/bin/env python3

__author__ = "Klemen Tušar"
__email__ = "[email protected]"
__copyright__ = "GPL"
__version__ = "1.0.1"
__date__ = "2015-09-12"
__status__ = "Production"

import os.path, sqlite3, mysql.connector
from mysql.connector import errorcode


class SQLite3toMySQL:
    """
    Use this class to transfer an SQLite 3 database to MySQL.

    NOTE: Requires MySQL Connector/Python 2.0.4 or higher (https://dev.mysql.com/downloads/connector/python/)
    """
    def __init__(self, **kwargs):
        self._properties = kwargs
        self._sqlite_file = self._properties.get('sqlite_file', None)
        if not os.path.isfile(self._sqlite_file):
            print('SQLite file does not exist!')
            exit(1)
        self._mysql_user = self._properties.get('mysql_user', None)
        if self._mysql_user is None:
            print('Please provide a MySQL user!')
            exit(1)
        self._mysql_password = self._properties.get('mysql_password', None)
        if self._mysql_password is None:
            print('Please provide a MySQL password')
            exit(1)
        self._mysql_database = self._properties.get('mysql_database', 'transfer')
        self._mysql_host = self._properties.get('mysql_host', 'localhost')

        self._mysql_integer_type = self._properties.get('mysql_integer_type', 'int(11)')
        self._mysql_string_type = self._properties.get('mysql_string_type', 'varchar(300)')

        self._sqlite = sqlite3.connect(self._sqlite_file)
        self._sqlite.row_factory = sqlite3.Row
        self._sqlite_cur = self._sqlite.cursor()

        self._mysql = mysql.connector.connect(
            user=self._mysql_user,
            password=self._mysql_password,
            host=self._mysql_host
        )
        self._mysql_cur = self._mysql.cursor(prepared=True)
        try:
            self._mysql.database = self._mysql_database
        except mysql.connector.Error as err:
            if err.errno == errorcode.ER_BAD_DB_ERROR:
                self._create_database()
            else:
                print(err)
                exit(1)

    def _create_database(self):
        try:
            self._mysql_cur.execute("CREATE DATABASE IF NOT EXISTS `{}` DEFAULT CHARACTER SET 'utf8'".format(self._mysql_database))
            self._mysql_cur.close()
            self._mysql.commit()
            self._mysql.database = self._mysql_database
            self._mysql_cur = self._mysql.cursor(prepared=True)
        except mysql.connector.Error as err:
            print('_create_database failed creating databse {}: {}'.format(self._mysql_database, err))
            exit(1)

    def _create_table(self, table_name):
        primary_key = ''
        sql = 'CREATE TABLE IF NOT EXISTS `{}` ( '.format(table_name)
        self._sqlite_cur.execute('PRAGMA table_info("{}")'.format(table_name))
        for row in self._sqlite_cur.fetchall():
            column = dict(row)
            sql += ' `{name}` {type} {notnull} {auto_increment}, '.format(
                name=column['name'],
                type=self._mysql_string_type if column['type'].upper() == 'TEXT' else self._mysql_integer_type,
                notnull='NOT NULL' if column['notnull'] else 'NULL',
                auto_increment='AUTO_INCREMENT' if column['pk'] else ''
            )
            if column['pk']:
                primary_key = column['name']
        sql += ' PRIMARY KEY (`{}`) ) ENGINE = InnoDB CHARACTER SET utf8'.format(primary_key)
        try:
            self._mysql_cur.execute(sql)
            self._mysql.commit()
        except mysql.connector.Error as err:
            print('_create_table failed creating table {}: {}'.format(table_name, err))
            exit(1)

    def transfer(self):
        self._sqlite_cur.execute("SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%'")
        for row in self._sqlite_cur.fetchall():
            table = dict(row)
            # create the table
            self._create_table(table['name'])
            # populate it
            print('Transferring table {}'.format(table['name']))
            self._sqlite_cur.execute('SELECT * FROM "{}"'.format(table['name']))
            columns = [column[0] for column in self._sqlite_cur.description]
            try:
                self._mysql_cur.executemany("INSERT IGNORE INTO `{table}` ({fields}) VALUES ({placeholders})".format(
                    table=table['name'],
                    fields=('`{}`, ' * len(columns)).rstrip(' ,').format(*columns),
                    placeholders=('%s, ' * len(columns)).rstrip(' ,')
                ), (tuple(data) for data in self._sqlite_cur.fetchall()))
                self._mysql.commit()
            except mysql.connector.Error as err:
                print('_insert_table_data failed inserting data into table {}: {}'.format(table['name'], err))
                exit(1)
        print('Done!')


def main():
    """ For use in standalone terminal form """
    import sys, argparse
    parser = argparse.ArgumentParser()
    parser.add_argument('--sqlite-file', dest='sqlite_file', default=None, help='SQLite3 db file')
    parser.add_argument('--mysql-user', dest='mysql_user', default=None, help='MySQL user')
    parser.add_argument('--mysql-password', dest='mysql_password', default=None, help='MySQL password')
    parser.add_argument('--mysql-database', dest='mysql_database', default=None, help='MySQL host')
    parser.add_argument('--mysql-host', dest='mysql_host', default='localhost', help='MySQL host')
    parser.add_argument('--mysql-integer-type', dest='mysql_integer_type', default='int(11)', help='MySQL default integer field type')
    parser.add_argument('--mysql-string-type', dest='mysql_string_type', default='varchar(300)', help='MySQL default string field type')
    args = parser.parse_args()

    if len(sys.argv) == 1:
        parser.print_help()
        exit(1)

    converter = SQLite3toMySQL(
        sqlite_file=args.sqlite_file,
        mysql_user=args.mysql_user,
        mysql_password=args.mysql_password,
        mysql_database=args.mysql_database,
        mysql_host=args.mysql_host,
        mysql_integer_type=args.mysql_integer_type,
        mysql_string_type=args.mysql_string_type
    )
    converter.transfer()

if __name__ == '__main__':
    main()

Get current folder path

System.AppDomain.CurrentDomain.BaseDirectory

This will give you running directory of your application. This even works for web applications. Afterwards you can reach your file.

The difference between the 'Local System' account and the 'Network Service' account?

Since there is so much confusion about functionality of standard service accounts, I'll try to give a quick run down.

First the actual accounts:

  • LocalService account (preferred)

    A limited service account that is very similar to Network Service and meant to run standard least-privileged services. However, unlike Network Service it accesses the network as an Anonymous user.

    • Name: NT AUTHORITY\LocalService
    • the account has no password (any password information you provide is ignored)
    • HKCU represents the LocalService user account
    • has minimal privileges on the local computer
    • presents anonymous credentials on the network
    • SID: S-1-5-19
    • has its own profile under the HKEY_USERS registry key (HKEY_USERS\S-1-5-19)

     

  • NetworkService account

    Limited service account that is meant to run standard privileged services. This account is far more limited than Local System (or even Administrator) but still has the right to access the network as the machine (see caveat above).

    • NT AUTHORITY\NetworkService
    • the account has no password (any password information you provide is ignored)
    • HKCU represents the NetworkService user account
    • has minimal privileges on the local computer
    • presents the computer's credentials (e.g. MANGO$) to remote servers
    • SID: S-1-5-20
    • has its own profile under the HKEY_USERS registry key (HKEY_USERS\S-1-5-20)
    • If trying to schedule a task using it, enter NETWORK SERVICE into the Select User or Group dialog

     

  • LocalSystem account (dangerous, don't use!)

    Completely trusted account, more so than the administrator account. There is nothing on a single box that this account cannot do, and it has the right to access the network as the machine (this requires Active Directory and granting the machine account permissions to something)

    • Name: .\LocalSystem (can also use LocalSystem or ComputerName\LocalSystem)
    • the account has no password (any password information you provide is ignored)
    • SID: S-1-5-18
    • does not have any profile of its own (HKCU represents the default user)
    • has extensive privileges on the local computer
    • presents the computer's credentials (e.g. MANGO$) to remote servers

     

Above when talking about accessing the network, this refers solely to SPNEGO (Negotiate), NTLM and Kerberos and not to any other authentication mechanism. For example, processing running as LocalService can still access the internet.

The general issue with running as a standard out of the box account is that if you modify any of the default permissions you're expanding the set of things everything running as that account can do. So if you grant DBO to a database, not only can your service running as Local Service or Network Service access that database but everything else running as those accounts can too. If every developer does this the computer will have a service account that has permissions to do practically anything (more specifically the superset of all of the different additional privileges granted to that account).

It is always preferable from a security perspective to run as your own service account that has precisely the permissions you need to do what your service does and nothing else. However, the cost of this approach is setting up your service account, and managing the password. It's a balancing act that each application needs to manage.

In your specific case, the issue that you are probably seeing is that the the DCOM or COM+ activation is limited to a given set of accounts. In Windows XP SP2, Windows Server 2003, and above the Activation permission was restricted significantly. You should use the Component Services MMC snapin to examine your specific COM object and see the activation permissions. If you're not accessing anything on the network as the machine account you should seriously consider using Local Service (not Local System which is basically the operating system).


In Windows Server 2003 you cannot run a scheduled task as

  • NT_AUTHORITY\LocalService (aka the Local Service account), or
  • NT AUTHORITY\NetworkService (aka the Network Service account).

That capability only was added with Task Scheduler 2.0, which only exists in Windows Vista/Windows Server 2008 and newer.

A service running as NetworkService presents the machine credentials on the network. This means that if your computer was called mango, it would present as the machine account MANGO$:

enter image description here

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

Abort a git cherry-pick?

Try also with '--quit' option, which allows you to abort the current operation and further clear the sequencer state.

--quit Forget about the current operation in progress. Can be used to clear the sequencer state after a failed cherry-pick or revert.

--abort Cancel the operation and return to the pre-sequence state.

use help to see the original doc with more details, $ git help cherry-pick

I would avoid 'git reset --hard HEAD' that is too harsh and you might ended up doing some manual work.

How to change Toolbar home icon color

I solved it by editing styles.xml:

<style name="ToolbarColoredBackArrow" parent="AppTheme">
    <item name="android:textColorSecondary">INSERT_COLOR_HERE</item>
</style>

...then referencing the style in the Toolbar definition in the activity:

<LinearLayout
    android:id="@+id/main_parent_view"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <android.support.v7.widget.Toolbar
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:id="@+id/toolbar"
        app:theme="@style/ToolbarColoredBackArrow"
        app:popupTheme="@style/AppTheme"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:minHeight="?attr/actionBarSize"
        android:background="?attr/colorPrimary"/>

What is the difference between the HashMap and Map objects in Java?

Map is an interface that HashMap implements. The difference is that in the second implementation your reference to the HashMap will only allow the use of functions defined in the Map interface, while the first will allow the use of any public functions in HashMap (which includes the Map interface).

It will probably make more sense if you read Sun's interface tutorial

Clip/Crop background-image with CSS

Another option is to use linear-gradient() to cover up the edges of your image. Note that this is a stupid solution, so I'm not going to put much effort into explaining it...

_x000D_
_x000D_
.flair {_x000D_
  min-width: 50px; /* width larger than sprite */_x000D_
  text-indent: 60px;_x000D_
  height: 25px;_x000D_
  display: inline-block;_x000D_
  background:_x000D_
    linear-gradient(#F00, #F00) 50px 0/999px 1px repeat-y,_x000D_
    url('https://championmains.github.io/dynamicflairs/riven/spritesheet.png') #F00;_x000D_
}_x000D_
_x000D_
.flair-classic {_x000D_
  background-position: 50px 0, 0 -25px;_x000D_
}_x000D_
_x000D_
.flair-r2 {_x000D_
  background-position: 50px 0, -50px -175px;_x000D_
}_x000D_
_x000D_
.flair-smite {_x000D_
  text-indent: 35px;_x000D_
  background-position: 25px 0, -50px -25px;_x000D_
}
_x000D_
<img src="https://championmains.github.io/dynamicflairs/riven/spritesheet.png" alt="spritesheet" /><br />_x000D_
<br />_x000D_
<span class="flair flair-classic">classic sprite</span><br /><br />_x000D_
<span class="flair flair-r2">r2 sprite</span><br /><br />_x000D_
<span class="flair flair-smite">smite sprite</span><br /><br />
_x000D_
_x000D_
_x000D_

I'm using this method on this page: https://championmains.github.io/dynamicflairs/riven/ and can't use ::before or ::after elements because I'm already using them for another hack.

Regex to match URL end-of-line or "/" character

/(.+)/(\d{4}-\d{2}-\d{2})-(\d+)(/.*)?$

1st Capturing Group (.+)

.+ matches any character (except for line terminators)

  • + Quantifier — Matches between one and unlimited times, as many times as possible, giving back as needed (greedy)

2nd Capturing Group (\d{4}-\d{2}-\d{2})

\d{4} matches a digit (equal to [0-9])

  • {4} Quantifier — Matches exactly 4 times

- matches the character - literally (case sensitive)

\d{2} matches a digit (equal to [0-9])

  • {2} Quantifier — Matches exactly 2 times

- matches the character - literally (case sensitive)

\d{2} matches a digit (equal to [0-9])

  • {2} Quantifier — Matches exactly 2 times

- matches the character - literally (case sensitive)

3rd Capturing Group (\d+)

\d+ matches a digit (equal to [0-9])

  • + Quantifier — Matches between one and unlimited times, as many times as possible, giving back as needed (greedy)

4th Capturing Group (.*)?

? Quantifier — Matches between zero and one times, as many times as possible, giving back as needed (greedy)

.* matches any character (except for line terminators)

  • * Quantifier — Matches between zero and unlimited times, as many times as possible, giving back as needed (greedy)

$ asserts position at the end of the string

how to open an URL in Swift3

All you need is:

guard let url = URL(string: "http://www.google.com") else {
  return //be safe
}

if #available(iOS 10.0, *) {
    UIApplication.shared.open(url, options: [:], completionHandler: nil)
} else {
    UIApplication.shared.openURL(url)
}

Declare Variable for a Query String

I will point out that in the article linked in the top rated answer The Curse and Blessings of Dynamic SQL the author states that the answer is not to use dynamic SQL. Scroll almost to the end to see this.

From the article: "The correct method is to unpack the list into a table with a user-defined function or a stored procedure."

Of course, once the list is in a table you can use a join. I could not comment directly on the top rated answer, so I just added this comment.

How do I remove objects from a JavaScript associative array?

It's very straightforward if you have an Underscore.js dependency in your project -

_.omit(myArray, "lastname")

Pandas Split Dataframe into two Dataframes at a specific row

I generally use array split because it's easier simple syntax and scales better with more than 2 partitions.

import numpy as np
partitions = 2
dfs = np.array_split(df, partitions)

np.split(df, [100,200,300], axis=0] wants explicit index numbers which may or may not be desirable.

asp.net: How can I remove an item from a dropdownlist?

You can use this:

myDropDown.Items.Remove(myDropDown.Items.FindByValue("TextToFind"));

What is dynamic programming?

It's an optimization of your algorithm that cuts running time.

While a Greedy Algorithm is usually called naive, because it may run multiple times over the same set of data, Dynamic Programming avoids this pitfall through a deeper understanding of the partial results that must be stored to help build the final solution.

A simple example is traversing a tree or a graph only through the nodes that would contribute with the solution, or putting into a table the solutions that you've found so far so you can avoid traversing the same nodes over and over.

Here's an example of a problem that's suited for dynamic programming, from UVA's online judge: Edit Steps Ladder.

I'm going to make quick briefing of the important part of this problem's analysis, taken from the book Programming Challenges, I suggest you check it out.

Take a good look at that problem, if we define a cost function telling us how far appart two strings are, we have two consider the three natural types of changes:

Substitution - change a single character from pattern "s" to a different character in text "t", such as changing "shot" to "spot".

Insertion - insert a single character into pattern "s" to help it match text "t", such as changing "ago" to "agog".

Deletion - delete a single character from pattern "s" to help it match text "t", such as changing "hour" to "our".

When we set each of this operations to cost one step we define the edit distance between two strings. So how do we compute it?

We can define a recursive algorithm using the observation that the last character in the string must be either matched, substituted, inserted or deleted. Chopping off the characters in the last edit operation leaves a pair operation leaves a pair of smaller strings. Let i and j be the last character of the relevant prefix of and t, respectively. there are three pairs of shorter strings after the last operation, corresponding to the string after a match/substitution, insertion or deletion. If we knew the cost of editing the three pairs of smaller strings, we could decide which option leads to the best solution and choose that option accordingly. We can learn this cost, through the awesome thing that's recursion:

#define MATCH 0 /* enumerated type symbol for match */
#define INSERT 1 /* enumerated type symbol for insert */
#define DELETE 2 /* enumerated type symbol for delete */


int string_compare(char *s, char *t, int i, int j)

{

    int k; /* counter */
    int opt[3]; /* cost of the three options */
    int lowest_cost; /* lowest cost */
    if (i == 0) return(j * indel(’ ’));
    if (j == 0) return(i * indel(’ ’));
    opt[MATCH] = string_compare(s,t,i-1,j-1) +
      match(s[i],t[j]);
    opt[INSERT] = string_compare(s,t,i,j-1) +
      indel(t[j]);
    opt[DELETE] = string_compare(s,t,i-1,j) +
      indel(s[i]);
    lowest_cost = opt[MATCH];
    for (k=INSERT; k<=DELETE; k++)
    if (opt[k] < lowest_cost) lowest_cost = opt[k];
    return( lowest_cost );

}

This algorithm is correct, but is also impossibly slow.

Running on our computer, it takes several seconds to compare two 11-character strings, and the computation disappears into never-never land on anything longer.

Why is the algorithm so slow? It takes exponential time because it recomputes values again and again and again. At every position in the string, the recursion branches three ways, meaning it grows at a rate of at least 3^n – indeed, even faster since most of the calls reduce only one of the two indices, not both of them.

So how can we make the algorithm practical? The important observation is that most of these recursive calls are computing things that have already been computed before. How do we know? Well, there can only be |s| · |t| possible unique recursive calls, since there are only that many distinct (i, j) pairs to serve as the parameters of recursive calls.

By storing the values for each of these (i, j) pairs in a table, we can avoid recomputing them and just look them up as needed.

The table is a two-dimensional matrix m where each of the |s|·|t| cells contains the cost of the optimal solution of this subproblem, as well as a parent pointer explaining how we got to this location:

typedef struct {
int cost; /* cost of reaching this cell */
int parent; /* parent cell */
} cell;

cell m[MAXLEN+1][MAXLEN+1]; /* dynamic programming table */

The dynamic programming version has three differences from the recursive version.

First, it gets its intermediate values using table lookup instead of recursive calls.

**Second,**it updates the parent field of each cell, which will enable us to reconstruct the edit sequence later.

**Third,**Third, it is instrumented using a more general goal cell() function instead of just returning m[|s|][|t|].cost. This will enable us to apply this routine to a wider class of problems.

Here, a very particular analysis of what it takes to gather the most optimal partial results, is what makes the solution a "dynamic" one.

Here's an alternate, full solution to the same problem. It's also a "dynamic" one even though its execution is different. I suggest you check out how efficient the solution is by submitting it to UVA's online judge. I find amazing how such a heavy problem was tackled so efficiently.

Regular expression negative lookahead

A negative lookahead says, at this position, the following regex can not match.

Let's take a simplified example:

a(?!b(?!c))

a      Match: (?!b) succeeds
ac     Match: (?!b) succeeds
ab     No match: (?!b(?!c)) fails
abe    No match: (?!b(?!c)) fails
abc    Match: (?!b(?!c)) succeeds

The last example is a double negation: it allows a b followed by c. The nested negative lookahead becomes a positive lookahead: the c should be present.

In each example, only the a is matched. The lookahead is only a condition, and does not add to the matched text.

Change the icon of the exe file generated from Visual Studio 2010

I found it easier to edit the project file directly e.g. YourApp.csproj.

You can do this by modifying ApplicationIcon property element:

<ApplicationIcon>..\Path\To\Application.ico</ApplicationIcon>

Also, if you create an MSI installer for your application e.g. using WiX, you can use the same icon again for display in Add/Remove Programs. See tip 5 here.

Validate that a string is a positive integer

My function checks if number is +ve and could be have decimal value as well.

       function validateNumeric(numValue){
            var value = parseFloat(numValue);
            if (!numValue.toString().match(/^[-]?\d*\.?\d*$/)) 
                    return false;
            else if (numValue < 0) {
                return false;
            }
            return true;        
        }

How do I remove whitespace from the end of a string in Python?

>>> "    xyz     ".rstrip()
'    xyz'

There is more about rstrip in the documentation.

How to multiply duration by integer?

My turn:

https://play.golang.org/p/RifHKsX7Puh

package main

import (
    "fmt"
    "time"
)

func main() {
    var n int = 77
    v := time.Duration( 1.15 * float64(n) ) * time.Second

    fmt.Printf("%v %T", v, v)
}

It helps to remember the simple fact, that underlyingly the time.Duration is a mere int64, which holds nanoseconds value.

This way, conversion to/from time.Duration becomes a formality. Just remember:

  • int64
  • always nanosecs

How to make a redirection on page load in JSF 1.x

Assume that foo.jsp is your jsp file. and following code is the button that you want do redirect.

<h:commandButton value="Redirect" action="#{trial.enter }"/>  

And now we'll check the method for directing in your java (service) class

 public String enter() {
            if (userName.equals("xyz") && password.equals("123")) {
                return "enter";
            } else {
                return null;
            }
        } 

and now this is a part of faces-config.xml file

<managed-bean>
        <managed-bean-name>'class_name'</managed-bean-name>
        <managed-bean-class>'package_name'</managed-bean-class>
        <managed-bean-scope>request</managed-bean-scope>
    </managed-bean>


    <navigation-case>
                <from-outcome>enter</from-outcome>
                <to-view-id>/foo.jsp</to-view-id>
                <redirect />
            </navigation-case>

Avoiding "resource is out of sync with the filesystem"

This happens to me all the time.

Go to the error log, find the exception, and open a few levels until you can see something more like a root cause. Does it says "Resource is out of sync with the file system" ?

When renaming packages, of course, Eclipse has to move files around in the file system. Apparently what happens is that it later discovers that something it thinks it needs to clean up has been renamed, can't find it, throws an exception.

There are a couple of things you might try. First, go to Window: Preferences, Workspace, and enable "Refresh Automatically". In theory this should fix the problem, but for me, it didn't.

Second, if you are doing a large refactoring with subpackages, do the subpackages one at a time, from the bottom up, and explicitly refresh with the file system after each subpackage is renamed.

Third, just ignore the error: when the error dialog comes up, click Abort to preserve the partial change, instead of rolling it back. Try it again, and again, and you may find you can get through the entire operation using multiple retries.

Extract Month and Year From Date in R

Use substring?

d = "2004-02-06"
substr(d,0,7)
>"2004-02"

filters on ng-model in an input

If you are using read only input field, you can use ng-value with filter.

for example:

ng-value="price | number:8"

Purpose of ESI & EDI registers?

In addition to the registers being used for mass operations, they are useful for their property of being preserved through a function call (call-preserved) in 32-bit calling convention. The ESI, EDI, EBX, EBP, ESP are call-preserved whereas EAX, ECX and EDX are not call-preserved. Call-preserved registers are respected by C library function and their values persist through the C library function calls.

Jeff Duntemann in his assembly language book has an example assembly code for printing the command line arguments. The code uses esi and edi to store counters as they will be unchanged by the C library function printf. For other registers like eax, ecx, edx, there is no guarantee of them not being used by the C library functions.

https://www.amazon.com/Assembly-Language-Step-Step-Programming/dp/0470497025

See section 12.8 How C sees Command-Line Arguments.

Note that 64-bit calling conventions are different from 32-bit calling conventions, and I am not sure if these registers are call-preserved or not.

Use a list of values to select rows from a pandas dataframe

You can use isin method:

In [1]: df = pd.DataFrame({'A': [5,6,3,4], 'B': [1,2,3,5]})

In [2]: df
Out[2]:
   A  B
0  5  1
1  6  2
2  3  3
3  4  5

In [3]: df[df['A'].isin([3, 6])]
Out[3]:
   A  B
1  6  2
2  3  3

And to get the opposite use ~:

In [4]: df[~df['A'].isin([3, 6])]
Out[4]:
   A  B
0  5  1
3  4  5

Quick Way to Implement Dictionary in C

Section 6.6 of The C Programming Language presents a simple dictionary (hashtable) data structure. I don't think a useful dictionary implementation could get any simpler than this. For your convenience, I reproduce the code here.

struct nlist { /* table entry: */
    struct nlist *next; /* next entry in chain */
    char *name; /* defined name */
    char *defn; /* replacement text */
};

#define HASHSIZE 101
static struct nlist *hashtab[HASHSIZE]; /* pointer table */

/* hash: form hash value for string s */
unsigned hash(char *s)
{
    unsigned hashval;
    for (hashval = 0; *s != '\0'; s++)
      hashval = *s + 31 * hashval;
    return hashval % HASHSIZE;
}

/* lookup: look for s in hashtab */
struct nlist *lookup(char *s)
{
    struct nlist *np;
    for (np = hashtab[hash(s)]; np != NULL; np = np->next)
        if (strcmp(s, np->name) == 0)
          return np; /* found */
    return NULL; /* not found */
}

char *strdup(char *);
/* install: put (name, defn) in hashtab */
struct nlist *install(char *name, char *defn)
{
    struct nlist *np;
    unsigned hashval;
    if ((np = lookup(name)) == NULL) { /* not found */
        np = (struct nlist *) malloc(sizeof(*np));
        if (np == NULL || (np->name = strdup(name)) == NULL)
          return NULL;
        hashval = hash(name);
        np->next = hashtab[hashval];
        hashtab[hashval] = np;
    } else /* already there */
        free((void *) np->defn); /*free previous defn */
    if ((np->defn = strdup(defn)) == NULL)
       return NULL;
    return np;
}

char *strdup(char *s) /* make a duplicate of s */
{
    char *p;
    p = (char *) malloc(strlen(s)+1); /* +1 for ’\0’ */
    if (p != NULL)
       strcpy(p, s);
    return p;
}

Note that if the hashes of two strings collide, it may lead to an O(n) lookup time. You can reduce the likelihood of collisions by increasing the value of HASHSIZE. For a complete discussion of the data structure, please consult the book.

Change selected value of kendo ui dropdownlist

You have to use Kendo UI DropDownList select method (documentation in here).

Basically you should:

// get a reference to the dropdown list
var dropdownlist = $("#Instrument").data("kendoDropDownList");

If you know the index you can use:

// selects by index
dropdownlist.select(1);

If not, use:

// selects item if its text is equal to "test" using predicate function
dropdownlist.select(function(dataItem) {
    return dataItem.symbol === "test";
});

JSFiddle example here

How to get post slug from post in WordPress?

You can get that using the following methods:

<?php $post_slug = get_post_field( 'post_name', get_post() ); ?>

Or You can use this easy code:

<?php
    global $post;
    $post_slug = $post->post_name;
?>

PHP - SSL certificate error: unable to get local issuer certificate

I tried this it works

open

vendor\guzzlehttp\guzzle\src\Handler\CurlFactory.php

and change this

 $conf[CURLOPT_SSL_VERIFYHOST] = 2;
 `enter code here`$conf[CURLOPT_SSL_VERIFYPEER] = true;

to this

$conf[CURLOPT_SSL_VERIFYHOST] = 0;
$conf[CURLOPT_SSL_VERIFYPEER] = FALSE;

Draw horizontal rule in React Native

One can use margin in order to change the width of a line and place it center.

import { StyleSheet } from 'react-native;
<View style = {styles.lineStyle} />

const styles = StyleSheet.create({
  lineStyle:{
        borderWidth: 0.5,
        borderColor:'black',
        margin:10,
   }
 });

if you want to give margin dynamically then you can use Dimension width.

What are the JavaScript KeyCodes?

http://keycodes.atjayjo.com/

This app is just awesome. It is essentially a virtual keyboard that immediately shows you the keycode pressed on a standard US keyboard.

How do you handle multiple submit buttons in ASP.NET MVC Framework?

My Solution was to use 2 asp panels:

<asp:Panel ID=”..” DefaultButton=”ID_OF_SHIPPING_SUBMIT_BUTTON”….></asp:Panel>

How to reset the use/password of jenkins on windows?

You can try to re-set your Jenkins security:

  1. Stop the Jenkins service
  2. Open the config.xml with a text editor (i.e notepad++), maybe be in C:\jenkins\config.xml (could backup it also).
  3. Find this <useSecurity>true</useSecurity> and change it to <useSecurity>false</useSecurity>
  4. Start Jenkins service

You might create an admin user and enable security again.

Differences Between vbLf, vbCrLf & vbCr Constants

 Constant   Value               Description
 ----------------------------------------------------------------
 vbCr       Chr(13)             Carriage return
 vbCrLf     Chr(13) & Chr(10)   Carriage return–linefeed combination
 vbLf       Chr(10)             Line feed
  • vbCr : - return to line beginning
    Represents a carriage-return character for print and display functions.

  • vbCrLf : - similar to pressing Enter
    Represents a carriage-return character combined with a linefeed character for print and display functions.

  • vbLf : - go to next line
    Represents a linefeed character for print and display functions.


Read More from Constants Class

How to update all MySQL table rows at the same time?

just use UPDATE query without condition like this

 UPDATE tablename SET online_status=0;

JSON array get length

have you tried size() ? Something like :

jar.size();

Hope it helps.

Warning: Attempt to present * on * whose view is not in the window hierarchy - swift

Swift 3

I had this keep coming up as a newbie and found that present loads modal views that can be dismissed but switching to root controller is best if you don't need to show a modal.

I was using this

let storyboard = UIStoryboard(name: "Main", bundle: nil)
let vc  = storyboard?.instantiateViewController(withIdentifier: "MainAppStoryboard") as! TabbarController
present(vc, animated: false, completion: nil)

Using this instead with my tabController:

let storyboard = UIStoryboard(name: "Main", bundle: nil)
let view = storyboard.instantiateViewController(withIdentifier: "MainAppStoryboard") as UIViewController
let appDelegate = UIApplication.shared.delegate as! AppDelegate
//show window
appDelegate.window?.rootViewController = view

Just adjust to a view controller if you need to switch between multiple storyboard screens.

System.BadImageFormatException: Could not load file or assembly

It seems that you are using the 64-bit version of the tool to install a 32-bit/x86 architecture application. Look for the 32-bit version of the tool here:

C:\Windows\Microsoft.NET\Framework\v4.0.30319

and it should install your 32-bit application just fine.

run a python script in terminal without the python command

Add the following line to the beginning script1.py

#!/usr/bin/env python

and then make the script executable:

$ chmod +x script1.py

If the script resides in a directory that appears in your PATH variable, you can simply type

$ script1.py

Otherwise, you'll need to provide the full path (either absolute or relative). This includes the current working directory, which should not be in your PATH.

$ ./script1.py

Where to place and how to read configuration resource files in servlet based application?

Word of warning: if you put config files in your WEB-INF/classes folder, and your IDE, say Eclipse, does a clean/rebuild, it will nuke your conf files unless they were in the Java source directory. BalusC's great answer alludes to that in option 1 but I wanted to add emphasis.

I learned the hard way that if you "copy" a web project in Eclipse, it does a clean/rebuild from any source folders. In my case I had added a "linked source dir" from our POJO java library, it would compile to the WEB-INF/classes folder. Doing a clean/rebuild in that project (not the web app project) caused the same problem.

I thought about putting my confs in the POJO src folder, but these confs are all for 3rd party libs (like Quartz or URLRewrite) that are in the WEB-INF/lib folder, so that didn't make sense. I plan to test putting it in the web projects "src" folder when i get around to it, but that folder is currently empty and having conf files in it seems inelegant.

So I vote for putting conf files in WEB-INF/commonConfFolder/filename.properties, next to the classes folder, which is Balus option 2.

ERROR 1044 (42000): Access denied for user ''@'localhost' to database 'db'

You may need to set up a root account for your MySQL database:

In the terminal type:

mysqladmin -u root password 'root password goes here'

And then to invoke the MySQL client:

mysql -h localhost -u root -p

What is better, adjacency lists or adjacency matrices for graph problems in C++?

Okay, I've compiled the Time and Space complexities of basic operations on graphs.
The image below should be self-explanatory.
Notice how Adjacency Matrix is preferable when we expect the graph to be dense, and how Adjacency List is preferable when we expect the graph to be sparse.
I've made some assumptions. Ask me if a complexity (Time or Space) needs clarification. (For example, For a sparse graph, I've taken En to be a small constant, as I've assumed that addition of a new vertex will add only a few edges, because we expect the graph to remain sparse even after adding that vertex.)

Please tell me if there are any mistakes.

enter image description here

Hibernate-sequence doesn't exist

In my case, replacing all annotations GenerationType.AUTO by GenerationType.SEQUENCE solved the issue.

Refresh DataGridView when updating data source

Well, it doesn't get much better than that. Officially, you should use

dataGridView1.DataSource = typeof(List); 
dataGridView1.DataSource = itemStates;

It's still a "clear/reset source" kind of solution, but I have yet to find anything else that would reliably refresh the DGV data source.

SQL - Rounding off to 2 decimal places

Convert your number to a Numeric or Decimal.

Replace your query with the following.

Sql server

Select Convert(Numeric(38, 2), Minutes/60.0) from ....

MySql:

Select Convert(Minutes/60.0, Decimal(65, 2)) from ....

The Cast function is a wrapper for the Convert function. Couple that with SQL being an interpreted language and the result is that even though the two functions produce the same results, there is slightly more going on behind the scenes in the Cast function. Using the Convert function is a small saving, but small savings multiply. The parameters for Numeric and Decimal (38, 2) and (65, 2) represent the maximum precision level and decimal places to use.

Python: find position of element in array

There is a built in method for doing this:

numpy.where()

You can find out more about it in the excellent detailed documentation.

Formatting "yesterday's" date in python

all answers are correct, but I want to mention that time delta accepts negative arguments.

>>> from datetime import date, timedelta
>>> yesterday = date.today() + timedelta(days=-1)
>>> print(yesterday.strftime('%m%d%y')) #for python2 remove parentheses 

How do I print to the debug output window in a Win32 app?

Consider using the VC++ runtime Macros for Reporting _RPTN() and _RPTFN()

You can use the _RPTn, and _RPTFn macros, defined in CRTDBG.H, to replace the use of printf statements for debugging. These macros automatically disappear in your release build when _DEBUG is not defined, so there is no need to enclose them in #ifdefs.

Example...

if (someVar > MAX_SOMEVAR) {
    _RPTF2(_CRT_WARN, "In NameOfThisFunc( )," 
         " someVar= %d, otherVar= %d\n", someVar, otherVar );
}

Or you can use the VC++ runtime functions _CrtDbgReport, _CrtDbgReportW directly.

_CrtDbgReport and _CrtDbgReportW can send the debug report to three different destinations: a debug report file, a debug monitor (the Visual Studio debugger), or a debug message window.

_CrtDbgReport and _CrtDbgReportW create the user message for the debug report by substituting the argument[n] arguments into the format string, using the same rules defined by the printf or wprintf functions. These functions then generate the debug report and determine the destination or destinations, based on the current report modes and file defined for reportType. When the report is sent to a debug message window, the filename, lineNumber, and moduleName are included in the information displayed in the window.

Bootstrap modal: close current, open new

I use this method:

$(function() {
  return $(".modal").on("show.bs.modal", function() {
    var curModal;
    curModal = this;
    $(".modal").each(function() {
      if (this !== curModal) {
        $(this).modal("hide");
      }
    });
  });
});

cast_sender.js error: Failed to load resource: net::ERR_FAILED in Chrome

A simple fix for this is to install the Google Cast extension. If you don't have a Chromecast, or don't want to use the extension, no problem; just don't use the extension.

How to make an android app to always run in background?

You have to start a service in your Application class to run it always. If you do that, your service will be always running. Even though user terminates your app from task manager or force stop your app, it will start running again.

Create a service:

public class YourService extends Service {

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        // do your jobs here
        return super.onStartCommand(intent, flags, startId);
    }
}

Create an Application class and start your service:

public class App extends Application {

    @Override
    public void onCreate() {
        super.onCreate();

        startService(new Intent(this, YourService.class));
    }
}

Add "name" attribute into the "application" tag of your AndroidManifest.xml

android:name=".App"

Also, don't forget to add your service in the "application" tag of your AndroidManifest.xml

<service android:name=".YourService"/>

And also this permission request in the "manifest" tag (if API level 28 or higher):

<uses-permission android:name="android.permission.FOREGROUND_SERVICE"/>

UPDATE

After Android Oreo, Google introduced some background limitations. Therefore, this solution above won't work probably. When a user kills your app from task manager, Android System will kill your service as well. If you want to run a service which is always alive in the background. You have to run a foreground service with showing an ongoing notification. So, edit your service like below.

public class YourService extends Service {

    private static final int NOTIF_ID = 1;
    private static final String NOTIF_CHANNEL_ID = "Channel_Id";

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId){

        // do your jobs here

        startForeground();
        
        return super.onStartCommand(intent, flags, startId);
    }

    private void startForeground() {
        Intent notificationIntent = new Intent(this, MainActivity.class);

        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,
                notificationIntent, 0);

        startForeground(NOTIF_ID, new NotificationCompat.Builder(this, 
                NOTIF_CHANNEL_ID) // don't forget create a notification channel first
                .setOngoing(true)
                .setSmallIcon(R.drawable.ic_notification)
                .setContentTitle(getString(R.string.app_name))
                .setContentText("Service is running background")
                .setContentIntent(pendingIntent)
                .build());         
    }
}

EDIT: RESTRICTED OEMS

Unfortunately, some OEMs (Xiaomi, OnePlus, Samsung, Huawei etc.) restrict background operations due to provide longer battery life. There is no proper solution for these OEMs. Users need to allow some special permissions that are specific for OEMs or they need to add your app into whitelisted app list by device settings. You can find more detail information from https://dontkillmyapp.com/.

If background operations are an obligation for you, you need to explain it to your users why your feature is not working and how they can enable your feature by allowing those permissions. I suggest you to use AutoStarter library (https://github.com/judemanutd/AutoStarter) in order to redirect your users regarding permissions page easily from your app.

By the way, if you need to run some periodic work instead of having continuous background job. You better take a look WorkManager (https://developer.android.com/topic/libraries/architecture/workmanager)

How to store NULL values in datetime fields in MySQL?

I just tested in MySQL v5.0.6 and the datetime column accepted null without issue.

PowerShell to remove text from a string

This should do what you want:

C:\PS> if ('=keep this,' -match '=([^,]*)') { $matches[1] }
keep this

Most recent previous business day in Python

Maybe this code could help:

lastBusDay = datetime.datetime.today()
shift = datetime.timedelta(max(1,(lastBusDay.weekday() + 6) % 7 - 3))
lastBusDay = lastBusDay - shift

The idea is that on Mondays yo have to go back 3 days, on Sundays 2, and 1 in any other day.

The statement (lastBusDay.weekday() + 6) % 7 just re-bases the Monday from 0 to 6.

Really don't know if this will be better in terms of performance.

Windows batch script to unhide files hidden by virus

Try this.

Does not require any options to change.

Does not require any command line activity.

Just run software and you will done the job.

www.vhghorecha.in/unhide-all-files-folders-virus/

Happy Knowledge Sharing

What is the main difference between Collection and Collections in Java?

Are you asking about the Collections class versus the classes which implement the Collection interface?

If so, the Collections class is a utility class having static methods for doing operations on objects of classes which implement the Collection interface. For example, Collections has methods for finding the max element in a Collection.

The Collection interface defines methods common to structures which hold other objects. List and Set are subinterfaces of Collection, and ArrayList and HashSet are examples of concrete collections.

Detecting scroll direction

This is an addition to what prateek has answered.There seems to be a glitch in the code in IE so i decided to modify it a bit nothing fancy(just another condition)

$('document').ready(function() {
var lastScrollTop = 0;
$(window).scroll(function(event){
   var st = $(this).scrollTop();
   if (st > lastScrollTop){
       console.log("down")
   }
   else if(st == lastScrollTop)
   {
     //do nothing 
     //In IE this is an important condition because there seems to be some instances where the last scrollTop is equal to the new one
   }
   else {
      console.log("up")
   }
   lastScrollTop = st;
});});

addID in jQuery?

ID is an attribute, you can set it with the attr function:

$(element).attr('id', 'newID');

I'm not sure what you mean about adding IDs since an element can only have one identifier and this identifier must be unique.

CSS Background Image Not Displaying

I was having the same issue, after i remove the repeat 0 0 part, it solved my problem.

How to import CSV file data into a PostgreSQL table?

How to import CSV file data into a PostgreSQL table?

steps:

  1. Need to connect postgresql database in terminal

    psql -U postgres -h localhost
    
  2. Need to create database

    create database mydb;
    
  3. Need to create user

    create user siva with password 'mypass';
    
  4. Connect with database

    \c mydb;
    
  5. Need to create schema

    create schema trip;
    
  6. Need to create table

    create table trip.test(VendorID int,passenger_count int,trip_distance decimal,RatecodeID int,store_and_fwd_flag varchar,PULocationID int,DOLocationID int,payment_type decimal,fare_amount decimal,extra decimal,mta_tax decimal,tip_amount decimal,tolls_amount int,improvement_surcharge decimal,total_amount
    );
    
  7. Import csv file data to postgresql

    COPY trip.test(VendorID int,passenger_count int,trip_distance decimal,RatecodeID int,store_and_fwd_flag varchar,PULocationID int,DOLocationID int,payment_type decimal,fare_amount decimal,extra decimal,mta_tax decimal,tip_amount decimal,tolls_amount int,improvement_surcharge decimal,total_amount) FROM '/home/Documents/trip.csv' DELIMITER ',' CSV HEADER;
    
  8. Find the given table data

    select * from trip.test;
    

ValueError: invalid literal for int () with base 10

So if you have

floatInString = '5.0'

You can convert it to int with floatInInt = int(float(floatInString))

ActionController::InvalidAuthenticityToken

In rails 5, we need to add 2 lines of code

    skip_before_action :verify_authenticity_token
    protect_from_forgery prepend: true, with: :exception

How to install gdb (debugger) in Mac OSX El Capitan?

Please note that this answer was written for Mac OS El Capitan. For newer versions, beware that it may no longer apply. In particular, the legacy option is quite possibly deprecated.

There are two solutions to the problem, and they are both mentioned in other answers to this question and to How to get gdb to work using macports under OSX 10.11 El Capitan?, but to clear up some confusion here is my summary (as an answer since it got a bit long for a comment):

Which alternative is more secure I guess boils down to the choice between 1) trusting self-signed certificates and 2) giving users more privileges.

Alternative 1: signing the binary

If the signature alternative is used, disabling SIP to add the -p option to taskgated is not required.

However, note that with this alternative, debugging is only allowed for users in the _developer group.

Using codesign to sign using a cert named gdb-cert:

codesign -s gdb-cert /opt/local/bin/ggdb

(using the MacPorts standard path, adopt as necessary)

For detailed code-signing recipes (incl cert creation), see : https://gcc.gnu.org/onlinedocs/gcc-4.8.1/gnat_ugn_unw/Codesigning-the-Debugger.html or https://sourceware.org/gdb/wiki/BuildingOnDarwin

Note that you need to restart the keychain application and the taskgated service during and after the process (the easiest way is to reboot).

Alternative 2: use the legacy option for taskgated

As per the answer by @user14241, disabling SIP and adding the -p option to taskgated is an option. Note that if using this option, signing the binary is not needed, and it also bypasses the dialog for authenticating as a member of the Developer Tools group (_developer).

After adding the -p option (allow groups procmod and procview) to taskgated you also need to add the users that should be allowed to use gdb to the procmod group.

The recipe is:

  1. restart in recovery mode, open a terminal and run csrutil disable

  2. restart machine and edit /System/Library/LaunchDaemons/com.apple.taskgated.plist, adding the -p opion:

    <array>
        <string>/usr/libexec/taskgated</string>
        <string>-sp</string>
    </array>
    
  3. restart in recovery mode to reenable SIP (csrutil enable)

  4. restart machine and add user USERNAME to the group procmod:

    sudo dseditgroup -o edit -a USERNAME -t user procmod

    An alternative that does not involve adding users to groups is to make the executable setgid procmod, as that also makes procmod the effective group id of any user executing the setgid binary (suggested in https://apple.stackexchange.com/a/112132)

    sudo chgrp procmod /path/to/gdb
    sudo chmod g+s /path/to/gdb 
    

how to hide <li> bullets in navigation menu and footer links BUT show them for listing items

You can also define a class for the bullets you want to show, so in the CSS:

ul {list-style:none; list-style-type:none; list-style-image:none;}

And in the HTML you just define which lists to show:

<ul style="list-style:disc;">

Or you alternatively define a CSS class:

.show-list {list-style:disc;}

Then apply it to the list you want to show:

<ul class="show-list">

All other lists won't show the bullets...

How to generate a git patch for a specific commit?

If you want to be sure the (single commit) patch will be applied on top of a specific commit, you can use the new git 2.9 (June 2016) option git format-patch --base

git format-patch --base=COMMIT_VALUE~ -M -C COMMIT_VALUE~..COMMIT_VALUE

# or
git format-patch --base=auto -M -C COMMIT_VALUE~..COMMIT_VALUE

# or
git config format.useAutoBase true
git format-patch -M -C COMMIT_VALUE~..COMMIT_VALUE

See commit bb52995, commit 3de6651, commit fa2ab86, commit ded2c09 (26 Apr 2016) by Xiaolong Ye (``).
(Merged by Junio C Hamano -- gitster -- in commit 72ce3ff, 23 May 2016)

format-patch: add '--base' option to record base tree info

Maintainers or third party testers may want to know the exact base tree the patch series applies to. Teach git format-patch a '--base' option to record the base tree info and append it at the end of the first message (either the cover letter or the first patch in the series).

The base tree info consists of the "base commit", which is a well-known commit that is part of the stable part of the project history everybody else works off of, and zero or more "prerequisite patches", which are well-known patches in flight that is not yet part of the "base commit" that need to be applied on top of "base commit" in topological order before the patches can be applied.

The "base commit" is shown as "base-commit: " followed by the 40-hex of the commit object name.
A "prerequisite patch" is shown as "prerequisite-patch-id: " followed by the 40-hex "patch id", which can be obtained by passing the patch through the "git patch-id --stable" command.


Git 2.23 (Q3 2019) will improve that, because the "--base" option of "format-patch" computed the patch-ids for prerequisite patches in an unstable way, which has been updated to compute in a way that is compatible with "git patch-id --stable".

See commit a8f6855, commit 6f93d26 (26 Apr 2019) by Stephen Boyd (akshayka).
(Merged by Junio C Hamano -- gitster -- in commit 8202d12, 13 Jun 2019)

format-patch: make --base patch-id output stable

We weren't flushing the context each time we processed a hunk in the patch-id generation code in diff.c, but we were doing that when we generated "stable" patch-ids with the 'patch-id' tool.

Let's port that similar logic over from patch-id.c into diff.c so we can get the same hash when we're generating patch-ids for 'format-patch --base=' types of command invocations.


Before Git 2.24 (Q4 2019), "git format-patch -o <outdir>" did an equivalent of "mkdir <outdir>" not "mkdir -p <outdir>", which is being corrected.

See commit edefc31 (11 Oct 2019) by Bert Wesarg (bertwesarg).
(Merged by Junio C Hamano -- gitster -- in commit f1afbb0, 18 Oct 2019)

format-patch: create leading components of output directory

Signed-off-by: Bert Wesarg

'git format-patch -o ' did an equivalent of 'mkdir <outdir>' not 'mkdir -p <outdir>', which is being corrected.

Avoid the usage of 'adjust_shared_perm' on the leading directories which may have security implications. Achieved by temporarily disabling of 'config.sharedRepository' like 'git init' does.


With Git 2.25 (Q1 2020), "git rebase" did not work well when format.useAutoBase configuration variable is set, which has been corrected.

See commit cae0bc0, commit 945dc55, commit 700e006, commit a749d01, commit 0c47e06 (04 Dec 2019) by Denton Liu (Denton-L).
(Merged by Junio C Hamano -- gitster -- in commit 71a7de7, 16 Dec 2019)

rebase: fix format.useAutoBase breakage

Reported-by: Christian Biesinger
Signed-off-by: Denton Liu

With format.useAutoBase = true, running rebase resulted in an error:

fatal: failed to get upstream, if you want to record base commit automatically,
please use git branch --set-upstream-to to track a remote branch.
Or you could specify base commit by --base=<base-commit-id> manually
error:
git encountered an error while preparing the patches to replay
these revisions:

ede2467cdedc63784887b587a61c36b7850ebfac..d8f581194799ae29bf5fa72a98cbae98a1198b12

As a result, git cannot rebase them.

Fix this by always passing --no-base to format-patch from rebase so that the effect of format.useAutoBase is negated.


With Git 2.29 (Q4 2020), "git format-patch"(man) learns to take "whenAble" as a possible value for the format.useAutoBase configuration variable to become no-op when the automatically computed base does not make sense.

See commit 7efba5f (01 Oct 2020) by Jacob Keller (jacob-keller).
(Merged by Junio C Hamano -- gitster -- in commit 5f8c70a, 05 Oct 2020)

format-patch: teach format.useAutoBase "whenAble" option

Signed-off-by: Jacob Keller

The format.useAutoBase configuration option exists to allow users to enable '--base=auto' for format-patch by default.

This can sometimes lead to poor workflow, due to unexpected failures when attempting to format an ancient patch:

$ git format-patch -1 <an old commit>
fatal: base commit shouldn't be in revision list  

This can be very confusing, as it is not necessarily immediately obvious that the user requested a --base (since this was in the configuration, not on the command line).

We do want --base=auto to fail when it cannot provide a suitable base, as it would be equally confusing if a formatted patch did not include the base information when it was requested.

Teach format.useAutoBase a new mode, "whenAble".

This mode will cause format-patch to attempt to include a base commit when it can. However, if no valid base commit can be found, then format-patch will continue formatting the patch without a base commit.

In order to avoid making yet another branch name unusable with --base, do not teach --base=whenAble or --base=whenable.

Instead, refactor the base_commit option to use a callback, and rely on the global configuration variable auto_base.

This does mean that a user cannot request this optional base commit generation from the command line. However, this is likely not too valuable. If the user requests base information manually, they will be immediately informed of the failure to acquire a suitable base commit. This allows the user to make an informed choice about whether to continue the format.

Add tests to cover the new mode of operation for --base.

git config now includes in its man page:

format-patch by default.
Can also be set to "whenAble" to allow enabling --base=auto if a suitable base is available, but to skip adding base info otherwise without the format dying.


With Git 2.30 (Q1 2021), "git format-patch --output=there"(man) did not work as expected and instead crashed.

The option is now supported.

See commit dc1672d, commit 1e1693b, commit 4c6f781 (04 Nov 2020) by Jeff King (peff).
(Merged by Junio C Hamano -- gitster -- in commit 5edc8bd, 18 Nov 2020)

format-patch: support --output option

Reported-by: Johannes Postler
Signed-off-by: Jeff King

We've never intended to support diff's --output option in format-patch. And until baa4adc66a (parse-options: disable option abbreviation with PARSE_OPT_KEEP_UNKNOWN, 2019-01-27, Git v2.22.0-rc0), it was impossible to trigger. We first parse the format-patch options before handing the remainder off to setup_revisions().
Before that commit, we'd accept "--output=foo" as an abbreviation for "--output-directory=foo". But afterwards, we don't check abbreviations, and --output gets passed to the diff code.

This results in nonsense behavior and bugs. The diff code will have opened a filehandle at rev.diffopt.file, but we'll overwrite that with our own handles that we open for each individual patch file. So the --output file will always just be empty. But worse, the diff code also sets rev.diffopt.close_file, so log_tree_commit() will close the filehandle itself. And then the main loop in cmd_format_patch() will try to close it again, resulting in a double-free.

The simplest solution would be to just disallow --output with format-patch, as nobody ever intended it to work. However, we have accidentally documented it (because format-patch includes diff-options). And it does work with "git log"(man) , which writes the whole output to the specified file. It's easy enough to make that work for format-patch, too: it's really the same as --stdout, but pointed at a specific file.

We can detect the use of the --output option by the "close_file" flag (note that we can't use rev.diffopt.file, since the diff setup will otherwise set it to stdout). So we just need to unset that flag, but don't have to do anything else. Our situation is otherwise exactly like --stdout (note that we don't fclose() the file, but nor does the stdout case; exiting the program takes care of that for us).

Subset data.frame by date

Well, it's clearly not a number since it has dashes in it. The error message and the two comments tell you that it is a factor but the commentators are apparently waiting and letting the message sink in. Dirk is suggesting that you do this:

 EPL2011_12$Date2 <- as.Date( as.character(EPL2011_12$Date), "%d-%m-%y")

After that you can do this:

 EPL2011_12FirstHalf <- subset(EPL2011_12, Date2 > as.Date("2012-01-13") )

R date functions assume the format is either "YYYY-MM-DD" or "YYYY/MM/DD". You do need to compare like classes: date to date, or character to character.

Naming convention - underscore in C++ and C# variables

_var has no meaning and only serves the purpose of making it easier to distinguish that the variable is a private member variable.

In C++, using the _var convention is bad form, because there are rules governing the use of the underscore in front of an identifier. _var is reserved as a global identifier, while _Var (underscore + capital letter) is reserved anytime. This is why in C++, you'll see people using the var_ convention instead.

Create new XML file and write data to it?

DOMDocument is a great choice. It's a module specifically designed for creating and manipulating XML documents. You can create a document from scratch, or open existing documents (or strings) and navigate and modify their structures.

$xml = new DOMDocument();
$xml_album = $xml->createElement("Album");
$xml_track = $xml->createElement("Track");
$xml_album->appendChild( $xml_track );
$xml->appendChild( $xml_album );

$xml->save("/tmp/test.xml");

To re-open and write:

$xml = new DOMDocument();
$xml->load('/tmp/test.xml');
$nodes = $xml->getElementsByTagName('Album') ;
if ($nodes->length > 0) {
   //insert some stuff using appendChild()
}

//re-save
$xml->save("/tmp/test.xml");

What's the difference between IFrame and Frame?

While the security is the same, it may be easier for fraudulent applications to dupe users using an iframe since they have more flexibility regarding where the frame is placed.

Escaping quotation marks in PHP

Save your text not in a PHP file, but in an ordinary text file called, say, "text.txt"

Then with one simple $text1 = file_get_contents('text.txt'); command have your text with not a single problem.

javax.faces.application.ViewExpiredException: View could not be restored

I was getting this error : javax.faces.application.ViewExpiredException.When I using different requests, I found those having same JsessionId, even after restarting the server. So this is due to the browser cache. Just close the browser and try, it will work.

What is the first character in the sort order used by Windows Explorer?

I know there is already an answer - and this is an old question - but I was wondering the same thing and after finding this answer I did a little experimentation on my own and had (IMO) a worthwhile addition to the discussion.

The non-visible characters can still be used in a folder name - a placeholder is inserted - but the sort on ASCII value still seems to hold.

I tested on Windows7, holding down the alt-key and typing in the ASCII code using the numeric keypad. I did not test very many, but was successful creating foldernames that started with ASCII 1, ASCII 2, and ASCII 3. Those correspond with SOH, STX and ETX. Respectively it displayed happy face, filled happy face, and filled heart.

I'm not sure if I can duplicate that here - but I will type them in on the next lines and submit.

?foldername

?foldername

?foldername

Using a BOOL property

There's no benefit to using properties with primitive types. @property is used with heap allocated NSObjects like NSString*, NSNumber*, UIButton*, and etc, because memory managed accessors are created for free. When you create a BOOL, the value is always allocated on the stack and does not require any special accessors to prevent memory leakage. isWorking is simply the popular way of expressing the state of a boolean value.

In another OO language you would make a variable private bool working; and two accessors: SetWorking for the setter and IsWorking for the accessor.

Javascript: convert 24-hour time-of-day string to 12-hour time with AM/PM and no timezone

toLocaleTimeString() makes this very simple. There is no need to do this yourself anymore. You'll be happier and live longer if you don't attack dates with string methods.

_x000D_
_x000D_
const timeString = '18:00:00'_x000D_
// Append any date. Use your birthday._x000D_
const timeString12hr = new Date('1970-01-01T' + timeString + 'Z')_x000D_
  .toLocaleTimeString({},_x000D_
    {timeZone:'UTC',hour12:true,hour:'numeric',minute:'numeric'}_x000D_
  );_x000D_
document.getElementById('myTime').innerText = timeString12hr
_x000D_
<h1 id='myTime'></h1>
_x000D_
_x000D_
_x000D_

How can I format bytes a cell in Excel as KB, MB, GB etc?

For the exact result, I'd rather calculate it, but using display format.

Assuming A1 cell has value 29773945664927.

  1. Count the number of commas in B1 cell.

    =QUOTIENT(LEN(A1)-1,3)

  2. Divide the value by 1024^B1 in C1 cell.

    =A1/1024^B1

  3. Display unit in D1 cell.

    =SWITCH(B1, 5," PB", 4," TB", 3," GB", 2," MB",1," KB",0," B")

  4. Hide B1 cell.

screenshot

Validate phone number with JavaScript

The following REGEX will validate any of these formats:

(123) 456-7890
123-456-7890
123.456.7890
1234567890

/^[(]{0,1}[0-9]{3}[)]{0,1}[-\s\.]{0,1}[0-9]{3}[-\s\.]{0,1}[0-9]{4}$/

Swing vs JavaFx for desktop applications

No one has mentioned it, but JavaFX does not compile or run on certain architectures deemed "servers" by Oracle (e.g. Solaris), because of the missing "jfxrt.jar" support. Stick with SWT, until further notice.

open_basedir restriction in effect. File(/) is not within the allowed path(s):

In addition to @yogihosting's answer, if you are using DirectAdmin, then follow these steps:

  1. Go to the DirectAdmin's login page. Usually, its port is 2222.
  2. Login as administrator. Its username is admin by default.
  3. From the "Access Level" on the right panel, make sure you are on "Admin Level". If not, change to it.
  4. From the "Extra Features" section, click on "Custom HTTPD Configurations".
  5. Choose the domain you want to change.
  6. Enter the configurations you want to change in the textarea at the top of the page. You should consider the existing configuration file and modify values based on it. For example, if you see that open_basedir is set inside a <Directory>, maybe you should surround your change in the related <Directory> tag:

    <Directory "/path/to/directory">
        php_admin_value open_basedir none
    </Directory>
    
  7. After making necessary changes, click on the "Save" button.

  8. You should now see your changes saved to the configuration file if they were valid.

There is another way of editing the configuration file, however:

Caution: Be careful, and use the following steps at your own risk, as you may run into errors, or it may lead to downtime. The recommended way is the previous one, as it prevents you from modifying configuration file improperly and show you the error.

  1. Login to your server as root.
  2. Go to /usr/local/directadmin/data/users. From the listed users, go to one related to the domain you want to change.
  3. Here, there is an httpd.conf file. Make a backup from it:

    cp httpd.conf httpd.conf.back
    
  4. Now edit the configuration file with your editor of choice. For example, edit existing open_basedir to none. Do not try to remove things, or you may experience downtime. Save the file after editing.

  5. Restart the Apache web server using one of the following ways (use sudo if needed):

    httpd -k graceful
    apachectl -k graceful
    apache2 -k graceful
    
  6. If your encounter any errors, then replace the main configuration file with the backed-up file, and restart the web server.

Again, the first solution is the preferred one, and you should not try the second method at the first time. As it is noted in the caution, the advantage of the first way is that it prevents saving your bad-configured stuff.

Hope it helps!

GDB: Listing all mapped memory regions for a crashed process

(gdb) maintenance info sections 
Exec file:
    `/path/to/app.out', file type elf32-littlearm.
    0x0000->0x0360 at 0x00008000: .intvecs ALLOC LOAD READONLY DATA HAS_CONTENTS

This is from comment by phihag above, deserves a separate answer. This works but info proc does not on the arm-none-eabi-gdb v7.4.1.20130913-cvs from the gcc-arm-none-eabi Ubuntu package.

What is the difference between IQueryable<T> and IEnumerable<T>?

The primary difference is that the LINQ operators for IQueryable<T> take Expression objects instead of delegates, meaning the custom query logic it receives, e.g., a predicate or value selector, is in the form of an expression tree instead of a delegate to a method.

  • IEnumerable<T> is great for working with sequences that are iterated in-memory, but
  • IQueryable<T> allows for out-of memory things like a remote data source, such as a database or web service.

Query execution:

  • Where the execution of a query is going to be performed "in process", typically all that's required is the code (as code) to execute each part of the query.

  • Where the execution will be performed out-of-process, the logic of the query has to be represented in data such that the LINQ provider can convert it into the appropriate form for the out-of-memory execution - whether that's an LDAP query, SQL or whatever.

More in:

http://www.codeproject.com/KB/cs/646361/WhatHowWhere.jpg

Get full query string in C# ASP.NET

just a moment ago, i came across with the same issue. and i resolve it in the following manner.

Response.Redirect("../index.aspx?Name="+this.textName.Text+"&LastName="+this.textlName.Text);

with reference to the this

jQuery getTime function

It's plain javascript:

new Date()

Set multiple system properties Java command line

You may be able to use the JAVA_TOOL_OPTIONS environment variable to set options. It worked for me with Rasbian. See Environment Variables and System Properties which has this to say:

In many environments, the command line is not readily accessible to start the application with the necessary command-line options.

This often happens with applications that use embedded VMs (meaning they use the Java Native Interface (JNI) Invocation API to start the VM), or where the startup is deeply nested in scripts. In these environments the JAVA_TOOL_OPTIONS environment variable can be useful to augment a command line.

When this environment variable is set, the JNI_CreateJavaVM function (in the JNI Invocation API), the JNI_CreateJavaVM function adds the value of the environment variable to the options supplied in its JavaVMInitArgs argument.

However this environment variable use may be disabled for security reasons.

In some cases, this option is disabled for security reasons. For example, on the Oracle Solaris operating system, this option is disabled when the effective user or group ID differs from the real ID.

See this example showing the difference between specifying on the command line versus using the JAVA_TOOL_OPTIONS environment variable.

screenshot showing use of JAVA_TOOL_OPTIONS environment variable

Laravel Escaping All HTML in Blade Template

Change your syntax from {{ }} to {!! !!}.

As The Alpha said in a comment above (not an answer so I thought I'd post), in Laravel 5, the {{ }} (previously non-escaped output syntax) has changed to {!! !!}. Replace {{ }} with {!! !!} and it should work.

How to increase the max connections in postgres?

Adding to Winnie's great answer,

If anyone is not able to find the postgresql.conf file location in your setup, you can always ask the postgres itself.

SHOW config_file;

For me changing the max_connections alone made the trick.

How to make a round button?

use ImageButton instead of Button....

and make Round image with transparent background

C++ String Concatenation operator<<

nametext is an std::string but these do not have the stream insertion operator (<<) like output streams do.

To concatenate strings you can use the append member function (or its equivalent, +=, which works in the exact same way) or the + operator, which creates a new string as a result of concatenating the previous two.

How to encode a string in JavaScript for displaying in HTML?

The only character that needs escaping is <. (> is meaningless outside of a tag).

Therefore, your "magic" code is:

safestring = unsafestring.replace(/</g,'&lt;');

How to do a deep comparison between 2 objects with lodash?

Here's a concise solution:

_.differenceWith(a, b, _.isEqual);

generate random double numbers in c++

This should be performant, thread-safe and flexible enough for many uses:

#include <random>
#include <iostream>

template<typename Numeric, typename Generator = std::mt19937>
Numeric random(Numeric from, Numeric to)
{
    thread_local static Generator gen(std::random_device{}());

    using dist_type = typename std::conditional
    <
        std::is_integral<Numeric>::value
        , std::uniform_int_distribution<Numeric>
        , std::uniform_real_distribution<Numeric>
    >::type;

    thread_local static dist_type dist;

    return dist(gen, typename dist_type::param_type{from, to});
}

int main(int, char*[])
{
    for(auto i = 0U; i < 20; ++i)
        std::cout << random<double>(0.0, 0.3) << '\n';
}

How to initialize private static members in C++?

Also working in privateStatic.cpp file :

#include <iostream>

using namespace std;

class A
{
private:
  static int v;
};

int A::v = 10; // possible initializing

int main()
{
A a;
//cout << A::v << endl; // no access because of private scope
return 0;
}

// g++ privateStatic.cpp -o privateStatic && ./privateStatic

What is the difference between linear regression and logistic regression?

The basic difference between Linear Regression and Logistic Regression is : Linear Regression is used to predict a continuous or numerical value but when we are looking for predicting a value that is categorical Logistic Regression come into picture.

Logistic Regression is used for binary classification.

Overriding a JavaScript function while referencing the original

You could do something like this:

var a = (function() {
    var original_a = a;

    if (condition) {
        return function() {
            new_code();
            original_a();
        }
    } else {
        return function() {
            original_a();
            other_new_code();
        }
    }
})();

Declaring original_a inside an anonymous function keeps it from cluttering the global namespace, but it's available in the inner functions.

Like Nerdmaster mentioned in the comments, be sure to include the () at the end. You want to call the outer function and store the result (one of the two inner functions) in a, not store the outer function itself in a.

Swift programmatically navigate to another view controller/scene

OperationQueue.main.addOperation {
   let storyBoard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
   let newViewController = storyBoard.instantiateViewController(withIdentifier: "Storyboard ID") as! NewViewController
   self.present(newViewController, animated: true, completion: nil)
}

It worked for me when I put the code inside of the OperationQueue.main.addOperation, that will execute in the main thread for me.

Find column whose name contains a specific string

Getting name and subsetting based on Start, Contains, and Ends:

# from: https://stackoverflow.com/questions/21285380/find-column-whose-name-contains-a-specific-string
# from: https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.str.contains.html
# from: https://cmdlinetips.com/2019/04/how-to-select-columns-using-prefix-suffix-of-column-names-in-pandas/
# from: https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.filter.html




import pandas as pd



data = {'spike_starts': [1,2,3], 'ends_spike_starts': [4,5,6], 'ends_spike': [7,8,9], 'not': [10,11,12]}
df = pd.DataFrame(data)



print("\n")
print("----------------------------------------")
colNames_contains = df.columns[df.columns.str.contains(pat = 'spike')].tolist() 
print("Contains")
print(colNames_contains)



print("\n")
print("----------------------------------------")
colNames_starts = df.columns[df.columns.str.contains(pat = '^spike')].tolist() 
print("Starts")
print(colNames_starts)



print("\n")
print("----------------------------------------")
colNames_ends = df.columns[df.columns.str.contains(pat = 'spike$')].tolist() 
print("Ends")
print(colNames_ends)



print("\n")
print("----------------------------------------")
df_subset_start = df.filter(regex='^spike',axis=1)
print("Starts")
print(df_subset_start)



print("\n")
print("----------------------------------------")
df_subset_contains = df.filter(regex='spike',axis=1)
print("Contains")
print(df_subset_contains)



print("\n")
print("----------------------------------------")
df_subset_ends = df.filter(regex='spike$',axis=1)
print("Ends")
print(df_subset_ends)

How can I show a hidden div when a select option is selected?

You should hook onto the change event of the <select> element instead of on the individual options.

var select = document.getElementById('test'),
onChange = function(event) {
    var shown = this.options[this.selectedIndex].value == 1;

    document.getElementById('hidden_div').style.display = shown ? 'block' : 'none';
};

// attach event handler
if (window.addEventListener) {
    select.addEventListener('change', onChange, false);
} else {
    // of course, IE < 9 needs special treatment
    select.attachEvent('onchange', function() {
        onChange.apply(select, arguments);
    });
}

Demo

How to get the first five character of a String

If we want only first 5 characters from any field, then this can be achieved by Left Attribute

Vessel = f.Vessel !=null ? f.Vessel.Left(5) : ""

How can I get a list of all functions stored in the database of a particular schema in PostgreSQL?

\df <schema>.*

in psql gives the necessary information.

To see the query that's used internally connect to a database with psql and supply an extra "-E" (or "--echo-hidden") option and then execute the above command.

Launch Image does not show up in my iOS App

There is a bug where Xcode 6 launch images stored in asset files cause iphone landscape only apps on iOS7/iOS8 to display a black launch image. iPad works fine.

http://www.raywenderlich.com/forums/viewtopic.php?f=2&t=10868

Solution: Use the new Launchscreen.xib for ios8+ onwards. (it is far better)

For ios7 devices to work you simply turn off launch images source and use the old school launch images file names in the plist

iphone5 - [email protected] 
iphone4s - [email protected]
ipad2 - Default-Landscape~ipad.png
ipad retina - Default-Landscape@2x~ipad.png

Painful but works. B
enter image description here

What happens when a duplicate key is put into a HashMap?

By definition, the put command replaces the previous value associated with the given key in the map (conceptually like an array indexing operation for primitive types).

The map simply drops its reference to the value. If nothing else holds a reference to the object, that object becomes eligible for garbage collection. Additionally, Java returns any previous value associated with the given key (or null if none present), so you can determine what was there and maintain a reference if necessary.

More information here: HashMap Doc

GDB: break if variable equal value

You can use a watchpoint for this (A breakpoint on data instead of code).

You can start by using watch i.
Then set a condition for it using condition <breakpoint num> i == 5

You can get the breakpoint number by using info watch

How to get a MemoryStream from a Stream in .NET?

If you're modifying your class to accept a Stream instead of a filename, don't bother converting to a MemoryStream. Let the underlying Stream handle the operations:

public class MyClass
{ 
    Stream _s;

    public MyClass(Stream s) { _s = s; }
}

But if you really need a MemoryStream for internal operations, you'll have to copy the data out of the source Stream into the MemoryStream:

public MyClass(Stream stream)
{
    _ms = new MemoryStream();
    CopyStream(stream, _ms);
}

// Merged From linked CopyStream below and Jon Skeet's ReadFully example
public static void CopyStream(Stream input, Stream output)
{
    byte[] buffer = new byte[16*1024];
    int read;
    while((read = input.Read (buffer, 0, buffer.Length)) > 0)
    {
        output.Write (buffer, 0, read);
    }
}

Determine if an element has a CSS class with jQuery

In the interests of helping anyone who lands here but was actually looking for a jQuery free way of doing this:

element.classList.contains('your-class-name')

ssh "permissions are too open" error

I am using VPC on EC2 and was getting the same error messages. I noticed I was using the public DNS. I changed that to the private DNS and vola!! it worked...

Can clearInterval() be called inside setInterval()?

Yes you can. You can even test it:

_x000D_
_x000D_
var i = 0;_x000D_
var timer = setInterval(function() {_x000D_
  console.log(++i);_x000D_
  if (i === 5) clearInterval(timer);_x000D_
  console.log('post-interval'); //this will still run after clearing_x000D_
}, 200);
_x000D_
_x000D_
_x000D_

In this example, this timer clears when i reaches 5.

Skip download if files exist in wget?

When running Wget with -r or -p, but without -N, -nd, or -nc, re-downloading a file will result in the new copy simply overwriting the old.

So adding -nc will prevent this behavior, instead causing the original version to be preserved and any newer copies on the server to be ignored.

See more info at GNU.

Delegation: EventEmitter or Observable in Angular

I found out another solution for this case without using Reactivex neither services. I actually love the rxjx API however I think it goes best when resolving an async and/or complex function. Using It in that way, Its pretty exceeded to me.

What I think you are looking for is for a broadcast. Just that. And I found out this solution:

<app>
  <app-nav (selectedTab)="onSelectedTab($event)"></app-nav>
       // This component bellow wants to know when a tab is selected
       // broadcast here is a property of app component
  <app-interested [broadcast]="broadcast"></app-interested>
</app>

 @Component class App {
   broadcast: EventEmitter<tab>;

   constructor() {
     this.broadcast = new EventEmitter<tab>();
   }

   onSelectedTab(tab) {
     this.broadcast.emit(tab)
   }    
 }

 @Component class AppInterestedComponent implements OnInit {
   broadcast: EventEmitter<Tab>();

   doSomethingWhenTab(tab){ 
      ...
    }     

   ngOnInit() {
     this.broadcast.subscribe((tab) => this.doSomethingWhenTab(tab))
   }
 }

This is a full working example: https://plnkr.co/edit/xGVuFBOpk2GP0pRBImsE

java build path problems

Go for the second option, Edit the project to agree with the latest JDK

  • Right click "JRE System Library [J2SE 1.5] in your project"
  • Choose "Properties"
  • Select "Workspace default JRE (jdk1.6)

enter image description here

JSON ValueError: Expecting property name: line 1 column 2 (char 1)

used ast, example

In [15]: a = "[{'start_city': '1', 'end_city': 'aaa', 'number': 1},\
...:      {'start_city': '2', 'end_city': 'bbb', 'number': 1},\
...:      {'start_city': '3', 'end_city': 'ccc', 'number': 1}]"
In [16]: import ast
In [17]: ast.literal_eval(a)
Out[17]:
[{'end_city': 'aaa', 'number': 1, 'start_city': '1'},
 {'end_city': 'bbb', 'number': 1, 'start_city': '2'},
 {'end_city': 'ccc', 'number': 1, 'start_city': '3'}]

How to get the data-id attribute?

HTML

<span id="spanTest" data-value="50">test</span>

JS

$(this).data().value;

or

$("span#spanTest").data().value;

ANS : 50

Works for me!

HTML img align="middle" doesn't align an image

You don't need align="center" and float:left. Remove both of these. margin: 0 auto is sufficient.

How do I import/include MATLAB functions?

Solution for Windows

Go to File --> Set Path and add the folder containing the functions as Matlab files. (At least for Matlab 2007b on Vista)

NGINX - No input file specified. - php Fast/CGI

use in windows

fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;

wasn't putting -b

php-cgi.exe -b 127.0.0.1:9000

How to test enum types?

Usually I would say it is overkill, but there are occasionally reasons for writing unit tests for enums.

Sometimes the values assigned to enumeration members must never change or the loading of legacy persisted data will fail. Similarly, apparently unused members must not be deleted. Unit tests can be used to guard against a developer making changes without realising the implications.

How do I request and receive user input in a .bat and use it to run a certain program?

Here is a working example:

@echo off
:ask
@echo echo Would you like to use developer mode?(Y/N)
set INPUT=
set /P INPUT=Type input: %=%
If /I "%INPUT%"=="y" goto yes 
If /I "%INPUT%"=="n" goto no
goto ask
:yes
@echo you select yes
goto exit
:no
@echo you select no
goto exit
:exit
@pause

How do I do a bulk insert in mySQL using node.js

Bulk insert in Node.js can be done using the below code. I have referred lots of blog for getting this work.

please refer this link as well. https://www.technicalkeeda.com/nodejs-tutorials/insert-multiple-records-into-mysql-using-nodejs

The working code.

  const educations = request.body.educations;
  let queryParams = [];
  for (let i = 0; i < educations.length; i++) {
    const education = educations[i];
    const userId = education.user_id;
    const from = education.from;
    const to = education.to;
    const instituteName = education.institute_name;
    const city = education.city;
    const country = education.country;
    const certificateType = education.certificate_type;
    const studyField = education.study_field;
    const duration = education.duration;

    let param = [
      from,
      to,
      instituteName,
      city,
      country,
      certificateType,
      studyField,
      duration,
      userId,
    ];

    queryParams.push(param);
  }

  let sql =
    "insert into tbl_name (education_from, education_to, education_institute_name, education_city, education_country, education_certificate_type, education_study_field, education_duration, user_id) VALUES ?";
  let sqlQuery = dbManager.query(sql, [queryParams], function (
    err,
    results,
    fields
  ) {
    let res;
    if (err) {
      console.log(err);
      res = {
        success: false,
        message: "Insertion failed!",
      };
    } else {
      res = {
        success: true,
        id: results.insertId,
        message: "Successfully inserted",
      };
    }

    response.send(res);
  });

Hope this will help you.

starting file download with JavaScript

Reading the answers - including the accepted one I'd like to point out the security implications of passing a path directly to readfile via GET.

It may seem obvious to some but some may simply copy/paste this code:

<?php 
   header("Content-Type: application/octet-stream");
   header("Content-Disposition: attachment; filename=".$_GET['path']);
   readfile($_GET['path']);
?>

So what happens if I pass something like '/path/to/fileWithSecrets' to this script? The given script will happily send any file the webserver-user has access to.

Please refer to this discussion for information how to prevent this: How do I make sure a file path is within a given subdirectory?

What is the difference between "JPG" / "JPEG" / "PNG" / "BMP" / "GIF" / "TIFF" Image?

Yes. They are different file formats (and their file extensions).

Wikipedia entries for each of the formats will give you quite a bit of information:

  • JPEG (or JPG, for the file extension; Joint Photographic Experts Group)
  • PNG (Portable Network Graphics)
  • BMP (Bitmap)
  • GIF (Graphics Interchange Format)
  • TIFF (or TIF, for the file extension; Tagged Image File Format)

Image formats can be separated into three broad categories:

  • lossy compression,
  • lossless compression,
  • uncompressed,

Uncompressed formats take up the most amount of data, but they are exact representations of the image. Bitmap formats such as BMP generally are uncompressed, although there also are compressed BMP files as well.

Lossy compression formats are generally suited for photographs. It is not suited for illustrations, drawings and text, as compression artifacts from compressing the image will standout. Lossy compression, as its name implies, does not encode all the information of the file, so when it is recovered into an image, it will not be an exact representation of the original. However, it is able to compress images very effectively compared to lossless formats, as it discards certain information. A prime example of a lossy compression format is JPEG.

Lossless compression formats are suited for illustrations, drawings, text and other material that would not look good when compressed with lossy compression. As the name implies, lossless compression will encode all the information from the original, so when the image is decompressed, it will be an exact representation of the original. As there is no loss of information in lossless compression, it is not able to achieve as high a compression as lossy compression, in most cases. Examples of lossless image compression is PNG and GIF. (GIF only allows 8-bit images.)

TIFF and BMP are both "wrapper" formats, as the data inside can depend upon the compression technique that is used. It can contain both compressed and uncompressed images.

When to use a certain image compression format really depends on what is being compressed.

Related question: Ruthlessly compressing large images for the web

How to make rectangular image appear circular with CSS

Building on the answer from @fzzle - to achieve a circle from a rectangle without defining a fixed height or width, the following will work. The padding-top:100% keeps a 1:1 ratio for the circle-cropper div. Set an inline background image, center it, and use background-size:cover to hide any excess.

CSS

.circle-cropper {
  background-repeat: no-repeat;
  background-size: cover;
  background-position: 50%;
  border-radius: 50%;
  width: 100%;
  padding-top: 100%;
}

HTML

<div class="circle-cropper" role="img" style="background-image:url(myrectangle.jpg);"></div>

C++ int to byte array

An int (or any other data type for that matter) is already stored as bytes in memory. So why not just copy the memory directly?

memcpy(arrayOfByte, &x, sizeof x);

A simple elegant one liner that will also work with any other data type.



If you need the bytes reversed you can use std::reverse

memcpy(arrayOfByte, &x, sizeof x);
std::reverse(arrayOfByte, arrayOfByte + sizeof x);

or better yet, just copy the bytes in reverse to begin with

BYTE* p = (BYTE*) &x;
std::reverse_copy(p, p + sizeof x, arrayOfByte);

If you don't want to make a copy of the data at all, and just have its byte representation

BYTE* bytes = (BYTE*) &x;

Test only if variable is not null in if statement

I don't believe the expression is sensical as it is.

Elvis means "if truthy, use the value, else use this other thing."

Your "other thing" is a closure, and the value is status != null, neither of which would seem to be what you want. If status is null, Elvis says true. If it's not, you get an extra layer of closure.

Why can't you just use:

(it.description == desc) && ((status == null) || (it.status == status))

Even if that didn't work, all you need is the closure to return the appropriate value, right? There's no need to create two separate find calls, just use an intermediate variable.

Insert json file into mongodb

In MongoDB To insert Json array data from file(from particular location from a system / pc) using mongo shell command. While executing below command, command should be in single line.

var file = cat('I:/data/db/card_type_authorization.json'); var o = JSON.parse(file); db.CARD_TYPE_AUTHORIZATION.insert(o);

JSON File: card_type_authorization.json

[{
"code": "visa",
"position": 1,
"description": "Visa",
"isVertualCard": false,
"comments": ""
},{
    "code": "mastercard",
    "position": 2,
    "description": "Mastercard",
    "isVertualCard": false,
    "comments": ""
}]

matplotlib colorbar for scatter

Here is the OOP way of adding a colorbar:

fig, ax = plt.subplots()
im = ax.scatter(x, y, c=c)
fig.colorbar(im, ax=ax)

Convert normal date to unix timestamp

new Date('2012.08.10').getTime() / 1000

Check the JavaScript Date documentation.

How to format dateTime in django template?

{{ wpis.entry.lastChangeDate|date:"SHORT_DATETIME_FORMAT" }}

"unadd" a file to svn before commit

For Files - svn revert filename

For Folders - svn revert -R folder

install / uninstall APKs programmatically (PackageManager vs Intents)

According to Froyo source code, the Intent.EXTRA_INSTALLER_PACKAGE_NAME extra key is queried for the installer package name in the PackageInstallerActivity.

Git Push Error: insufficient permission for adding an object to repository database

After using git for a long time without problems, I encountered this problem today. After some reflection, I realized I changed my umask earlier today from 022 to something else.

All the answers by other people are helpful, i.e., do chmod for the offending directories. But the root cause is my new umask which will always cause a new problem down the road whenever a new directory is created under .git/object/. So, the long term solution for me is to change umask back to 022.

How can I align two divs horizontally?

Add a class to each of the divs:

_x000D_
_x000D_
.source, .destination {_x000D_
    float: left;_x000D_
    width: 48%;_x000D_
    margin: 0;_x000D_
    padding: 0;_x000D_
}_x000D_
.source {_x000D_
    margin-right: 4%;_x000D_
}
_x000D_
<div class="source">_x000D_
    <span>source list</span>_x000D_
    <select size="10">_x000D_
        <option />_x000D_
        <option />_x000D_
        <option />_x000D_
    </select>_x000D_
</div>_x000D_
<div class="destination">_x000D_
    <span>destination list</span>_x000D_
    <select size="10">_x000D_
        <option />_x000D_
        <option />_x000D_
        <option />_x000D_
    </select>_x000D_
</div>
_x000D_
_x000D_
_x000D_

That's a generic percentages solution - using pixel-based widths is usually much more reliable. You'll probably want to change the various margin/padding sizes too.

You can also optionally wrap the HTML in a container div, and use this CSS:

.container {
  overflow: hidden;
}

This will ensure subsequent content does not wrap around the floated elements.

Rounding a double to turn it into an int (java)

If you don't like Math.round() you can use this simple approach as well:

int a = (int) (doubleVar + 0.5);

Get content of a DIV using JavaScript

(1) Your <script> tag should be placed before the closing </body> tag. Your JavaScript is trying to manipulate HTML elements that haven't been loaded into the DOM yet.
(2) Your assignment of HTML content looks jumbled.
(3) Be consistent with the case in your element ID, i.e. 'DIV2' vs 'Div2'
(4) User lower case for 'document' object (credit: ThatOtherPerson)

<body>
<div id="DIV1">
 // Some content goes here.
</div>

<div id="DIV2">
</div>
<script type="text/javascript">

   var MyDiv1 = document.getElementById('DIV1');
   var MyDiv2 = document.getElementById('DIV2');
   MyDiv2.innerHTML = MyDiv1.innerHTML;

</script>
</body>

Filter Java Stream to 1 and only 1 element

I think this way is more simple:

User resultUser = users.stream()
    .filter(user -> user.getId() > 0)
    .findFirst().get();

How to test if a DataSet is empty?

You should loop through all tables and test if table.Rows.Count is 0

bool IsEmpty(DataSet dataSet)
{
    foreach(DataTable table in dataSet.Tables)
        if (table.Rows.Count != 0) return false;

    return true;
}

Update: Since a DataTable could contain deleted rows RowState = Deleted, depending on what you want to achive, it could be a good idea to check the DefaultView instead (which does not contain deleted rows).

bool IsEmpty(DataSet dataSet)
{
    return !dataSet.Tables.Cast<DataTable>().Any(x => x.DefaultView.Count > 0);
}

How does C compute sin() and other math functions?

I'll try to answer for the case of sin() in a C program, compiled with GCC's C compiler on a current x86 processor (let's say a Intel Core 2 Duo).

In the C language the Standard C Library includes common math functions, not included in the language itself (e.g. pow, sin and cos for power, sine, and cosine respectively). The headers of which are included in math.h.

Now on a GNU/Linux system, these libraries functions are provided by glibc (GNU libc or GNU C Library). But the GCC compiler wants you to link to the math library (libm.so) using the -lm compiler flag to enable usage of these math functions. I'm not sure why it isn't part of the standard C library. These would be a software version of the floating point functions, or "soft-float".

Aside: The reason for having the math functions separate is historic, and was merely intended to reduce the size of executable programs in very old Unix systems, possibly before shared libraries were available, as far as I know.

Now the compiler may optimize the standard C library function sin() (provided by libm.so) to be replaced with an call to a native instruction to your CPU/FPU's built-in sin() function, which exists as an FPU instruction (FSIN for x86/x87) on newer processors like the Core 2 series (this is correct pretty much as far back as the i486DX). This would depend on optimization flags passed to the gcc compiler. If the compiler was told to write code that would execute on any i386 or newer processor, it would not make such an optimization. The -mcpu=486 flag would inform the compiler that it was safe to make such an optimization.

Now if the program executed the software version of the sin() function, it would do so based on a CORDIC (COordinate Rotation DIgital Computer) or BKM algorithm, or more likely a table or power-series calculation which is commonly used now to calculate such transcendental functions. [Src: http://en.wikipedia.org/wiki/Cordic#Application]

Any recent (since 2.9x approx.) version of gcc also offers a built-in version of sin, __builtin_sin() that it will used to replace the standard call to the C library version, as an optimization.

I'm sure that is as clear as mud, but hopefully gives you more information than you were expecting, and lots of jumping off points to learn more yourself.

Forms authentication timeout vs sessionState timeout

The difference is that one (forms time-out) has to do authenticating the user and the other( session timeout) has to do with how long cached data is stored on the server. So they are very independent things so one doesn't take precedence over the other.

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

  1. Set the path to restore the file.
  2. Click "Options" on the left hand side.
  3. Uncheck "Take tail-log backup before restoring"
  4. Tick the check box - "Close existing connections to destination database". enter image description here
  5. Click OK.

Display unescaped HTML in Vue.js

You can use the directive v-html to show it. like this:

<td v-html="desc"></td>

Getting min and max Dates from a pandas dataframe

'Date' is your index so you want to do,

print (df.index.min())
print (df.index.max())

2014-03-13 00:00:00
2014-03-31 00:00:00

How to Execute SQL Script File in Java?

If you use Spring you can use DataSourceInitializer:

@Bean
public DataSourceInitializer dataSourceInitializer(@Qualifier("dataSource") final DataSource dataSource) {
    ResourceDatabasePopulator resourceDatabasePopulator = new ResourceDatabasePopulator();
    resourceDatabasePopulator.addScript(new ClassPathResource("/data.sql"));
    DataSourceInitializer dataSourceInitializer = new DataSourceInitializer();
    dataSourceInitializer.setDataSource(dataSource);
    dataSourceInitializer.setDatabasePopulator(resourceDatabasePopulator);
    return dataSourceInitializer;
}

Used to set up a database during initialization and clean up a database during destruction.

https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/jdbc/datasource/init/DataSourceInitializer.html

PHP multidimensional array search by value

Just share, maybe can like this.

if( ! function_exists('arraySearchMulti')){
function arraySearchMulti($search,$key,$array,$returnKey=false)
{
    foreach ($array as $k => $val) {
        if (isset($val[$key])) {
            if ((string)$val[$key] == (string)$search) {
                return ($returnKey ? $k : $val);
            }
        }else{
            return (is_array($val) ? arraySearchMulti($search,$key,$val,$returnKey) : null);
        }
    }
    return null;
}}

What are the differences between ArrayList and Vector?

Differences

  • Vectors are synchronized, ArrayLists are not.
  • Data Growth Methods

Use ArrayLists if there is no specific requirement to use Vectors.

Synchronization

If multiple threads access an ArrayList concurrently then we must externally synchronize the block of code which modifies the list either structurally or simply modifies an element. Structural modification means addition or deletion of element(s) from the list. Setting the value of an existing element is not a structural modification.

Collections.synchronizedList is normally used at the time of creation of the list to avoid any accidental unsynchronized access to the list.

Reference

Data growth

Internally, both the ArrayList and Vector hold onto their contents using an Array. When an element is inserted into an ArrayList or a Vector, the object will need to expand its internal array if it runs out of room. A Vector defaults to doubling the size of its array, while the ArrayList increases its array size by 50 percent.

Reference

How to open CSV file in R when R says "no such file or directory"?

I had to combine Maiasaura and Svun answers to get it to work: using setwd and escaping all the slashes and spaces.

setwd('C:\\Users\\firstname\ lastname\\Desktop\\folder1\\folder2\\folder3')
data = read.csv("file.csv")
data

This solved the issue for me.

String to LocalDate

Datetime formatting is performed by the org.joda.time.format.DateTimeFormatter class. Three classes provide factory methods to create formatters, and this is one. The others are ISODateTimeFormat and DateTimeFormatterBuilder.

DateTimeFormatter format = DateTimeFormat.forPattern("yyyy-MMM-dd");
LocalDate lDate = new LocalDate().parse("2005-nov-12",format);

final org.joda.time.LocalDate class is an immutable datetime class representing a date without a time zone. LocalDate is thread-safe and immutable, provided that the Chronology is as well. All standard Chronology classes supplied are thread-safe and immutable.

Key hash for Android-Facebook app

The simplest solution:

  1. Don't add the hash key, implement everything else
  2. When facebook login is pressed, you will get an error saying "Invalid key hash. The key hash "xxx" does not match any stored key. ..."
  3. Open the facebook app dashboard and add the hash "xxx=" ("xxx" hash from the error + "=" sign)

VBA array sort function?

Take a look here:
Edit: The referenced source (allexperts.com) has since closed, but here are the relevant author comments:

There are many algorithms available on the web for sorting. The most versatile and usually the quickest is the Quicksort algorithm. Below is a function for it.

Call it simply by passing an array of values (string or numeric; it doesn't matter) with the Lower Array Boundary (usually 0) and the Upper Array Boundary (i.e. UBound(myArray).)

Example: Call QuickSort(myArray, 0, UBound(myArray))

When it's done, myArray will be sorted and you can do what you want with it.
(Source: archive.org)

Public Sub QuickSort(vArray As Variant, inLow As Long, inHi As Long)
  Dim pivot   As Variant
  Dim tmpSwap As Variant
  Dim tmpLow  As Long
  Dim tmpHi   As Long

  tmpLow = inLow
  tmpHi = inHi

  pivot = vArray((inLow + inHi) \ 2)

  While (tmpLow <= tmpHi)
     While (vArray(tmpLow) < pivot And tmpLow < inHi)
        tmpLow = tmpLow + 1
     Wend

     While (pivot < vArray(tmpHi) And tmpHi > inLow)
        tmpHi = tmpHi - 1
     Wend

     If (tmpLow <= tmpHi) Then
        tmpSwap = vArray(tmpLow)
        vArray(tmpLow) = vArray(tmpHi)
        vArray(tmpHi) = tmpSwap
        tmpLow = tmpLow + 1
        tmpHi = tmpHi - 1
     End If
  Wend

  If (inLow < tmpHi) Then QuickSort vArray, inLow, tmpHi
  If (tmpLow < inHi) Then QuickSort vArray, tmpLow, inHi
End Sub

Note that this only works with single-dimensional (aka "normal"?) arrays. (There's a working multi-dimensional array QuickSort here.)

PHP function to get the subdomain of a URL

If you only want what comes before the first period:

list($sub) = explode('.', 'en.example.com', 2);

Basic HTTP authentication with Node and Express 4

We can implement the basic authorization without needing any module

//1.
var http = require('http');

//2.
var credentials = {
    userName: "vikas kohli",
    password: "vikas123"
};
var realm = 'Basic Authentication';

//3.
function authenticationStatus(resp) {
    resp.writeHead(401, { 'WWW-Authenticate': 'Basic realm="' + realm + '"' });
    resp.end('Authorization is needed');

};

//4.
var server = http.createServer(function (request, response) {
    var authentication, loginInfo;

    //5.
    if (!request.headers.authorization) {
        authenticationStatus (response);
        return;
    }

    //6.
    authentication = request.headers.authorization.replace(/^Basic/, '');

    //7.
    authentication = (new Buffer(authentication, 'base64')).toString('utf8');

    //8.
    loginInfo = authentication.split(':');

    //9.
    if (loginInfo[0] === credentials.userName && loginInfo[1] === credentials.password) {
        response.end('Great You are Authenticated...');
         // now you call url by commenting the above line and pass the next() function
    }else{

    authenticationStatus (response);

}

});
 server.listen(5050);

Source:- http://www.dotnetcurry.com/nodejs/1231/basic-authentication-using-nodejs

Update an outdated branch against master in a Git repo

Update the master branch, which you need to do regardless.

Then, one of:

  1. Rebase the old branch against the master branch. Solve the merge conflicts during rebase, and the result will be an up-to-date branch that merges cleanly against master.

  2. Merge your branch into master, and resolve the merge conflicts.

  3. Merge master into your branch, and resolve the merge conflicts. Then, merging from your branch into master should be clean.

None of these is better than the other, they just have different trade-off patterns.

I would use the rebase approach, which gives cleaner overall results to later readers, in my opinion, but that is nothing aside from personal taste.

To rebase and keep the branch you would:

git checkout <branch> && git rebase <target>

In your case, check out the old branch, then

git rebase master 

to get it rebuilt against master.

trying to align html button at the center of the my page

Place it inside another div, use CSS to move the button to the middle:

<div style="width:100%;height:100%;position:absolute;vertical-align:middle;text-align:center;">
    <button type="button" style="background-color:yellow;margin-left:auto;margin-right:auto;display:block;margin-top:22%;margin-bottom:0%">
mybuttonname</button> 
</div>?

Here is an example: JsFiddle

Android Layout Weight

i would suppose to set the EditTexts width to wrap_content and put the two buttons into a LinearLayout whose width is fill_parent and weight set to 1.

In Python, how to check if a string only contains certain characters?

Here's a simple, pure-Python implementation. It should be used when performance is not critical (included for future Googlers).

import string
allowed = set(string.ascii_lowercase + string.digits + '.')

def check(test_str):
    set(test_str) <= allowed

Regarding performance, iteration will probably be the fastest method. Regexes have to iterate through a state machine, and the set equality solution has to build a temporary set. However, the difference is unlikely to matter much. If performance of this function is very important, write it as a C extension module with a switch statement (which will be compiled to a jump table).

Here's a C implementation, which uses if statements due to space constraints. If you absolutely need the tiny bit of extra speed, write out the switch-case. In my tests, it performs very well (2 seconds vs 9 seconds in benchmarks against the regex).

#define PY_SSIZE_T_CLEAN
#include <Python.h>

static PyObject *check(PyObject *self, PyObject *args)
{
        const char *s;
        Py_ssize_t count, ii;
        char c;
        if (0 == PyArg_ParseTuple (args, "s#", &s, &count)) {
                return NULL;
        }
        for (ii = 0; ii < count; ii++) {
                c = s[ii];
                if ((c < '0' && c != '.') || c > 'z') {
                        Py_RETURN_FALSE;
                }
                if (c > '9' && c < 'a') {
                        Py_RETURN_FALSE;
                }
        }

        Py_RETURN_TRUE;
}

PyDoc_STRVAR (DOC, "Fast stringcheck");
static PyMethodDef PROCEDURES[] = {
        {"check", (PyCFunction) (check), METH_VARARGS, NULL},
        {NULL, NULL}
};
PyMODINIT_FUNC
initstringcheck (void) {
        Py_InitModule3 ("stringcheck", PROCEDURES, DOC);
}

Include it in your setup.py:

from distutils.core import setup, Extension
ext_modules = [
    Extension ('stringcheck', ['stringcheck.c']),
],

Use as:

>>> from stringcheck import check
>>> check("abc")
True
>>> check("ABC")
False

Python - Passing a function into another function

A function name can become a variable name (and thus be passed as an argument) by dropping the parentheses. A variable name can become a function name by adding the parentheses.

In your example, equate the variable rules to one of your functions, leaving off the parentheses and the mention of the argument. Then in your game() function, invoke rules( v ) with the parentheses and the v parameter.

if puzzle == type1:
    rules = Rule1
else:
    rules = Rule2

def Game(listA, listB, rules):
    if rules( v ) == True:
        do...
    else:
        do...

Best practice for storing and protecting private API keys in applications

Ages old post, but still good enough. I think hiding it in an .so library would be great, using NDK and C++ of course. .so files can be viewed in a hex editor, but good luck decompiling that :P

How to import a module given its name as string?

Note: imp is deprecated since Python 3.4 in favor of importlib

As mentioned the imp module provides you loading functions:

imp.load_source(name, path)
imp.load_compiled(name, path)

I've used these before to perform something similar.

In my case I defined a specific class with defined methods that were required. Once I loaded the module I would check if the class was in the module, and then create an instance of that class, something like this:

import imp
import os

def load_from_file(filepath):
    class_inst = None
    expected_class = 'MyClass'

    mod_name,file_ext = os.path.splitext(os.path.split(filepath)[-1])

    if file_ext.lower() == '.py':
        py_mod = imp.load_source(mod_name, filepath)

    elif file_ext.lower() == '.pyc':
        py_mod = imp.load_compiled(mod_name, filepath)

    if hasattr(py_mod, expected_class):
        class_inst = getattr(py_mod, expected_class)()

    return class_inst

jQuery datepicker, onSelect won't work

It should be "datepicker", not "datePicker" if you are using the jQuery UI DatePicker plugin. Perhaps, you have a different but similar plugin that doesn't support the select handler.

await is only valid in async function

The current implementation of async / await only supports the await keyword inside of async functions Change your start function signature so you can use await inside start.

 var start = async function(a, b) {

 }

For those interested, the proposal for top-level await is currently in Stage 2: https://github.com/tc39/proposal-top-level-await

round() for float in C++

It may be worth noting that if you wanted an integer result from the rounding you don't need to pass it through either ceil or floor. I.e.,

int round_int( double r ) {
    return (r > 0.0) ? (r + 0.5) : (r - 0.5); 
}

VBA procedure to import csv file into access

The easiest way to do it is to link the CSV-file into the Access database as a table. Then you can work on this table as if it was an ordinary access table, for instance by creating an appropriate query based on this table that returns exactly what you want.

You can link the table either manually or with VBA like this

DoCmd.TransferText TransferType:=acLinkDelim, TableName:="tblImport", _
    FileName:="C:\MyData.csv", HasFieldNames:=true

UPDATE

Dim db As DAO.Database

' Re-link the CSV Table
Set db = CurrentDb
On Error Resume Next:   db.TableDefs.Delete "tblImport":   On Error GoTo 0
db.TableDefs.Refresh
DoCmd.TransferText TransferType:=acLinkDelim, TableName:="tblImport", _
    FileName:="C:\MyData.csv", HasFieldNames:=true
db.TableDefs.Refresh

' Perform the import
db.Execute "INSERT INTO someTable SELECT col1, col2, ... FROM tblImport " _
   & "WHERE NOT F1 IN ('A1', 'A2', 'A3')"
db.Close:   Set db = Nothing

convert base64 to image in javascript/jquery

You can just create an Image object and put the base64 as its src, including the data:image... part like this:

var image = new Image();
image.src = 'data:image/png;base64,iVBORw0K...';
document.body.appendChild(image);

It's what they call "Data URIs" and here's the compatibility table for inner peace.

Font Awesome 5 font-family issue

If you are using SVG with JavaScript you need to enable this because it's disabled by default. Use

<script data-search-pseudo-elements ... >

inside your script tag.

How to update attributes without validation

You can do something like:

object.attribute = value
object.save(:validate => false)

Copying text to the clipboard using Java

This is the accepted answer written in a decorative way:

Toolkit.getDefaultToolkit()
        .getSystemClipboard()
        .setContents(
                new StringSelection(txtMySQLScript.getText()),
                null
        );

Warning: push.default is unset; its implicit value is changing in Git 2.0

Brought my answer over from other thread that may close as a duplicate...

From GIT documentation: Git Docs

Below gives the full information. In short, simple will only push the current working branch and even then only if it also has the same name on the remote. This is a very good setting for beginners and will become the default in GIT 2.0

Whereas matching will push all branches locally that have the same name on the remote. (Without regard to your current working branch ). This means potentially many different branches will be pushed, including those that you might not even want to share.

In my personal usage, I generally use a different option: current which pushes the current working branch, (because I always branch for any changes). But for a beginner I'd suggest simple

push.default
Defines the action git push should take if no refspec is explicitly given. Different values are well-suited for specific workflows; for instance, in a purely central workflow (i.e. the fetch source is equal to the push destination), upstream is probably what you want. Possible values are:

nothing - do not push anything (error out) unless a refspec is explicitly given. This is primarily meant for people who want to avoid mistakes by always being explicit.

current - push the current branch to update a branch with the same name on the receiving end. Works in both central and non-central workflows.

upstream - push the current branch back to the branch whose changes are usually integrated into the current branch (which is called @{upstream}). This mode only makes sense if you are pushing to the same repository you would normally pull from (i.e. central workflow).

simple - in centralized workflow, work like upstream with an added safety to refuse to push if the upstream branch's name is different from the local one.

When pushing to a remote that is different from the remote you normally pull from, work as current. This is the safest option and is suited for beginners.

This mode will become the default in Git 2.0.

matching - push all branches having the same name on both ends. This makes the repository you are pushing to remember the set of branches that will be pushed out (e.g. if you always push maint and master there and no other branches, the repository you push to will have these two branches, and your local maint and master will be pushed there).

To use this mode effectively, you have to make sure all the branches you would push out are ready to be pushed out before running git push, as the whole point of this mode is to allow you to push all of the branches in one go. If you usually finish work on only one branch and push out the result, while other branches are unfinished, this mode is not for you. Also this mode is not suitable for pushing into a shared central repository, as other people may add new branches there, or update the tip of existing branches outside your control.

This is currently the default, but Git 2.0 will change the default to simple.

Getting hold of the outer class object from the inner class object

if you don't have control to modify the inner class, the refection may help you (but not recommend). this$0 is reference in Inner class which tells which instance of Outer class was used to create current instance of Inner class.