Programs & Examples On #Filterfunction

System.BadImageFormatException: Could not load file or assembly

I found a different solution to this issue. Apparently my IIS 7 did not have 32bit mode enabled in my Application Pool by default.

To enable 32bit mode, open IIS and select your Application Pool. Mine was named "ASP.NET v4.0".
Right click, go to "Advanced Settings" and change the section named: "Enabled 32-bit Applications" to true.

Restart your web server and try again.

I found the fix from this blog reference: http://darrell.mozingo.net/2009/01/17/running-iis-7-in-32-bit-mode/

Additionally, you can change the settings on Visual Studio. In my case, I went to Tools > Options > Projects and Solutions > Web Projects and checked Use the 64 bit version of IIS Express for web sites and projects - This was on VS Pro 2015. Nothing else fixed it but this.

"Object doesn't support property or method 'find'" in IE

You are using the JavaScript array.find() method. Note that this is standard JS, and has nothing to do with jQuery. In fact, your entire code in the question makes no use of jQuery at all.

You can find the documentation for array.find() here: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/find

If you scroll to the bottom of this page, you will note that it has browser support info, and you will see that it states that IE does not support this method.

Ironically, your best way around this would be to use jQuery, which does have similar functionality that is supported in all browsers.

How to make a view with rounded corners?

public class RoundedCornerLayout extends FrameLayout {
    private double mCornerRadius;

    public RoundedCornerLayout(Context context) {
        this(context, null, 0);
    }

    public RoundedCornerLayout(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public RoundedCornerLayout(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init(context, attrs, defStyle);
    }

    private void init(Context context, AttributeSet attrs, int defStyle) {
        DisplayMetrics metrics = context.getResources().getDisplayMetrics();
        setLayerType(View.LAYER_TYPE_SOFTWARE, null);
    }

    public double getCornerRadius() {
        return mCornerRadius;
    }

    public void setCornerRadius(double cornerRadius) {
        mCornerRadius = cornerRadius;
    }

    @Override
    public void draw(Canvas canvas) {
        int count = canvas.save();

        final Path path = new Path();
        path.addRoundRect(new RectF(0, 0, canvas.getWidth(), canvas.getHeight()), (float) mCornerRadius, (float) mCornerRadius, Path.Direction.CW);
        canvas.clipPath(path, Region.Op.REPLACE);

        canvas.clipPath(path);
        super.draw(canvas);
        canvas.restoreToCount(count);
    }
}

How do you iterate through every file/directory recursively in standard C++?

Answers of getting all file names recursively with C++11 for Windows and Linux(with experimental/filesystem):
For Windows:

#include <io.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <windows.h>
void getFiles_w(string path, vector<string>& files) {
    intptr_t hFile = 0; 
    struct _finddata_t fileinfo;  
    string p; 
    if ((hFile = _findfirst(p.assign(path).append("\\*").c_str(), &fileinfo)) != -1) {
        do {
            if ((fileinfo.attrib & _A_SUBDIR)) {
                if (strcmp(fileinfo.name, ".") != 0 && strcmp(fileinfo.name, "..") != 0)
                    getFiles(p.assign(path).append("/").append(fileinfo.name), files);
            }
            else {
                files.push_back(p.assign(path).append("/").append(fileinfo.name));
            }
        } while (_findnext(hFile, &fileinfo) == 0);
    }
}

For Linux:

#include <experimental/filesystem>
bool getFiles(std::experimental::filesystem::path path, vector<string>& filenames) {
    namespace stdfs = std::experimental::filesystem;
    // http://en.cppreference.com/w/cpp/experimental/fs/directory_iterator
    const stdfs::directory_iterator end{} ;
    
    for (stdfs::directory_iterator iter{path}; iter != end ; ++iter) {
        // http://en.cppreference.com/w/cpp/experimental/fs/is_regular_file 
        if (!stdfs::is_regular_file(*iter)) { // comment out if all names (names of directories tc.) are required 
            if (getFiles(iter->path(), filenames)) 
                return true;
        }
        else {
            filenames.push_back(iter->path().string()) ;
            cout << iter->path().string() << endl;  
        }
    }
    return false;
}

Just remember to link -lstdc++fs when you compile it with g++ in Linux.

C# DateTime to UTC Time without changing the time

Use the DateTime.ToUniversalTime method.

Using HeapDumpOnOutOfMemoryError parameter for heap dump for JBoss

I found it hard to decipher what is meant by "working directory of the VM". In my example, I was using the Java Service Wrapper program to execute a jar - the dump files were created in the directory where I had placed the wrapper program, e.g. c:\myapp\bin. The reason I discovered this is because the files can be quite large and they filled up the hard drive before I discovered their location.

Oracle Add 1 hour in SQL

select sysdate + 1/24 from dual;

sysdate is a function without arguments which returns DATE type
+ 1/24 adds 1 hour to a date

select to_char(to_date('2014-10-15 03:30:00 pm', 'YYYY-MM-DD HH:MI:SS pm') + 1/24, 'YYYY-MM-DD HH:MI:SS pm') from dual;

How to get Chrome to allow mixed content?

On OSX using the current Chrome build (2/20/2020, 79.0.3945.130), you can:

Click on the 'i' info icon on the left side of address bar.

Click Site Settings

Scroll down to Insecure content

Change it from Blocked (Default) to Allow

Reload the page and try your action again.

How can I see the current value of my $PATH variable on OS X?

Use the command:

 echo $PATH

and you will see all path:

/Users/name/.rvm/gems/ruby-2.5.1@pe/bin:/Users/name/.rvm/gems/ruby-2.5.1@global/bin:/Users/sasha/.rvm/rubies/ruby-2.5.1/bin:/Users/sasha/.rvm/bin:

How to define multiple CSS attributes in jQuery?

Using a plain object, you can pair up strings that represent property names with their corresponding values. Changing the background color, and making text bolder, for instance would look like this:

$("#message").css({
    "background-color": "#0F0", 
    "font-weight"     : "bolder"
});

Alternatively, you can use the JavaScript property names too:

$("#message").css({
    backgroundColor: "rgb(128, 115, 94)",
    fontWeight     : "700"
});

More information can be found in jQuery's documentation.

Javascript : Send JSON Object with Ajax?

Adding Json.stringfy around the json that fixed the issue

How to add title to seaborn boxplot

Seaborn box plot returns a matplotlib axes instance. Unlike pyplot itself, which has a method plt.title(), the corresponding argument for an axes is ax.set_title(). Therefore you need to call

sns.boxplot('Day', 'Count', data= gg).set_title('lalala')

A complete example would be:

import seaborn as sns
import matplotlib.pyplot as plt

tips = sns.load_dataset("tips")
sns.boxplot(x=tips["total_bill"]).set_title("LaLaLa")

plt.show()

Of course you could also use the returned axes instance to make it more readable:

ax = sns.boxplot('Day', 'Count', data= gg)
ax.set_title('lalala')
ax.set_ylabel('lololo')

Android Studio was unable to find a valid Jvm (Related to MAC OS)

I am using Mac OS X 10.10 also. And to fix this problem.

  1. Open Android Studio application package content (by right click on Android Studio icon in Application folder)
  2. Open file Infor.plist
  3. Search and replace:

    <key> JVM version</key>
    <string>1.6*</string>
    

replaced by:

    <key> JVM version</key>
    <string>1.6+</string>

That's it!

How do I copy to the clipboard in JavaScript?

For the security reason you can't do that. You must choose Flash for copying to the clipboard.

I suggest this one: http://zeroclipboard.org/

Inputting a default image in case the src attribute of an html <img> is not valid?

_x000D_
_x000D_
<img style="background-image: url(image1), url(image2);"></img>                                            
_x000D_
_x000D_
_x000D_

Use background image that let you add multiple images. My case: image1 is the main image, this will get from some place (browser doing a request) image2 is a default local image to show while image1 is being loaded. If image1 returns any kind of error, the user won't see any change and this will be clean for user experience

Change package name for Android in React Native

In VS Code, press Ctrl + Shift + F and enter your old package name in 'Find' and enter your new package in 'Replace'. Then press 'Replace all occurrences'.

Definitely not the pragmatic way. But, it's done the trick for me.

PHP Fatal error: Using $this when not in object context

First you understand one thing, $this inside a class denotes the current object.
That is which is you are created out side of the class to call class function or variable.

So when you are calling your class function like foobar::foobarfunc(), object is not created. But inside that function you written return $this->foo(). Now here $this is nothing. Thats why its saying Using $this when not in object context in class.php

Solutions:

  1. Create a object and call foobarfunc().

  2. Call foo() using class name inside the foobarfunc().

JavaScript: get code to run every minute

Using setInterval:

setInterval(function() {
    // your code goes here...
}, 60 * 1000); // 60 * 1000 milsec

The function returns an id you can clear your interval with clearInterval:

var timerID = setInterval(function() {
    // your code goes here...
}, 60 * 1000); 

clearInterval(timerID); // The setInterval it cleared and doesn't run anymore.

A "sister" function is setTimeout/clearTimeout look them up.


If you want to run a function on page init and then 60 seconds after, 120 sec after, ...:

function fn60sec() {
    // runs every 60 sec and runs on init.
}
fn60sec();
setInterval(fn60sec, 60*1000);

CSS to hide INPUT BUTTON value text

I had the opposite problem (worked in Internet Explorer, but not in Firefox). For Internet Explorer, you need to add left padding, and for Firefox, you need to add transparent color. So here is our combined solution for a 16px x 16px icon button:

input.iconButton
{
    font-size: 1em;
    color: transparent; /* Fix for Firefox */
    border-style: none;
    border-width: 0;
    padding: 0 0 0 16px !important; /* Fix for Internet Explorer */
    text-align: left;
    width: 16px;
    height: 16px;
    line-height: 1 !important;
    background: transparent url(../images/button.gif) no-repeat scroll 0 0;
    overflow: hidden;
    cursor: pointer;
}

CardView not showing Shadow in Android L

Add android:hardwareAccelerated="true" in your manifests file like below it works for me

 <activity
        android:name=".activity.MyCardViewActivity"
        android:hardwareAccelerated="true"></activity>

Update style of a component onScroll in React.js

I solved the problem via using and modifying CSS variables. This way I do not have to modify the component state which causes performance issues.

index.css

:root {
  --navbar-background-color: rgba(95,108,255,1);
}

Navbar.jsx

import React, { Component } from 'react';
import styles from './Navbar.module.css';

class Navbar extends Component {

    documentStyle = document.documentElement.style;
    initalNavbarBackgroundColor = 'rgba(95, 108, 255, 1)';
    scrolledNavbarBackgroundColor = 'rgba(95, 108, 255, .7)';

    handleScroll = () => {
        if (window.scrollY === 0) {
            this.documentStyle.setProperty('--navbar-background-color', this.initalNavbarBackgroundColor);
        } else {
            this.documentStyle.setProperty('--navbar-background-color', this.scrolledNavbarBackgroundColor);
        }
    }

    componentDidMount() {
        window.addEventListener('scroll', this.handleScroll);
    }

    componentWillUnmount() {
        window.removeEventListener('scroll', this.handleScroll);
    }

    render () {
        return (
            <nav className={styles.Navbar}>
                <a href="/">Home</a>
                <a href="#about">About</a>
            </nav>
        );
    }
};

export default Navbar;

Navbar.module.css

.Navbar {
    background: var(--navbar-background-color);
}

Format Date output in JSF

With EL 2 (Expression Language 2) you can use this type of construct for your question:

    #{formatBean.format(myBean.birthdate)}

Or you can add an alternate getter in your bean resulting in

    #{myBean.birthdateString}

where getBirthdateString returns the proper text representation. Remember to annotate the get method as @Transient if it is an Entity.

Why does the Visual Studio editor show dots in blank spaces?

Press ctrl + E followed by S key to remove the lines in Visual Studio 10

Converting an int into a 4 byte char array (C)

Why would you need an intermediate cast to void * in C++ Because cpp doesn't allow direct conversion between pointers, you need to use reinterpret_cast or casting to void* does the thing.

Get all dates between two dates in SQL Server

This is the method that I would use.

DECLARE 
    @DateFrom DATETIME = GETDATE(),
    @DateTo DATETIME = DATEADD(HOUR, -1, GETDATE() + 2); -- Add 2 days and minus one hour


-- Dates spaced a day apart 

WITH MyDates (MyDate)
AS (
    SELECT @DateFrom
    UNION ALL
    SELECT DATEADD(DAY, 1, MyDate)
    FROM MyDates
    WHERE MyDate < @DateTo
   )

SELECT 
    MyDates.MyDate
    , CONVERT(DATE, MyDates.MyDate) AS [MyDate in DATE format]
FROM 
    MyDates;

Here is a similar example, but this time the dates are spaced one hour apart to further aid understanding of how the query works:

-- Alternative example with dates spaced an hour apart

WITH MyDates (MyDate)
AS (SELECT @DateFrom
    UNION ALL
    SELECT DATEADD(HOUR, 1, MyDate)
    FROM MyDates
    WHERE MyDate < @DateTo
   )

SELECT 
    MyDates.MyDate
FROM 
    MyDates;

As you can see, the query is fast, accurate and versatile.

How to output loop.counter in python jinja template?

in python:

env = Environment(loader=FileSystemLoader("templates"))
env.globals["enumerate"] = enumerate

in template:

{% for k,v in enumerate(list) %}
{% endfor %}

"SELECT ... IN (SELECT ...)" query in CodeIgniter

Note that these solutions use the Code Igniter Active Records Class

This method uses sub queries like you wish but you should sanitize $countryId yourself!

$this->db->select('username')
         ->from('user')
         ->where('`locationId` in', '(select `locationId` from `locations` where `countryId` = '.$countryId.')', false)
         ->get();

Or this method would do it using joins and will sanitize the data for you (recommended)!

$this->db->select('username')
         ->from('users')
         ->join('locations', 'users.locationid = locations.locationid', 'inner')
         ->where('countryid', $countryId)
         ->get();

npm - how to show the latest version of a package

If you're looking for the current and the latest versions of all your installed packages, you can also use:

npm outdated

Jenkins - Configure Jenkins to poll changes in SCM

That's an old question, I know. But, according to me, it is missing proper answer.

The actual / optimal workflow here would be to incorporate SVN's post-commit hook so it triggers Jenkins job after the actual commit is issued only, not in any other case. This way you avoid unneeded polls on your SCM system.

You may find the following links interesting:

In case of my setup in the corp's SVN server, I utilize the following (censored) script as a post-commit hook on the subversion server side:

#!/bin/sh

# POST-COMMIT HOOK

REPOS="$1"
REV="$2"
#TXN_NAME="$3"
LOGFILE=/var/log/xxx/svn/xxx.post-commit.log

MSG=$(svnlook pg --revprop $REPOS svn:log -r$REV)
JENK="http://jenkins.xxx.com:8080/job/xxx/job/xxx/buildWithParameters?token=xxx&username=xxx&cause=xxx+r$REV"
JENKtest="http://jenkins.xxx.com:8080/view/all/job/xxx/job/xxxx/buildWithParameters?token=xxx&username=xxx&cause=xxx+r$REV"

echo post-commit $* >> $LOGFILE 2>&1

# trigger Jenkins job - xxx
svnlook changed $REPOS -r $REV | cut -d' ' -f4 | grep -qP "branches/xxx/xxx/Source"
if test 0 -eq $? ; then
        echo $(date) - $REPOS - $REV: >> $LOGFILE
        svnlook changed $REPOS -r $REV | cut -d' ' -f4 | grep -P "branches/xxx/xxx/Source" >> $LOGFILE 2>&1
        echo logmsg: $MSG >> $LOGFILE 2>&1
        echo curl -qs $JENK >> $LOGFILE 2>&1
        curl -qs $JENK >> $LOGFILE 2>&1
        echo -------- >> $LOGFILE
fi

# trigger Jenkins job - xxxx
svnlook changed $REPOS -r $REV | cut -d' ' -f4 | grep -qP "branches/xxx_TEST"
if test 0 -eq $? ; then
        echo $(date) - $REPOS - $REV: >> $LOGFILE
        svnlook changed $REPOS -r $REV | cut -d' ' -f4 | grep -P "branches/xxx_TEST" >> $LOGFILE 2>&1
        echo logmsg: $MSG >> $LOGFILE 2>&1
        echo curl -qs $JENKtest >> $LOGFILE 2>&1
        curl -qs $JENKtest >> $LOGFILE 2>&1
        echo -------- >> $LOGFILE
fi

exit 0

How to replace NA values in a table for selected columns

We can solve it in data.table way with tidyr::repalce_na function and lapply

library(data.table)
library(tidyr)
setDT(df)
df[,c("a","b","c"):=lapply(.SD,function(x) replace_na(x,0)),.SDcols=c("a","b","c")]

In this way, we can also solve paste columns with NA string. First, we replace_na(x,""),then we can use stringr::str_c to combine columns!

How to load/reference a file as a File instance from the classpath

Try getting hold of a URL for your classpath resource:

URL url = this.getClass().getResource("/com/path/to/file.txt")

Then create a file using the constructor that accepts a URI:

File file = new File(url.toURI());

PHP CURL CURLOPT_SSL_VERIFYPEER ignored

According to documentation: to verify host or peer certificate you need to specify alternate certificates with the CURLOPT_CAINFO option or a certificate directory can be specified with the CURLOPT_CAPATH option.

Also look at CURLOPT_SSL_VERIFYHOST:

  • 1 to check the existence of a common name in the SSL peer certificate.
  • 2 to check the existence of a common name and also verify that it matches the hostname provided.

curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);

MySQL Trigger after update only if row has changed

BUT imagine a large table with changing columns. You have to compare every column and if the database changes you have to adjust the trigger. AND it doesn't "feel" good to compare every row hardcoded :)

Yeah, but that's the way to proceed.

As a side note, it's also good practice to pre-emptively check before updating:

UPDATE foo SET b = 3 WHERE a=3 and b <> 3;

In your example this would make it update (and thus overwrite) two rows instead of three.

WCF Service , how to increase the timeout?

The timeout configuration needs to be set at the client level, so the configuration I was setting in the web.config had no effect, the WCF test tool has its own configuration and there is where you need to set the timeout.

How to loop over grouped Pandas dataframe?

df.groupby('l_customer_id_i').agg(lambda x: ','.join(x)) does already return a dataframe, so you cannot loop over the groups anymore.

In general:

  • df.groupby(...) returns a GroupBy object (a DataFrameGroupBy or SeriesGroupBy), and with this, you can iterate through the groups (as explained in the docs here). You can do something like:

    grouped = df.groupby('A')
    
    for name, group in grouped:
        ...
    
  • When you apply a function on the groupby, in your example df.groupby(...).agg(...) (but this can also be transform, apply, mean, ...), you combine the result of applying the function to the different groups together in one dataframe (the apply and combine step of the 'split-apply-combine' paradigm of groupby). So the result of this will always be again a DataFrame (or a Series depending on the applied function).

Loop through all elements in XML using NodeList

public class XMLParser {
   public static void main(String[] args){
      try {
         DocumentBuilder dBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
         Document doc = dBuilder.parse(new File("xml input"));
         NodeList nl=doc.getDocumentElement().getChildNodes();

         for(int k=0;k<nl.getLength();k++){
             printTags((Node)nl.item(k));
         }
      } catch (Exception e) {/*err handling*/}
   }

   public static void printTags(Node nodes){
       if(nodes.hasChildNodes()  || nodes.getNodeType()!=3){
           System.out.println(nodes.getNodeName()+" : "+nodes.getTextContent());
           NodeList nl=nodes.getChildNodes();
           for(int j=0;j<nl.getLength();j++)printTags(nl.item(j));
       }
   }
}

Recursively loop through and print out all the xml child tags in the document, in case you don't have to change the code to handle dynamic changes in xml, provided it's a well formed xml.

ImportError: No module named enum

Please use --user at end of this, it is working fine for me.

pip install enum34 --user

Pass props to parent component in React.js

It appears there's a simple answer. Consider this:

var Child = React.createClass({
  render: function() {
    <a onClick={this.props.onClick.bind(null, this)}>Click me</a>
  }
});

var Parent = React.createClass({
  onClick: function(component, event) {
    component.props // #=> {Object...}
  },
  render: function() {
    <Child onClick={this.onClick} />
  }
});

The key is calling bind(null, this) on the this.props.onClick event, passed from the parent. Now, the onClick function accepts arguments component, AND event. I think that's the best of all worlds.

UPDATE: 9/1/2015

This was a bad idea: letting child implementation details leak in to the parent was never a good path. See Sebastien Lorber's answer.

Why should hash functions use a prime number modulus?

I've read the popular wordpress website linked in some of the above popular answers at the top. From what I've understood, I'd like to share a simple observation I made.

You can find all the details in the article here, but assume the following holds true:

  • Using a prime number gives us the "best chance" of an unique value

A general hashmap implementation wants 2 things to be unique.

  • Unique hash code for the key
  • Unique index to store the actual value

How do we get the unique index? By making the initial size of the internal container a prime as well. So basically, prime is involved because it possesses this unique trait of producing unique numbers which we end up using to ID objects and finding indexes inside the internal container.

Example:

key = "key"

value = "value" uniqueId = "k" * 31 ^ 2 + "e" * 31 ^ 1` + "y"

maps to unique id

Now we want a unique location for our value - so we

uniqueId % internalContainerSize == uniqueLocationForValue , assuming internalContainerSize is also a prime.

I know this is simplified, but I'm hoping to get the general idea through.

Which mime type should I use for mp3

Your best bet would be using the RFC defined mime-type audio/mpeg.

server certificate verification failed. CAfile: /etc/ssl/certs/ca-certificates.crt CRLfile: none

Eventually, add the http.sslverify to your .git/config.

[core]
    repositoryformatversion = 0
    filemode = true
    bare = false
    logallrefupdates = true
[remote "origin"]
    url = https://server/user/project.git
    fetch = +refs/heads/*:refs/remotes/origin/*
[branch "master"]
    remote = origin
    merge = refs/heads/master
[http]
        sslVerify = false

JPA and Hibernate - Criteria vs. JPQL or HQL

We used mainly Criteria in our application in the beginning but after it was replaced with HQL due to the performance issues.
Mainly we are using very complex queries with several joins which leads to multiple queries in Criteria but is very optimized in HQL.
The case is that we use just several propeties on specific object and not complete objects. With Criteria the problem was also string concatenation.
Let say if you need to display name and surname of the user in HQL it is quite easy (name || ' ' || surname) but in Crteria this is not possible.
To overcome this we used ResultTransormers, where there were methods where such concatenation was implemented for needed result.
Today we mainly use HQL like this:

String hql = "select " +
            "c.uuid as uuid," +
            "c.name as name," +
            "c.objective as objective," +
            "c.startDate as startDate," +
            "c.endDate as endDate," +
            "c.description as description," +
            "s.status as status," +
            "t.type as type " +
            "from " + Campaign.class.getName() + " c " +
            "left join c.type t " +
            "left join c.status s";

Query query =  hibernateTemplate.getSessionFactory().getCurrentSession().getSession(EntityMode.MAP).createQuery(hql);
query.setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
return query.list();

so in our case the returned records are maps of needed properties.

Running ASP.Net on a Linux based server

There is the Mono Project from Novell that will allow you to run ASP.Net on Apache.

http://www.mono-project.com/Main_Page

How to access cookies in AngularJS?

The original accepted answer mentions jquery.cookie plugin. A few months ago though, it was renamed to js-cookie and the jQuery dependency removed. One of the reasons was just to make it easy to integrate with other frameworks, like Angular.

Now, if you want to integrate js-cookie with angular, it is as easy as something like:

module.factory( "cookies", function() {
  return Cookies.noConflict();
});

And that's it. No jQuery. No ngCookies.


You can also create custom instances to handle specific server-side cookies that are written differently. Take for example PHP, that convert the spaces in the server-side to a plus sign + instead of also percent-encode it:

module.factory( "phpCookies", function() {
  return Cookies
    .noConflict()
    .withConverter(function( value, name ) {
      return value
            // Decode all characters according to the "encodeURIComponent" spec
            .replace(/(%[0-9A-Z]{2})+/g, decodeURIComponent)
            // Decode the plus sign to spaces
            .replace(/\+/g, ' ')
    });
});

The usage for a custom Provider would be something like this:

module.service( "customDataStore", [ "phpCookies", function( phpCookies ) {
  this.storeData = function( data ) {
    phpCookies.set( "data", data );
  };
  this.containsStoredData = function() {
    return phpCookies.get( "data" );
  }
}]);

I hope this helps anyone.

See detailed info in this issue: https://github.com/js-cookie/js-cookie/issues/103

For detailed docs on how to integrate with server-side, see here: https://github.com/js-cookie/js-cookie/blob/master/SERVER_SIDE.md

How to push to History in React Router v4?

You can use the history methods outside of your components. Try by the following way.

First, create a history object used the history package:

// src/history.js

import { createBrowserHistory } from 'history';

export default createBrowserHistory();

Then wrap it in <Router> (please note, you should use import { Router } instead of import { BrowserRouter as Router }):

// src/index.jsx

// ...
import { Router, Route, Link } from 'react-router-dom';
import history from './history';

ReactDOM.render(
  <Provider store={store}>
    <Router history={history}>
      <div>
        <ul>
          <li><Link to="/">Home</Link></li>
          <li><Link to="/login">Login</Link></li>
        </ul>
        <Route exact path="/" component={HomePage} />
        <Route path="/login" component={LoginPage} />
      </div>
    </Router>
  </Provider>,
  document.getElementById('root'),
);

Change your current location from any place, for example:

// src/actions/userActionCreators.js

// ...
import history from '../history';

export function login(credentials) {
  return function (dispatch) {
    return loginRemotely(credentials)
      .then((response) => {
        // ...
        history.push('/');
      });
  };
}

UPD: You can also see a slightly different example in React Router FAQ.

Is it possible to ignore one single specific line with Pylint?

Pylint message control is documented in the Pylint manual:

Is it possible to locally disable a particular message?

Yes, this feature has been added in Pylint 0.11. This may be done by adding # pylint: disable=some-message,another-one at the desired block level or at the end of the desired line of code.

You can use the message code or the symbolic names.

For example,

def test():
    # Disable all the no-member violations in this function
    # pylint: disable=no-member
    ...
global VAR # pylint: disable=global-statement

The manual also has further examples.

There is a wiki that documents all Pylint messages and their codes.

Debugging JavaScript in IE7

Microsoft Script Editor can be used to debug Javascript in IE. It's less buggy than Microsoft Script Debugger but has the same basic functionality, which unfortunately is pretty much limited to stepping through execution. I can't seem to inspect variables or any handy stuff like that. Also, it only shipped with Office XP/2003 for some bizarre reason. More info here if you're game.

I downloaded the Visual Web Developer 2008 Express Edition mentioned by Eugene Lazutkin but haven't had a chance to try it yet. I'd recommend trying that before Script Editor/Debugger.

Highest Salary in each department

select T1.* from (select empname as e1,department_name,salary from employee ) as T1, (select max(salary) maxsal,department_name dept1 from employee group by department_name) as T2 where T1.department_name=T2.dept1 and T1.salary=maxsal;

What is the difference between instanceof and Class.isAssignableFrom(...)?

When using instanceof, you need to know the class of B at compile time. When using isAssignableFrom() it can be dynamic and change during runtime.

Postgres user does not exist?

I get exactly the same errors as kryshah with su - postgres and sudo -u postgres psql. DanielM's answer gives also errors.

Outputs when wrong settings

Answer however from przbabu's comment.

masi$ psql
psql: FATAL:  database "masi" does not exist
masi$ psql -U postgres
psql: FATAL:  role "postgres" does not exist
masi$ psql postgres
psql (9.4.1)
Type "help" for help.

I think the some part of this problem may be in owner settings in OSX

masi$ ls -al /Users/
total 0
drwxr-xr-x   7 root      admin  238 Jul  3 09:50 .
drwxr-xr-x  37 root      wheel 1326 Jul  2 19:02 ..
-rw-r--r--   1 root      wheel    0 Sep 10  2014 .localized
drwxrwxrwt   7 root      wheel  238 Apr  9 19:49 Shared
drwxr-xr-x   2 root      admin   68 Jul  3 09:50 postgres
drwxr-xr-x+ 71 masi      staff 2414 Jul  3 09:50 masi

but doing sudo chown -R postgres:staff /Users/postgres gives chown: invalid user: ‘postgres:staff’.

In short, this is not the solution the problem. Use the tools provided by the postgres installation to create a user and database.

To get right settings and outputs

There are specific commands after postgres installation to add a new user to the database system. After initdb, run the following as described here

createuser --pwprompt postgres
createdb -Opostgres -Eutf8 masi_development
psql -U postgres -W masi_development

To avoid the password request all the time, you have three choices as described here.

How can I set the color of a selected row in DataGrid

I've tried ControlBrushKey but it didn't work for unselected rows. The background for the unselected row was still white. But I've managed to find out that I have to override the rowstyle.

<DataGrid x:Name="pbSelectionDataGrid" Height="201" Margin="10,0"
          FontSize="20" SelectionMode="Single" FontWeight="Bold">
    <DataGrid.Resources>
        <SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}" Color="#FFFDD47C"/>
        <SolidColorBrush x:Key="{x:Static SystemColors.ControlBrushKey}" Color="#FFA6E09C"/>
        <SolidColorBrush x:Key="{x:Static SystemColors.HighlightTextBrushKey}" Color="Red"/>
        <SolidColorBrush x:Key="{x:Static SystemColors.ControlTextBrushKey}" Color="Violet"/>
    </DataGrid.Resources>
    <DataGrid.RowStyle>
        <Style TargetType="DataGridRow">
            <Setter Property="Background" Value="LightBlue" />
        </Style>
    </DataGrid.RowStyle>
</DataGrid>

Set adb vendor keys

I tried almost anything but no help...

Everytime was just this

?  ~ adb devices    
List of devices attached
* daemon not running. starting it now on port 5037 *
* daemon started successfully *
aeef5e4e    unauthorized

However I've managed to connect device!

There is tutor, step by step.

  1. Remove existing adb keys on PC:

$ rm -v .android/adbkey* .android/adbkey .android/adbkey.pub

  1. Remove existing authorized adb keys on device, path is /data/misc/adb/adb_keys

  2. Now create new adb keypair

? ~ adb keygen .android/adbkey adb I 47453 711886 adb_auth_host.cpp:220] generate_key '.android/adbkey' adb I 47453 711886 adb_auth_host.cpp:173] Writing public key to '.android/adbkey.pub'

  1. Manually copy from PC .android/adbkey.pub (pubkic key) to Device on path /data/misc/adb/adb_keys

  2. Reboot device and check adb devices :

? ~ adb devices List of devices attached aeef5e4e device

Permissions of /data/misc/adb/adb_keys are (766/-rwxrw-rw-) on my device

Failed to load resource: the server responded with a status of 404 (Not Found) error in server

Use your browser's network inspector (F12) to see when the browser is requesting the bgbody.png image and what absolute path it's using and why the server is returning a 404 response.

...assuming that bgbody.png actually exists :)

Is your CSS in a stylesheet file or in a <style> block in a page? If it's in a stylesheet then the relative path must be relative to the CSS stylesheet (not the document that references it). If it's in a page then it must be relative to the current resource path. If you're using non-filesystem-based resource paths (i.e. using URL rewriting or URL routing) then this will cause problems and it's best to always use absolute paths.

Going by your relative path it looks like you store your images separately from your stylesheets. I don't think this is a good idea - I support storing images and other resources, like fonts, in the same directory as the stylesheet itself, as it simplifies paths and is also a more logical filesystem arrangement.

Can't connect to MySQL server on '127.0.0.1' (10061) (2003)

Slightly different case, but it may help someone.

I followed the instructions to create a secondary database instance, and I had to clone the ini file as part of that. It was failing to start the service, with the same error. Turns out notepad.exe had re-encoded the cloned ini file as UTF8-BOM, and MySQL (version 8) refused to work with it. Removing the BOM fixed the problem.

How do you sort an array on multiple columns?

My own library for working with ES6 iterables (blinq) allows (among other things) easy multi-level sorting

_x000D_
_x000D_
const blinq = window.blinq.blinq_x000D_
// or import { blinq } from 'blinq'_x000D_
// or const { blinq } = require('blinq')_x000D_
const dates = [{_x000D_
    day: 1, month: 10, year: 2000_x000D_
  },_x000D_
  {_x000D_
    day: 1, month: 1, year: 2000_x000D_
  },_x000D_
  {_x000D_
    day: 2, month: 1, year: 2000_x000D_
  },_x000D_
  {_x000D_
    day: 1, month: 1, year: 1999_x000D_
  },_x000D_
  {_x000D_
    day: 1, month: 1, year: 2000_x000D_
  }_x000D_
]_x000D_
const sortedDates = blinq(dates)_x000D_
  .orderBy(x => x.year)_x000D_
  .thenBy(x => x.month)_x000D_
  .thenBy(x => x.day);_x000D_
_x000D_
console.log(sortedDates.toArray())_x000D_
// or console.log([...sortedDates])
_x000D_
<script src="https://cdn.jsdelivr.net/npm/[email protected]"></script>
_x000D_
_x000D_
_x000D_

How can I get new selection in "select" in Angular 2?

Another option is to store the object in value as a string:

<select [ngModel]="selectedDevice | json" (ngModelChange)="onChange($event)">
    <option [value]="i | json" *ngFor="let i of devices">{{i}}</option>
</select>

component:

onChange(val) {
    this.selectedDevice = JSON.parse(val);
}

This was the only way I could get two way binding working to set the select value on page load. This was because my list that populates the select box was not the exact same object as my select was bound to and it needs to be the same object, not just same property values.

Select multiple value in DropDownList using ASP.NET and C#

In that case you should use ListBox control instead of dropdown and Set the SelectionMode property to Multiple

<asp:ListBox runat="server" SelectionMode="Multiple" >
  <asp:ListItem Text="test1"></asp:ListItem>
  <asp:ListItem Text="test2"></asp:ListItem>
  <asp:ListItem Text="test3"></asp:ListItem>
</asp:ListBox>

Replace preg_replace() e modifier with preg_replace_callback

You shouldn't use flag e (or eval in general).

You can also use T-Regx library

pattern('(^|_)([a-z])')->replace($word)->by()->group(2)->callback('strtoupper');

add elements to object array

If you can, use a List<Subject> instead of Subject[]... this will let you do Student.Subject.Add(new Subject()). If that is not possible, you'll have to resize your array... look at Array.Resize() at http://msdn.microsoft.com/en-us/library/bb348051.aspx

Disable developer mode extensions pop up in Chrome

1) Wait for the popup balloon to appear.

2) Open a new tab.

3) Close the a new tab. The popup will be gone from the original tab.

A small Chrome extension can automate these steps:

manifest.json

{
  "name": "Open and close tab",
  "description": "After Chrome starts, open and close a new tab.",
  "version": "1.0",
  "manifest_version": 2,
  "permissions": ["tabs"],
  "background": {
    "scripts": ["background.js"], 
    "persistent": false
  }
}

background.js

// This runs when Chrome starts up
chrome.runtime.onStartup.addListener(function() {

  // Execute the inner function after a few seconds
  setTimeout(function() {

    // Open new tab
    chrome.tabs.create({url: "about:blank"});

    // Get tab ID of newly opened tab, then close the tab
    chrome.tabs.query({'currentWindow': true}, function(tabs) {
      var newTabId = tabs[1].id;
      chrome.tabs.remove(newTabId);
    });

  }, 5000);

});

With this extension installed, launch Chrome and immediately switch apps before the popup appears... a few seconds later, the popup will be gone and you won't see it when you switch back to Chrome.

MySQL select 10 random rows from 600K rows fast

Its very simple and single line query.

SELECT * FROM Table_Name ORDER BY RAND() LIMIT 0,10;

Dynamically set value of a file input

It is not possible to dynamically change the value of a file field, otherwise you could set it to "c:\yourfile" and steal files very easily.

However there are many solutions to a multi-upload system. I'm guessing that you're wanting to have a multi-select open dialog.

Perhaps have a look at http://www.plupload.com/ - it's a very flexible solution to multiple file uploads, and supports drop zones e.t.c.

Format a BigDecimal as String with max 2 decimal digits, removing 0 on decimal part

If its money use:

NumberFormat.getNumberInstance(java.util.Locale.US).format(bd)

How to pass a value from one Activity to another in Android?

Standard way of passing data from one activity to another:

If you want to send large number of data from one activity to another activity then you can put data in a bundle and then pass it using putExtra() method.

//Create the `intent`
 Intent i = new Intent(this, ActivityTwo.class);
String one="xxxxxxxxxxxxxxx";
String two="xxxxxxxxxxxxxxxxxxxxx";
//Create the bundle
Bundle bundle = new Bundle();
//Add your data to bundle
bundle.putString(“ONE”, one);
bundle.putString(“TWO”, two);  
//Add the bundle to the intent
i.putExtras(bundle);
//Fire that second activity
startActivity(i);

otherwise you can use putExtra() directly with intent to send data and getExtra() to get data.

Intent i=new Intent(this, ActivityTwo.class);
i.putExtra("One",one);
i.putExtra("Two",two);
startActivity(i);

SQLite UPSERT / UPDATE OR INSERT

This is a late answer. Starting from SQLIte 3.24.0, released on June 4, 2018, there is finally a support for UPSERT clause following PostgreSQL syntax.

INSERT INTO players (user_name, age)
  VALUES('steven', 32) 
  ON CONFLICT(user_name) 
  DO UPDATE SET age=excluded.age;

Note: For those having to use a version of SQLite earlier than 3.24.0, please reference this answer below (posted by me, @MarqueIV).

However if you do have the option to upgrade, you are strongly encouraged to do so as unlike my solution, the one posted here achieves the desired behavior in a single statement. Plus you get all the other features, improvements and bug fixes that usually come with a more recent release.

Why javascript getTime() is not a function?

To use this function/method,you need an instance of the class Date .

This method is always used in conjunction with a Date object.

See the code below :

var d = new Date();
d.getTime();

Link : http://www.w3schools.com/jsref/jsref_getTime.asp

Making TextView scrollable on Android

XML - You can use android:scrollHorizontally Attribute

Whether the text is allowed to be wider than the view (and therefore can be scrolled horizontally).

May be a boolean value, such as "true" or "false".

Prigramacaly - setHorizontallyScrolling(boolean)

Creating a JSON array in C#

new {var_data[counter] =new [] { 
                new{  "S NO":  "+ obj_Data_Row["F_ID_ITEM_MASTER"].ToString() +","PART NAME": " + obj_Data_Row["F_PART_NAME"].ToString() + ","PART ID": " + obj_Data_Row["F_PART_ID"].ToString() + ","PART CODE":" + obj_Data_Row["F_PART_CODE"].ToString() + ", "CIENT PART ID": " + obj_Data_Row["F_ID_CLIENT"].ToString() + ","TYPES":" + obj_Data_Row["F_TYPE"].ToString() + ","UOM":" + obj_Data_Row["F_UOM"].ToString() + ","SPECIFICATION":" + obj_Data_Row["F_SPECIFICATION"].ToString() + ","MODEL":" + obj_Data_Row["F_MODEL"].ToString() + ","LOCATION":" + obj_Data_Row["F_LOCATION"].ToString() + ","STD WEIGHT":" + obj_Data_Row["F_STD_WEIGHT"].ToString() + ","THICKNESS":" + obj_Data_Row["F_THICKNESS"].ToString() + ","WIDTH":" + obj_Data_Row["F_WIDTH"].ToString() + ","HEIGHT":" + obj_Data_Row["F_HEIGHT"].ToString() + ","STUFF QUALITY":" + obj_Data_Row["F_STUFF_QTY"].ToString() + ","FREIGHT":" + obj_Data_Row["F_FREIGHT"].ToString() + ","THRESHOLD FG":" + obj_Data_Row["F_THRESHOLD_FG"].ToString() + ","THRESHOLD CL STOCK":" + obj_Data_Row["F_THRESHOLD_CL_STOCK"].ToString() + ","DESCRIPTION":" + obj_Data_Row["F_DESCRIPTION"].ToString() + "}
        }
    };

The VMware Authorization Service is not running

I followed Telvin's suggestion and it worked on Windows 7:

  1. Run the VMware installer by right clicking on it and selecting "Run as Administrator"
  2. In the resulting popup menu, select "Repair installation"

How to return a file (FileContentResult) in ASP.NET WebAPI

If you want to return IHttpActionResult you can do it like this:

[HttpGet]
public IHttpActionResult Test()
{
    var stream = new MemoryStream();

    var result = new HttpResponseMessage(HttpStatusCode.OK)
    {
        Content = new ByteArrayContent(stream.GetBuffer())
    };
    result.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment")
    {
        FileName = "test.pdf"
    };
    result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");

    var response = ResponseMessage(result);

    return response;
}

Jenkins - how to build a specific branch

To checkout the branch via Jenkins scripts use:

stage('Checkout SCM') {
    git branch: 'branchName', credentialsId: 'your_credentials', url: "giturlrepo"
}

Launching a website via windows commandline

start chrome https://www.google.com/ or start firefox https://www.google.com/

Get all table names of a particular database by SQL query?

USE DBName;
SELECT * FROM sys.Tables;

We can deal without GO in-place of you can use semicolon ;.

How to use the curl command in PowerShell?

In Powershell 3.0 and above there is both a Invoke-WebRequest and Invoke-RestMethod. Curl is actually an alias of Invoke-WebRequest in PoSH. I think using native Powershell would be much more appropriate than curl, but it's up to you :).

Invoke-WebRequest MSDN docs are here: https://technet.microsoft.com/en-us/library/hh849901.aspx?f=255&MSPPError=-2147217396

Invoke-RestMethod MSDN docs are here: https://technet.microsoft.com/en-us/library/hh849971.aspx?f=255&MSPPError=-2147217396

Get Windows version in a batch file

It's much easier (and faster) to get this information by only parsing the output of ver:

@echo off
setlocal
for /f "tokens=4-5 delims=. " %%i in ('ver') do set VERSION=%%i.%%j
if "%version%" == "10.0" echo Windows 10
if "%version%" == "6.3" echo Windows 8.1
if "%version%" == "6.2" echo Windows 8.
if "%version%" == "6.1" echo Windows 7.
if "%version%" == "6.0" echo Windows Vista.
rem etc etc
endlocal

This table on MSDN documents which version number corresponds to which Windows product version (this is where you get the 6.1 means Windows 7 information from).

The only drawback of this technique is that it cannot distinguish between the equivalent server and consumer versions of Windows.

How do I copy a version of a single file from one git branch to another?

Please note that in the accepted answer, the first option stages the entire file from the other branch (like git add ... had been performed), and that the second option just results in copying the file, but doesn't stage the changes (as if you had just edited the file manually and had outstanding differences).

Git copy file from another branch without staging it

Changes staged (e.g. git add filename):

$ git checkout directory/somefile.php feature-B

$ git status
On branch feature-A
Your branch is up-to-date with 'origin/feature-A'.
Changes to be committed:
  (use "git reset HEAD <file>..." to unstage)

        modified:   directory/somefile.php

Changes outstanding (not staged or committed):

$ git show feature-B:directory/somefile.php > directory/somefile.php

$ git status
On branch feature-A
Your branch is up-to-date with 'origin/feature-A'.
Changes not staged for commit:
  (use "git add <file>..." to update what will be committed)
  (use "git checkout -- <file>..." to discard changes in working directory)

        modified:   directory/somefile.php

no changes added to commit (use "git add" and/or "git commit -a")

C# Validating input for textbox on winforms

With WinForms you can use the ErrorProvider in conjunction with the Validating event to handle the validation of user input. The Validating event provides the hook to perform the validation and ErrorProvider gives a nice consistent approach to providing the user with feedback on any error conditions.

http://msdn.microsoft.com/en-us/library/system.windows.forms.errorprovider.aspx

How to get the second column from command output?

Or use sed & regex.

<some_command> | sed 's/^.* \(".*"$\)/\1/'

JavaScript, getting value of a td with id name

if i click table name its shown all fields about table. i did table field to show. but i need to know click function.

My Code:

$sql = "SHOW tables from database_name where tables_in_databasename not like '%tablename' and tables_in_databasename not like '%tablename%'";


$result=mysqli_query($cons,$sql);

$count = 0;

$array = array();

while ($row = mysqli_fetch_assoc($result)) {

    $count++;

    $tbody_txt .= '<tr>';

    foreach ($row as $key => $value) {
        if($count  == '1') {
            $thead_txt .='<td>'.$key.'</td>';
        }
        $tbody_txt .='<td>'.$value.'</td>';


        $array[$key][] = $value;
    }
}?>

Why do abstract classes in Java have constructors?

Implementation wise you will often see inside super() statement in subclasses constructors, something like:


public class A extends AbstractB{

  public A(...){
     super(String constructorArgForB, ...);
     ...
  }
}


How to get build time stamp from Jenkins build variables?

This answer below shows another method using "regexp feature of the Description Setter Plugin" which solved my problem as I could not install new plugins on Jenkins due to permission issues:

Use build timestamp in setting build description Jenkins

Downloading a Google font and setting up an offline site that uses it

Found a step-by-step way to achieve this (for 1 font):
(as of Sep-9 2013)

  1. Choose your font at http://www.google.com/fonts
  2. Add the desired one to your collection using "Add to collection" blue button
  3. Click the "See all styles" button near "Remove from collection" button and make sure that you have selected other styles you may also need such as 'bold'...
  4. Click the 'Use' tab button on bottom right of the page
  5. Click the download button on top with a down arrow image
  6. Click on "zip file" on the the popup message that appears
  7. Click "Close" button on the popup
  8. Slowly scroll the page until you see the 3 tabs "Standrd|@import|Javascript"
  9. Click "@import" tab
  10. Select and copy the url between 'url(' and ')'
  11. Copy it on address bar in a new tab and go there
  12. Do "File > Save page as..." and name it "desiredfontname.css" (replace accordingly)
  13. Decompress the fonts .zip file you downloaded (.ttf should be extracted)
  14. Go to "http://ttf2woff.com/" and convert any .ttf extracted from zip to .woff
  15. Edit desiredfontname.css and replace any url within it [between 'url(' and ')'] with the corresponding converted .woff file you got on ttf2woff.com; path you write should be according to your server doc_root
  16. Save the file and move it at its final place and write the corresponding <link/> CSS tag to import these in your HTML page
  17. From now, refer to this font by its font-family name in your styles

That's it. Cause I had the same problem and the solution on top did not work for me.

How do I change the figure size with subplots?

Alternatively, create a figure() object using the figsize argument and then use add_subplot to add your subplots. E.g.

import matplotlib.pyplot as plt
import numpy as np

f = plt.figure(figsize=(10,3))
ax = f.add_subplot(121)
ax2 = f.add_subplot(122)
x = np.linspace(0,4,1000)
ax.plot(x, np.sin(x))
ax2.plot(x, np.cos(x), 'r:')

Simple Example

Benefits of this method are that the syntax is closer to calls of subplot() instead of subplots(). E.g. subplots doesn't seem to support using a GridSpec for controlling the spacing of the subplots, but both subplot() and add_subplot() do.

Selecting fields from JSON output

Assume you stored that dictionary in a variable called values. To get id in to a variable, do:

idValue = values['criteria'][0]['id']

If that json is in a file, do the following to load it:

import json
jsonFile = open('your_filename.json', 'r')
values = json.load(jsonFile)
jsonFile.close()

If that json is from a URL, do the following to load it:

import urllib, json
f = urllib.urlopen("http://domain/path/jsonPage")
values = json.load(f)
f.close()

To print ALL of the criteria, you could:

for criteria in values['criteria']:
    for key, value in criteria.iteritems():
        print key, 'is:', value
    print ''

Angular2 Exception: Can't bind to 'routerLink' since it isn't a known native property

You have in your module

import {Routes, RouterModule} from '@angular/router';

you have to export the module RouteModule

example:

@NgModule({
  imports: [RouterModule.forChild(routes)],
  exports: [RouterModule]
})

to be able to access the functionalities for all who import this module.

Is Secure.ANDROID_ID unique for each device?

//Fields
String myID;
int myversion = 0;


myversion = Integer.valueOf(android.os.Build.VERSION.SDK);
if (myversion < 23) {
        TelephonyManager mngr = (TelephonyManager) 
getSystemService(Context.TELEPHONY_SERVICE);
        myID= mngr.getDeviceId();
    }
    else
    {
        myID = 
Settings.Secure.getString(getApplicationContext().getContentResolver(), 
Settings.Secure.ANDROID_ID);
    }

Yes, Secure.ANDROID_ID is unique for each device.

how to make negative numbers into positive

a *= (-1);

problem solved. If there is a smaller solution for a problem, then why you guys going for a complex solution. Please direct people to use the base logic also because then only the people can train their programming logic.

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.

How do I use the nohup command without getting nohup.out?

Have you tried redirecting all three I/O streams:

nohup ./yourprogram > foo.out 2> foo.err < /dev/null &

PDO Prepared Inserts multiple rows in single query

For what it is worth, I have seen a lot of users recommend iterating through INSERT statements instead of building out as a single string query as the selected answer did. I decided to run a simple test with just two fields and a very basic insert statement:

<?php
require('conn.php');

$fname = 'J';
$lname = 'M';

$time_start = microtime(true);
$stmt = $db->prepare('INSERT INTO table (FirstName, LastName) VALUES (:fname, :lname)');

for($i = 1; $i <= 10; $i++ )  {
    $stmt->bindParam(':fname', $fname);
    $stmt->bindParam(':lname', $lname);
    $stmt->execute();

    $fname .= 'O';
    $lname .= 'A';
}


$time_end = microtime(true);
$time = $time_end - $time_start;

echo "Completed in ". $time ." seconds <hr>";

$fname2 = 'J';
$lname2 = 'M';

$time_start2 = microtime(true);
$qry = 'INSERT INTO table (FirstName, LastName) VALUES ';
$qry .= "(?,?), ";
$qry .= "(?,?), ";
$qry .= "(?,?), ";
$qry .= "(?,?), ";
$qry .= "(?,?), ";
$qry .= "(?,?), ";
$qry .= "(?,?), ";
$qry .= "(?,?), ";
$qry .= "(?,?), ";
$qry .= "(?,?)";

$stmt2 = $db->prepare($qry);
$values = array();

for($j = 1; $j<=10; $j++) {
    $values2 = array($fname2, $lname2);
    $values = array_merge($values,$values2);

    $fname2 .= 'O';
    $lname2 .= 'A';
}

$stmt2->execute($values);

$time_end2 = microtime(true);
$time2 = $time_end2 - $time_start2;

echo "Completed in ". $time2 ." seconds <hr>";
?>

While the overall query itself took milliseconds or less, the latter (single string) query was consistently 8 times faster or more. If this was built out to say reflect an import of thousands of rows on many more columns, the difference could be enormous.

Mapping object to dictionary and vice versa

Seems reflection only help here.. I've done small example of converting object to dictionary and vise versa:

[TestMethod]
public void DictionaryTest()
{
    var item = new SomeCLass { Id = "1", Name = "name1" };
    IDictionary<string, object> dict = ObjectToDictionary<SomeCLass>(item);
    var obj = ObjectFromDictionary<SomeCLass>(dict);
}

private T ObjectFromDictionary<T>(IDictionary<string, object> dict)
    where T : class 
{
    Type type = typeof(T);
    T result = (T)Activator.CreateInstance(type);
    foreach (var item in dict)
    {
        type.GetProperty(item.Key).SetValue(result, item.Value, null);
    }
    return result;
}

private IDictionary<string, object> ObjectToDictionary<T>(T item)
    where T: class
{
    Type myObjectType = item.GetType();
    IDictionary<string, object> dict = new Dictionary<string, object>();
    var indexer = new object[0];
    PropertyInfo[] properties = myObjectType.GetProperties();
    foreach (var info in properties)
    {
        var value = info.GetValue(item, indexer);
        dict.Add(info.Name, value);
    }
    return dict;
}

See full command of running/stopped container in Docker

Use:

docker inspect -f "{{.Path}} {{.Args}} ({{.Id}})" $(docker ps -a -q)

That will display the command path and arguments, similar to docker ps.

How to set delay in android?

Here's an example where I change the background image from one to another with a 2 second alpha fade delay both ways - 2s fadeout of the original image into a 2s fadein into the 2nd image.

    public void fadeImageFunction(View view) {

    backgroundImage = (ImageView) findViewById(R.id.imageViewBackground);
    backgroundImage.animate().alpha(0f).setDuration(2000);

    // A new thread with a 2-second delay before changing the background image
    new Timer().schedule(
            new TimerTask(){
                @Override
                public void run(){
                    // you cannot touch the UI from another thread. This thread now calls a function on the main thread
                    changeBackgroundImage();
                }
            }, 2000);
   }

// this function runs on the main ui thread
private void changeBackgroundImage(){
    runOnUiThread(new Runnable() {
        @Override
        public void run() {
            backgroundImage = (ImageView) findViewById(R.id.imageViewBackground);
            backgroundImage.setImageResource(R.drawable.supes);
            backgroundImage.animate().alpha(1f).setDuration(2000);
        }
    });
}

how to open a jar file in Eclipse

use java decompiler. http://jd.benow.ca/. you can open the jar files.

Thanks, Manirathinam.

What is the best way to test for an empty string in Go?

Just to add more to comment

Mainly about how to do performance testing.

I did testing with following code:

import (
    "testing"
)

var ss = []string{"Hello", "", "bar", " ", "baz", "ewrqlosakdjhf12934c r39yfashk fjkashkfashds fsdakjh-", "", "123"}

func BenchmarkStringCheckEq(b *testing.B) {
    c := 0
    b.ResetTimer()
    for n := 0; n < b.N; n++ {
            for _, s := range ss {
                    if s == "" {
                            c++
                    }
            }
    } 
    t := 2 * b.N
    if c != t {
            b.Fatalf("did not catch empty strings: %d != %d", c, t)
    }
}
func BenchmarkStringCheckLen(b *testing.B) {
    c := 0
    b.ResetTimer()
    for n := 0; n < b.N; n++ {
            for _, s := range ss { 
                    if len(s) == 0 {
                            c++
                    }
            }
    } 
    t := 2 * b.N
    if c != t {
            b.Fatalf("did not catch empty strings: %d != %d", c, t)
    }
}
func BenchmarkStringCheckLenGt(b *testing.B) {
    c := 0
    b.ResetTimer()
    for n := 0; n < b.N; n++ {
            for _, s := range ss {
                    if len(s) > 0 {
                            c++
                    }
            }
    } 
    t := 6 * b.N
    if c != t {
            b.Fatalf("did not catch empty strings: %d != %d", c, t)
    }
}
func BenchmarkStringCheckNe(b *testing.B) {
    c := 0
    b.ResetTimer()
    for n := 0; n < b.N; n++ {
            for _, s := range ss {
                    if s != "" {
                            c++
                    }
            }
    } 
    t := 6 * b.N
    if c != t {
            b.Fatalf("did not catch empty strings: %d != %d", c, t)
    }
}

And results were:

% for a in $(seq 50);do go test -run=^$ -bench=. --benchtime=1s ./...|grep Bench;done | tee -a log
% sort -k 3n log | head -10

BenchmarkStringCheckEq-4        150149937            8.06 ns/op
BenchmarkStringCheckLenGt-4     147926752            8.06 ns/op
BenchmarkStringCheckLenGt-4     148045771            8.06 ns/op
BenchmarkStringCheckNe-4        145506912            8.06 ns/op
BenchmarkStringCheckLen-4       145942450            8.07 ns/op
BenchmarkStringCheckEq-4        146990384            8.08 ns/op
BenchmarkStringCheckLenGt-4     149351529            8.08 ns/op
BenchmarkStringCheckNe-4        148212032            8.08 ns/op
BenchmarkStringCheckEq-4        145122193            8.09 ns/op
BenchmarkStringCheckEq-4        146277885            8.09 ns/op

Effectively variants usually do not reach fastest time and there is only minimal difference (about 0.01ns/op) between variant top speed.

And if I look full log, difference between tries is greater than difference between benchmark functions.

Also there does not seem to be any measurable difference between BenchmarkStringCheckEq and BenchmarkStringCheckNe or BenchmarkStringCheckLen and BenchmarkStringCheckLenGt even if latter variants should inc c 6 times instead of 2 times.

You can try to get some confidence about equal performance by adding tests with modified test or inner loop. This is faster:

func BenchmarkStringCheckNone4(b *testing.B) {
    c := 0
    b.ResetTimer()
    for n := 0; n < b.N; n++ {
            for _, _ = range ss {
                    c++
            }
    }
    t := len(ss) * b.N
    if c != t {
            b.Fatalf("did not catch empty strings: %d != %d", c, t)
    }
}

This is not faster:

func BenchmarkStringCheckEq3(b *testing.B) {
    ss2 := make([]string, len(ss))
    prefix := "a"
    for i, _ := range ss {
            ss2[i] = prefix + ss[i]
    }
    c := 0
    b.ResetTimer()
    for n := 0; n < b.N; n++ {
            for _, s := range ss2 {
                    if s == prefix {
                            c++
                    }
            }
    }
    t := 2 * b.N
    if c != t {
            b.Fatalf("did not catch empty strings: %d != %d", c, t)
    }
}

Both variants are usually faster or slower than difference between main tests.

It would also good to generate test strings (ss) using string generator with relevant distribution. And have variable lengths too.

So I don't have any confidence of performance difference between main methods to test empty string in go.

And I can state with some confidence, it is faster not to test empty string at all than test empty string. And also it is faster to test empty string than to test 1 char string (prefix variant).

Vertical rulers in Visual Studio Code

Visual Studio Code 0.10.10 introduced this feature. To configure it, go to menu FilePreferencesSettings and add this to to your user or workspace settings:

"editor.rulers": [80,120]

The color of the rulers can be customized like this:

"workbench.colorCustomizations": {
    "editorRuler.foreground": "#ff4081"
}

How to export and import environment variables in windows?

You can use RegEdit to export the following two keys:

HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment

HKEY_CURRENT_USER\Environment

The first set are system/global environment variables; the second set are user-level variables. Edit as needed and then import the .reg files on the new machine.

PHP Multidimensional Array Searching (Find key by specific value)

This class method can search in array by multiple conditions:

class Stdlib_Array
{
    public static function multiSearch(array $array, array $pairs)
    {
        $found = array();
        foreach ($array as $aKey => $aVal) {
            $coincidences = 0;
            foreach ($pairs as $pKey => $pVal) {
                if (array_key_exists($pKey, $aVal) && $aVal[$pKey] == $pVal) {
                    $coincidences++;
                }
            }
            if ($coincidences == count($pairs)) {
                $found[$aKey] = $aVal;
            }
        }

        return $found;
    }    
}

// Example:

$data = array(
    array('foo' => 'test4', 'bar' => 'baz'),
    array('foo' => 'test',  'bar' => 'baz'),
    array('foo' => 'test1', 'bar' => 'baz3'),
    array('foo' => 'test',  'bar' => 'baz'),
    array('foo' => 'test',  'bar' => 'baz4'),
    array('foo' => 'test4', 'bar' => 'baz1'),
    array('foo' => 'test',  'bar' => 'baz1'),
    array('foo' => 'test3', 'bar' => 'baz2'),
    array('foo' => 'test',  'bar' => 'baz'),
    array('foo' => 'test',  'bar' => 'baz'),
    array('foo' => 'test4', 'bar' => 'baz1')
);

$result = Stdlib_Array::multiSearch($data, array('foo' => 'test4', 'bar' => 'baz1'));

var_dump($result);

Will produce:

array(2) {
  [5]=>
  array(2) {
    ["foo"]=>
    string(5) "test4"
    ["bar"]=>
    string(4) "baz1"
  }
  [10]=>
  array(2) {
    ["foo"]=>
    string(5) "test4"
    ["bar"]=>
    string(4) "baz1"
  }
}

Any difference between await Promise.all() and multiple await?

You can check for yourself.

In this fiddle, I ran a test to demonstrate the blocking nature of await, as opposed to Promise.all which will start all of the promises and while one is waiting it will go on with the others.

What does "The following object is masked from 'package:xxx'" mean?

I have the same problem. I avoid it with remove.packages("Package making this confusion") and it works. In my case, I don't need the second package, so that is not a very good idea.

How to extract request http headers from a request using NodeJS connect

If you use Express 4.x, you can use the req.get(headerName) method as described in Express 4.x API Reference

how to convert a string to a bool

bool b = str.Equals("1")? true : false;

Or even better, as suggested in a comment below:

bool b = str.Equals("1");

Replace X-axis with own values

Yo could also set labels = FALSE inside axis(...) and print the labels in a separate command with Text. With this option you can rotate the text the text in case you need it

lablist<-as.vector(c(1:10))
axis(1, at=seq(1, 10, by=1), labels = FALSE)
text(seq(1, 10, by=1), par("usr")[3] - 0.2, labels = lablist, srt = 45, pos = 1, xpd = TRUE)

Detailed explanation here

Image with rotated labels

SELECT INTO USING UNION QUERY

You can also try:

create table new_table as
select * from table1
union
select * from table2

Error in eval(expr, envir, enclos) : object not found

Don't know why @Janos deleted his answer, but it's correct: your data frame Train doesn't have a column named pre. When you pass a formula and a data frame to a model-fitting function, the names in the formula have to refer to columns in the data frame. Your Train has columns called residual.sugar, total.sulfur, alcohol and quality. You need to change either your formula or your data frame so they're consistent with each other.

And just to clarify: Pre is an object containing a formula. That formula contains a reference to the variable pre. It's the latter that has to be consistent with the data frame.

CSS, Images, JS not loading in IIS

If you're seeing 403 errors in your browser console, check your MVC Bundle Config. Bundle names should not match any existing folder names in your project.

eg.

bundles.Add(new StyleBundle("~/Content/css")...

...would cause issues for IIS if the folder structure $(ProjectDir)\Content\css exists in your project, since it tries to look within the existing folder for bundle content that's not there.

Instead just use something like:

bundles.Add(new StyleBundle("~/Content/cssbundle")...

Send POST request with JSON data using Volley

  • Create an object of RequestQueue class.

    RequestQueue queue = Volley.newRequestQueue(this);
    
  • Create a StringRequest with response and error listener.

     StringRequest sr = new StringRequest(Request.Method.POST,"http://api.someservice.com/post/comment", new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {
            mPostCommentResponse.requestCompleted();
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            mPostCommentResponse.requestEndedWithError(error);
        }
    }){
        @Override
        protected Map<String,String> getParams(){
            Map<String,String> params = new HashMap<String, String>();
            params.put("user",userAccount.getUsername());
            params.put("pass",userAccount.getPassword());
            params.put("comment", Uri.encode(comment));
            params.put("comment_post_ID",String.valueOf(postId));
            params.put("blogId",String.valueOf(blogId));
    
            return params;
        }
    
        @Override
        public Map<String, String> getHeaders() throws AuthFailureError {
            Map<String,String> params = new HashMap<String, String>();
            params.put("Content-Type","application/x-www-form-urlencoded");
            return params;
        }
    };
    
  • Add your request into the RequestQueue.

    queue.add(jsObjRequest);
    
  • Create PostCommentResponseListener interface just so you can see it. It’s a simple delegate for the async request.

    public interface PostCommentResponseListener {
    public void requestStarted();
    public void requestCompleted();
    public void requestEndedWithError(VolleyError error);
    }
    
  • Include INTERNET permission inside AndroidManifest.xml file.

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

How do you properly determine the current script directory?

The os.path... approach was the 'done thing' in Python 2.

In Python 3, you can find directory of script as follows:

from pathlib import Path
cwd = Path(__file__).parents[0]

How do I remove a submodule?

To remove a submodule added using:

git submodule add [email protected]:repos/blah.git lib/blah

Run:

git rm lib/blah

That's it.

For old versions of git (circa ~1.8.5) use:

git submodule deinit lib/blah
git rm lib/blah
git config -f .gitmodules --remove-section submodule.lib/blah

Original purpose of <input type="hidden">?

The values of form elements including type='hidden' are submitted to the server when the form is posted. input type="hidden" values are not visible in the page. Maintaining User IDs in hidden fields, for example, is one of the many uses.

SO uses a hidden field for the upvote click.

<input value="16293741" name="postId" type="hidden">

Using this value, the server-side script can store the upvote.

Where is Java Installed on Mac OS X?

Use unix find function to find javas installed...

sudo find / -name java

Convert Time DataType into AM PM Format:

Use following syntax to convert a time to AM PM format.

Replace the field name with the value in following query.

select CONVERT(varchar(15),CAST('17:30:00.0000000' AS TIME),100)

Dark theme in Netbeans 7 or 8

And then there is the original plugin ez-on-da-ice. Better yet, you can complain to me directly if there are issues. I promise you, I am mostly very responsive :).

http://plugins.netbeans.org/plugin/40985/ez-on-da-ice

enter image description here

Prevent WebView from displaying "web page not available"

Check out the discussion at Android WebView onReceivedError(). It's quite long, but the consensus seems to be that a) you can't stop the "web page not available" page appearing, but b) you could always load an empty page after you get an onReceivedError

Get current scroll position of ScrollView in React Native

If you wish to simply get the current position (e.g. when some button is pressed) rather than tracking it whenever the user scrolls, then invoking an onScroll listener is going to cause performance issues. Currently the most performant way to simply get current scroll position is using react-native-invoke package. There is an example for this exact thing, but the package does multiple other things.

Read about it here. https://medium.com/@talkol/invoke-any-native-api-directly-from-pure-javascript-in-react-native-1fb6afcdf57d#.68ls1sopd

INSTALL_FAILED_UPDATE_INCOMPATIBLE when I try to install compiled .apk on device

I installed Astro file manager and searched for a previous version of the apk-file, found one on the sdcard and deleted the apk-file using Astro file manager.

How to use Selenium with Python?

You mean Selenium WebDriver? Huh....

Prerequisite: Install Python based on your OS

Install with following command

pip install -U selenium

And use this module in your code

from selenium import webdriver

You can also use many of the following as required

from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import Select
from selenium.common.exceptions import NoSuchElementException

Here is an updated answer

I would recommend you to run script without IDE... Here is my approach

  1. USE IDE to find xpath of object / element
  2. And use find_element_by_xpath().click()

An example below shows login page automation

#ScriptName : Login.py
#---------------------
from selenium import webdriver

#Following are optional required
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import Select
from selenium.common.exceptions import NoSuchElementException

baseurl = "http://www.mywebsite.com/login.php"
username = "admin"
password = "admin"

xpaths = { 'usernameTxtBox' : "//input[@name='username']",
           'passwordTxtBox' : "//input[@name='password']",
           'submitButton' :   "//input[@name='login']"
         }

mydriver = webdriver.Firefox()
mydriver.get(baseurl)
mydriver.maximize_window()

#Clear Username TextBox if already allowed "Remember Me" 
mydriver.find_element_by_xpath(xpaths['usernameTxtBox']).clear()

#Write Username in Username TextBox
mydriver.find_element_by_xpath(xpaths['usernameTxtBox']).send_keys(username)

#Clear Password TextBox if already allowed "Remember Me" 
mydriver.find_element_by_xpath(xpaths['passwordTxtBox']).clear()

#Write Password in password TextBox
mydriver.find_element_by_xpath(xpaths['passwordTxtBox']).send_keys(password)

#Click Login button
mydriver.find_element_by_xpath(xpaths['submitButton']).click()

There is an another way that you can find xpath of any object -

  1. Install Firebug and Firepath addons in firefox
  2. Open URL in Firefox
  3. Press F12 to open Firepath developer instance
  4. Select Firepath in below browser pane and chose select by "xpath"
  5. Move cursor of the mouse to element on webpage
  6. in the xpath textbox you will get xpath of an object/element.
  7. Copy Paste xpath to the script.

Run script -

python Login.py

You can also use a CSS selector instead of xpath. CSS selectors are slightly faster than xpath in most cases, and are usually preferred over xpath (if there isn't an ID attribute on the elements you're interacting with).

Firepath can also capture the object's locator as a CSS selector if you move your cursor to the object. You'll have to update your code to use the equivalent find by CSS selector method instead -

find_element_by_css_selector(css_selector) 

What techniques can be used to speed up C++ compilation times?

Using dynamic linking instead of static one make you compiler faster that can feel.

If you use t Cmake, active the property:

set(BUILD_SHARED_LIBS ON)

Build Release, using static linking can get more optimize.

How to list npm user-installed packages?

npm list -g --depth=0
  • npm: the Node package manager command line tool
  • list -g: display a tree of every package found in the user’s folders (without the -g option it only shows the current directory’s packages)
  • depth 0 / — depth=0: avoid including every package’s dependencies in the tree view

This version of Android Studio cannot open this project, please retry with Android Studio 3.4 or newer

I encountered with this error and just decrease gradle version and android plugin version to 5.1.1 and 3.4.2.

Angularjs - display current date

View

<div ng-app="myapp">
{{AssignedDate.now() | date:'yyyy-MM-dd HH:mm:ss'}}
</div>

Controller

var app = angular.module('myapp',[])

app.run(function($rootScope){
    $rootScope.AssignedDate = Date;
})

Installed Ruby 1.9.3 with RVM but command line doesn't show ruby -v

  • Open Terminal.
  • Go to Edit -> Profile Preferences.
  • Select the Title & command Tab in the window opened.
  • Mark the checkbox Run command as login shell.
  • close the window and restart the Terminal.

Check this Official Linkenter image description here

Method has the same erasure as another method in type

Java generics uses type erasure. The bit in the angle brackets (<Integer> and <String>) gets removed, so you'd end up with two methods that have an identical signature (the add(Set) you see in the error). That's not allowed because the runtime wouldn't know which to use for each case.

If Java ever gets reified generics, then you could do this, but that's probably unlikely now.

Launching Google Maps Directions via an intent on Android

You can Launch Google Maps Directions via an intent on Android through this way

btn_search_route.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            String source = et_source.getText().toString();
            String destination = et_destination.getText().toString();

            if (TextUtils.isEmpty(source)) {
                et_source.setError("Enter Soruce point");
            } else if (TextUtils.isEmpty(destination)) {
                et_destination.setError("Enter Destination Point");
            } else {
                String sendstring="http://maps.google.com/maps?saddr=" +
                        source +
                        "&daddr=" +
                        destination;
                Intent intent = new Intent(android.content.Intent.ACTION_VIEW,
                        Uri.parse(sendstring));
                startActivity(intent);
            }
        }

    });

Using Auto Layout in UITableView for dynamic cell layouts & variable row heights

With regard to the accepted answer by @smileyborg, I have found

[cell.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize]

to be unreliable in some cases where constraints are ambiguous. Better to force the layout engine to calculate the height in one direction, by using the helper category on UIView below:

-(CGFloat)systemLayoutHeightForWidth:(CGFloat)w{
    [self setNeedsLayout];
    [self layoutIfNeeded];
    CGSize size = [self systemLayoutSizeFittingSize:CGSizeMake(w, 1) withHorizontalFittingPriority:UILayoutPriorityRequired verticalFittingPriority:UILayoutPriorityFittingSizeLevel];
    CGFloat h = size.height;
    return h;
}

Where w: is the width of the tableview

How to add a where clause in a MySQL Insert statement?

For Empty row how we can insert values on where clause

Try this

UPDATE table_name SET username="",password="" WHERE id =""

Countdown timer in React

Countdown of user input

Interface Screenshot screenshot

import React, { Component } from 'react';
import './App.css';

class App extends Component {
  constructor() {
    super();
    this.state = {
      hours: 0,
      minutes: 0,
      seconds:0
    }
    this.hoursInput = React.createRef();
    this.minutesInput= React.createRef();
    this.secondsInput = React.createRef();
  }

  inputHandler = (e) => {
    this.setState({[e.target.name]: e.target.value});
  }

  convertToSeconds = ( hours, minutes,seconds) => {
    return seconds + minutes * 60 + hours * 60 * 60;
  }

  startTimer = () => {
    this.timer = setInterval(this.countDown, 1000);
  }

  countDown = () => {
    const  { hours, minutes, seconds } = this.state;
    let c_seconds = this.convertToSeconds(hours, minutes, seconds);

    if(c_seconds) {

      // seconds change
      seconds ? this.setState({seconds: seconds-1}) : this.setState({seconds: 59});

      // minutes change
      if(c_seconds % 60 === 0 && minutes) {
        this.setState({minutes: minutes -1});
      }

      // when only hours entered
      if(!minutes && hours) {
        this.setState({minutes: 59});
      }

      // hours change
      if(c_seconds % 3600 === 0 && hours) {
        this.setState({hours: hours-1});
      }

    } else {
      clearInterval(this.timer);
    }
  }


  stopTimer = () => {
    clearInterval(this.timer);
  }

  resetTimer = () => {
    this.setState({
      hours: 0,
      minutes: 0,
      seconds: 0
    });
    this.hoursInput.current.value = 0;
    this.minutesInput.current.value = 0;
    this.secondsInput.current.value = 0;
  }


  render() {
    const { hours, minutes, seconds } = this.state;

    return (
      <div className="App">
         <h1 className="title"> (( React Countdown )) </h1>
         <div className="inputGroup">
            <h3>Hrs</h3>
            <input ref={this.hoursInput} type="number" placeholder={0}  name="hours"  onChange={this.inputHandler} />
            <h3>Min</h3>
            <input  ref={this.minutesInput} type="number"  placeholder={0}   name="minutes"  onChange={this.inputHandler} />
            <h3>Sec</h3>
            <input   ref={this.secondsInput} type="number"  placeholder={0}  name="seconds"  onChange={this.inputHandler} />
         </div>
         <div>
            <button onClick={this.startTimer} className="start">start</button>
            <button onClick={this.stopTimer}  className="stop">stop</button>
            <button onClick={this.resetTimer}  className="reset">reset</button>
         </div>
         <h1> Timer {hours}: {minutes} : {seconds} </h1>
      </div>

    );
  }
}

export default App;

How to implement a secure REST API with node.js

If you want to secure your application, then you should definitely start by using HTTPS instead of HTTP, this ensures a creating secure channel between you & the users that will prevent sniffing the data sent back & forth to the users & will help keep the data exchanged confidential.

You can use JWTs (JSON Web Tokens) to secure RESTful APIs, this has many benefits when compared to the server-side sessions, the benefits are mainly:

1- More scalable, as your API servers will not have to maintain sessions for each user (which can be a big burden when you have many sessions)

2- JWTs are self contained & have the claims which define the user role for example & what he can access & issued at date & expiry date (after which JWT won't be valid)

3- Easier to handle across load-balancers & if you have multiple API servers as you won't have to share session data nor configure server to route the session to same server, whenever a request with a JWT hit any server it can be authenticated & authorized

4- Less pressure on your DB as well as you won't have to constantly store & retrieve session id & data for each request

5- The JWTs can't be tampered with if you use a strong key to sign the JWT, so you can trust the claims in the JWT that is sent with the request without having to check the user session & whether he is authorized or not, you can just check the JWT & then you are all set to know who & what this user can do.

Many libraries provide easy ways to create & validate JWTs in most programming languages, for example: in node.js one of the most popular is jsonwebtoken

Since REST APIs generally aims to keep the server stateless, so JWTs are more compatible with that concept as each request is sent with Authorization token that is self contained (JWT) without the server having to keep track of user session compared to sessions which make the server stateful so that it remembers the user & his role, however, sessions are also widely used & have their pros, which you can search for if you want.

One important thing to note is that you have to securely deliver the JWT to the client using HTTPS & save it in a secure place (for example in local storage).

You can learn more about JWTs from this link

How to check if activity is in foreground or in visible background?

Here is a solution using Application class.

public class AppSingleton extends Application implements Application.ActivityLifecycleCallbacks {

private WeakReference<Context> foregroundActivity;


@Override
public void onActivityResumed(Activity activity) {
    foregroundActivity=new WeakReference<Context>(activity);
}

@Override
public void onActivityPaused(Activity activity) {
    String class_name_activity=activity.getClass().getCanonicalName();
    if (foregroundActivity != null && 
            foregroundActivity.get().getClass().getCanonicalName().equals(class_name_activity)) {
        foregroundActivity = null;
    }
}

//............................

public boolean isOnForeground(@NonNull Context activity_cntxt) {
    return isOnForeground(activity_cntxt.getClass().getCanonicalName());
}

public boolean isOnForeground(@NonNull String activity_canonical_name) {
    if (foregroundActivity != null && foregroundActivity.get() != null) {
        return foregroundActivity.get().getClass().getCanonicalName().equals(activity_canonical_name);
    }
    return false;
}
}

You can simply use it like follows,

((AppSingleton)context.getApplicationContext()).isOnForeground(context_activity);

If you have a reference to the required Activity or using the canonical name of the Activity, you can find out whether it's in the foreground or not. This solution may not be foolproof. Therefore your comments are really welcome.

Concept of void pointer in C programming

Void pointers are pointers that has no data type associated with it.A void pointer can hold address of any type and can be typcasted to any type. But, void pointer cannot be directly be dereferenced.

int x = 1;
void *p1;
p1 = &x;
cout << *p1 << endl; // this will give error
cout << (int *)(*p) << endl; // this is valid

How to reset sequence in postgres and fill id column with new data?

If you don't want to retain the ordering of ids, then you can

ALTER SEQUENCE seq RESTART WITH 1;
UPDATE t SET idcolumn=nextval('seq');

I doubt there's an easy way to do that in the order of your choice without recreating the whole table.

Occurrences of substring in a string

Here it is, wrapped up in a nice and reusable method:

public static int count(String text, String find) {
        int index = 0, count = 0, length = find.length();
        while( (index = text.indexOf(find, index)) != -1 ) {                
                index += length; count++;
        }
        return count;
}

How to calculate md5 hash of a file using javascript

HTML5 + spark-md5 and Q

Assuming your'e using a modern browser (that supports HTML5 File API), here's how you calculate the MD5 Hash of a large file (it will calculate the hash on variable chunks)

_x000D_
_x000D_
function calculateMD5Hash(file, bufferSize) {
  var def = Q.defer();

  var fileReader = new FileReader();
  var fileSlicer = File.prototype.slice || File.prototype.mozSlice || File.prototype.webkitSlice;
  var hashAlgorithm = new SparkMD5();
  var totalParts = Math.ceil(file.size / bufferSize);
  var currentPart = 0;
  var startTime = new Date().getTime();

  fileReader.onload = function(e) {
    currentPart += 1;

    def.notify({
      currentPart: currentPart,
      totalParts: totalParts
    });

    var buffer = e.target.result;
    hashAlgorithm.appendBinary(buffer);

    if (currentPart < totalParts) {
      processNextPart();
      return;
    }

    def.resolve({
      hashResult: hashAlgorithm.end(),
      duration: new Date().getTime() - startTime
    });
  };

  fileReader.onerror = function(e) {
    def.reject(e);
  };

  function processNextPart() {
    var start = currentPart * bufferSize;
    var end = Math.min(start + bufferSize, file.size);
    fileReader.readAsBinaryString(fileSlicer.call(file, start, end));
  }

  processNextPart();
  return def.promise;
}

function calculate() {

  var input = document.getElementById('file');
  if (!input.files.length) {
    return;
  }

  var file = input.files[0];
  var bufferSize = Math.pow(1024, 2) * 10; // 10MB

  calculateMD5Hash(file, bufferSize).then(
    function(result) {
      // Success
      console.log(result);
    },
    function(err) {
      // There was an error,
    },
    function(progress) {
      // We get notified of the progress as it is executed
      console.log(progress.currentPart, 'of', progress.totalParts, 'Total bytes:', progress.currentPart * bufferSize, 'of', progress.totalParts * bufferSize);
    });
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/q.js/1.4.1/q.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/spark-md5/2.0.2/spark-md5.min.js"></script>

<div>
  <input type="file" id="file"/>
  <input type="button" onclick="calculate();" value="Calculate" class="btn primary" />
</div>
_x000D_
_x000D_
_x000D_

PHP: HTTP or HTTPS?

If your request is sent by HTTPS you will have an extra server variable named 'HTTPS'

if (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off') { //HTTPS } 

Get index of element as child relative to parent

There's no need to require a big library like jQuery to accomplish this, if you don't want to. To achieve this with built-in DOM manipulation, get a collection of the li siblings in an array, and on click, check the indexOf the clicked element in that array.

_x000D_
_x000D_
const lis = [...document.querySelectorAll('#wizard > li')];_x000D_
lis.forEach((li) => {_x000D_
  li.addEventListener('click', () => {_x000D_
    const index = lis.indexOf(li);_x000D_
    console.log(index);_x000D_
  });_x000D_
});
_x000D_
<ul id="wizard">_x000D_
    <li>Step 1</li>_x000D_
    <li>Step 2</li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

Or, with event delegation:

_x000D_
_x000D_
const lis = [...document.querySelectorAll('#wizard li')];_x000D_
document.querySelector('#wizard').addEventListener('click', ({ target }) => {_x000D_
  // Make sure the clicked element is a <li> which is a child of wizard:_x000D_
  if (!target.matches('#wizard > li')) return;_x000D_
  _x000D_
  const index = lis.indexOf(target);_x000D_
  console.log(index);_x000D_
});
_x000D_
<ul id="wizard">_x000D_
    <li>Step 1</li>_x000D_
    <li>Step 2</li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

Or, if the child elements may change dynamically (like with a todo list), then you'll have to construct the array of lis on every click, rather than beforehand:

_x000D_
_x000D_
const wizard = document.querySelector('#wizard');_x000D_
wizard.addEventListener('click', ({ target }) => {_x000D_
  // Make sure the clicked element is a <li>_x000D_
  if (!target.matches('li')) return;_x000D_
  _x000D_
  const lis = [...wizard.children];_x000D_
  const index = lis.indexOf(target);_x000D_
  console.log(index);_x000D_
});
_x000D_
<ul id="wizard">_x000D_
    <li>Step 1</li>_x000D_
    <li>Step 2</li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

How to break a while loop from an if condition inside the while loop?

An "if" is not a loop. Just use the break inside the "if" and it will break out of the "while".

If you ever need to use genuine nested loops, Java has the concept of a labeled break. You can put a label before a loop, and then use the name of the label is the argument to break. It will break outside of the labeled loop.

How do I set up the database.yml file in Rails?

At first I would use http://ruby.railstutorial.org/.

And database.yml is place where you put setup for database your application use - username, password, host - for each database. With new application you dont need to change anything - simply use default sqlite setup.

How to remove "index.php" in codeigniter's path

If you are using Apache place a .htaccess file in your root web directory containing the following:

RewriteEngine on
RewriteCond $1 !^(index\.php|[Javascript / CSS / Image root Folder name(s)]|robots\.txt)
RewriteRule ^(.*)$ /index.php/$1 [L]

Another good version is located here:

http://snipplr.com/view/5966/codeigniter-htaccess/

How to increase the gap between text and underlining in CSS

I was able to Do it using the U (Underline Tag)

u {
    text-decoration: none;
    position: relative;
}
u:after {
    content: '';
    width: 100%;
    position: absolute;
    left: 0;
    bottom: 1px;
    border-width: 0 0 1px;
    border-style: solid;
}


<a href="" style="text-decoration:none">
    <div style="text-align: right; color: Red;">
        <u> Shop Now</u>
    </div>
</a>

Inner join vs Where

I don't know about Oracle but I know that the old syntax is being deprecated in SQL Server and will disappear eventually. Before I used that old syntax in a new query I would check what Oracle plans to do with it.

I prefer the newer syntax rather than the mixing of the join criteria with other needed where conditions. In the newer syntax it is much clearer what creates the join and what other conditions are being applied. Not really a big problem in a short query like this, but it gets much more confusing when you have a more complex query. Since people learn on the basic queries, I would tend to prefer people learn to use the join syntax before they need it in a complex query.

And again I don't know Oracle specifically, but I know the SQL Server version of the old style left join is flawed even in SQL Server 2000 and gives inconsistent results (sometimes a left join sometimes a cross join), so it should never be used. Hopefully Oracle doesn't suffer the same issue, but certainly left and right joins can be mcuh harder to properly express in the old syntax.

Plus it has been my experience (and of course this is strictly a personal opinion, you may have differnt experience) that developers who use the ANSII standard joins tend to have a better understanding of what a join is and what it means in terms of getting data out of the database. I belive that is becasue most of the people with good database understanding tend to write more complex queries and those seem to me to be far easier to maintain using the ANSII Standard than the old style.

Can you 'exit' a loop in PHP?

$arr = array('one', 'two', 'three', 'four', 'stop', 'five');
foreach ($arr as $val) {
    if ($val == 'stop') {
        break;    /* You could also write 'break 1;' here. */
    }
    echo "$val<br />\n";
}

How do I check out a specific version of a submodule using 'git submodule'?

Submodule repositories stay in a detached HEAD state pointing to a specific commit. Changing that commit simply involves checking out a different tag or commit then adding the change to the parent repository.

$ cd submodule
$ git checkout v2.0
Previous HEAD position was 5c1277e... bumped version to 2.0.5
HEAD is now at f0a0036... version 2.0

git-status on the parent repository will now report a dirty tree:

# On branch dev [...]
#
#   modified:   submodule (new commits)

Add the submodule directory and commit to store the new pointer.

How to Parse JSON Array with Gson

[
      {
           id : '1',
           title: 'sample title',
           ....
      },
      {
           id : '2',
           title: 'sample title',
           ....
     },
      ...
 ]

Check Easy code for this output

 Gson gson=new GsonBuilder().create();
                List<Post> list= Arrays.asList(gson.fromJson(yourResponse.toString,Post[].class));

HTML how to clear input using javascript?

Try this :

<script type="text/javascript">
function clearThis(target){
    if(target.value == "[email protected]")
    {
        target.value= "";
    }
}
</script>

Is there something like Codecademy for Java

As of right now, I do not know of any. It appears the code academy folks have set their sites on Ruby on Rails. They do not rule Java out of the picture however.

Cast Double to Integer in Java

You need to explicitly get the int value using method intValue() like this:

Double d = 5.25;
Integer i = d.intValue(); // i becomes 5

Or

double d = 5.25;
int i = (int) d;

.NET - How do I retrieve specific items out of a Dataset?

I prefer to use something like this:

int? var1 = ds.Tables[0].Rows[0].Field<int?>("ColumnName");

or

int? var1 = ds.Tables[0].Rows[0].Field<int?>(3);   //column index

How to clear a textbox using javascript

Simple one

onfocus="javascript:this.value=''" onblur="javascript: if(this.value==''){this.value='Search...';}"

How can I reverse the order of lines in a file?

tail -r works in most Linux and MacOS systems

seq 1 20 | tail -r

Is there an easy way to reload css without reloading the page?

simple if u are using php Just append the current time at the end of the css like

<link href="css/name.css?<?php echo 
time(); ?>" rel="stylesheet">

So now everytime u reload whatever it is , the time changes and browser thinks its a different file since the last bit keeps changing.... U can do this for any file u force the browser to always refresh using whatever scripting language u want

Why doesn't os.path.join() work in this case?

do it like this, without too the extra slashes

root="/home"
os.path.join(root,"build","test","sandboxes",todaystr,"new_sandbox")

Character reading from file in Python

Ref: http://docs.python.org/howto/unicode

Reading Unicode from a file is therefore simple:

import codecs
with codecs.open('unicode.rst', encoding='utf-8') as f:
    for line in f:
        print repr(line)

It's also possible to open files in update mode, allowing both reading and writing:

with codecs.open('test', encoding='utf-8', mode='w+') as f:
    f.write(u'\u4500 blah blah blah\n')
    f.seek(0)
    print repr(f.readline()[:1])

EDIT: I'm assuming that your intended goal is just to be able to read the file properly into a string in Python. If you're trying to convert to an ASCII string from Unicode, then there's really no direct way to do so, since the Unicode characters won't necessarily exist in ASCII.

If you're trying to convert to an ASCII string, try one of the following:

  1. Replace the specific unicode chars with ASCII equivalents, if you are only looking to handle a few special cases such as this particular example

  2. Use the unicodedata module's normalize() and the string.encode() method to convert as best you can to the next closest ASCII equivalent (Ref https://web.archive.org/web/20090228203858/http://techxplorer.com/2006/07/18/converting-unicode-to-ascii-using-python):

    >>> teststr
    u'I don\xe2\x80\x98t like this'
    >>> unicodedata.normalize('NFKD', teststr).encode('ascii', 'ignore')
    'I donat like this'
    

How to embed a YouTube channel into a webpage

I quickly did this for anyone else coming onto this page:

<object width="425" height="344">
<param name="movie" value="http://www.youtube.com/v/u1zgFlCw8Aw?fs=1"</param>
<param name="allowFullScreen" value="true"></param>
<param name="allowScriptAccess" value="always"></param>
<embed src="http://www.youtube.com/v/u1zgFlCw8Aw?fs=1"
  type="application/x-shockwave-flash"
  allowfullscreen="true"
  allowscriptaccess="always"
  width="425" height="344">
</embed>
</object>

See the jsFiddle.

How do I find duplicate values in a table in Oracle?

How about:

SELECT <column>, count(*)
FROM <table>
GROUP BY <column> HAVING COUNT(*) > 1;

To answer the example above, it would look like:

SELECT job_number, count(*)
FROM jobs
GROUP BY job_number HAVING COUNT(*) > 1;

Do you need to dispose of objects and set them to null?

You never need to set objects to null in C#. The compiler and runtime will take care of figuring out when they are no longer in scope.

Yes, you should dispose of objects that implement IDisposable.

Importing a function from a class in another file?

You can use the below syntax -

from FolderName.FileName import Classname

How to import Angular Material in project?

Starting from Angular version 9:

Breaking changes:

Components can no longer be imported through "@angular/material". Use the individual secondary entry-points, such as @angular/material/button.

This means that:

import { MatInputModule, MatCardModule } from "@angular/material";

becomes:

import { MatInputModule } from "@angular/material/input";
import { MatCardModule } from "@angular/material/card";

How to loop through key/value object in Javascript?

for (var key in data) {
    alert("User " + data[key] + " is #" + key); // "User john is #234"
}

How do I call an Angular 2 pipe with multiple arguments?

Extended from : user3777549

Multi-value filter on one set of data(reference to title key only)

HTML

<div *ngFor='let item of items | filtermulti: [{title:["mr","ms"]},{first:["john"]}]' >
 Hello {{item.first}} !
</div>

filterMultiple

args.forEach(function (filterobj) {
    console.log(filterobj)
    let filterkey = Object.keys(filterobj)[0];
    let filtervalue = filterobj[filterkey];
    myobjects.forEach(function (objectToFilter) {

      if (!filtervalue.some(x=>x==objectToFilter[filterkey]) && filtervalue != "") {
        // object didn't match a filter value so remove it from array via filter
        returnobjects = returnobjects.filter(obj => obj !== objectToFilter);
      }
    })
  });

Using jQuery to build table rows from AJAX response(json)

This is working sample that I copied from my project.

_x000D_
_x000D_
 function fetchAllReceipts(documentShareId) {_x000D_
_x000D_
        console.log('http call: ' + uri + "/" + documentShareId)_x000D_
        $.ajax({_x000D_
            url: uri + "/" + documentShareId,_x000D_
            type: "GET",_x000D_
            contentType: "application/json;",_x000D_
            cache: false,_x000D_
            success: function (receipts) {_x000D_
                //console.log(receipts);_x000D_
_x000D_
                $(receipts).each(function (index, item) {_x000D_
                    console.log(item);_x000D_
                    //console.log(receipts[index]);_x000D_
_x000D_
                    $('#receipts tbody').append(_x000D_
                        '<tr><td>' + item.Firstname + ' ' + item.Lastname +_x000D_
                        '</td><td>' + item.TransactionId +_x000D_
                        '</td><td>' + item.Amount +_x000D_
                        '</td><td>' + item.Status + _x000D_
                        '</td></tr>'_x000D_
                    )_x000D_
_x000D_
                });_x000D_
_x000D_
_x000D_
            },_x000D_
            error: function (XMLHttpRequest, textStatus, errorThrown) {_x000D_
                console.log(XMLHttpRequest);_x000D_
                console.log(textStatus);_x000D_
                console.log(errorThrown);_x000D_
_x000D_
            }_x000D_
_x000D_
        });_x000D_
    }_x000D_
    _x000D_
    _x000D_
    // Sample json data coming from server_x000D_
    _x000D_
    var data =     [_x000D_
    0: {Id: "7a4c411e-9a84-45eb-9c1b-2ec502697a4d", DocumentId: "e6eb6f85-3f44-4bba-8cb0-5f2f97da17f6", DocumentShareId: "d99803ce-31d9-48a4-9d70-f99bf927a208", Firstname: "Test1", Lastname: "Test1", }_x000D_
    1: {Id: "7a4c411e-9a84-45eb-9c1b-2ec502697a4d", DocumentId: "e6eb6f85-3f44-4bba-8cb0-5f2f97da17f6", DocumentShareId: "d99803ce-31d9-48a4-9d70-f99bf927a208", Firstname: "Test 2", Lastname: "Test2", }_x000D_
];
_x000D_
  <button type="button" class="btn btn-primary" onclick='fetchAllReceipts("@share.Id")'>_x000D_
                                        RECEIPTS_x000D_
                                    </button>_x000D_
 _x000D_
 <div id="receipts" style="display:contents">_x000D_
                <table class="table table-hover">_x000D_
                    <thead>_x000D_
                        <tr>_x000D_
                            <th>Name</th>_x000D_
                            <th>Transaction</th>_x000D_
                            <th>Amount</th>_x000D_
                            <th>Status</th>_x000D_
                        </tr>_x000D_
                    </thead>_x000D_
                    <tbody>_x000D_
_x000D_
                    </tbody>_x000D_
                </table>_x000D_
         </div>_x000D_
         _x000D_
 _x000D_
    _x000D_
    _x000D_
    
_x000D_
_x000D_
_x000D_

Open URL in new window with JavaScript

Don't confuse, if you won't give any strWindowFeatures then it will open in a new tab.

window.open('https://play.google.com/store/apps/details?id=com.drishya');

Linux error while loading shared libraries: cannot open shared object file: No such file or directory

similar problem found here: https://bugzilla.redhat.com/show_bug.cgi?id=1456202 I've tried the mentioned solution and it actually works.

The solutions in the previous questions may work. But I think this is an easy way to fix it. Try to reinstall the package libwbclient in fedora:

dnf reinstall libwbclient

How to hide only the Close (x) button?

If you really want to hide it, as in "not visible", then you will probably have to create a borderless form and draw the caption components yourself. VisualStyles library has the Windows Elements available. You would also have to add back in the functionality of re-sizing the form or moving the form by grabbing the caption bar. Not to mention the system menu in the corner.

In most cases, it's hard to justify having the "close" button not available, especially when you want a modal form with minimizing capabilities. Minimizing a modal form really makes no sense.

Why is HttpContext.Current null?

Clearly HttpContext.Current is not null only if you access it in a thread that handles incoming requests. That's why it works "when i use this code in another class of a page".

It won't work in the scheduling related class because relevant code is not executed on a valid thread, but a background thread, which has no HTTP context associated with.

Overall, don't use Application["Setting"] to store global stuffs, as they are not global as you discovered.

If you need to pass certain information down to business logic layer, pass as arguments to the related methods. Don't let your business logic layer access things like HttpContext or Application["Settings"], as that violates the principles of isolation and decoupling.

Update: Due to the introduction of async/await it is more often that such issues happen, so you might consider the following tip,

In general, you should only call HttpContext.Current in only a few scenarios (within an HTTP module for example). In all other cases, you should use

instead of HttpContext.Current.

Enabling SSL with XAMPP

I finally got this to work on my own hosted xampp windows 10 server web site. I.e. padlocks came up as ssl. I am using xampp version from November 2020.

  1. Went to certbot.eff.org. Selected from their home page software [apache] and system [windows]. Then downloaded and installed certbot software found at the next page into my C drive.

  2. Then from command line [cmd in Windows Start and then before you open cmd right click to run cmd as admin] I enhtered the command from Certbot page above. I.e. navigated to system32-- C:\WINDOWS\system32> certbot certonly --standalone

  3. Then followed the prompts and enteredmy domain name. This created certs as cert1.pem and key1.pem in C:\Certbot yourwebsitedomain folder. the cmd windows tells you where these are.

  4. Then took these and changed their names from cert1.pem to my domainname or shorter+cert.pem and same for domainname or shorter+key.key. Copied these into C:\xampp\apache\ssl.crt and ssl.key folders respectively.

  5. Then for G:\xampp\apache\conf\extra\httpd-vhosts entered the following:

<VirtualHost *:443>
    DocumentRoot "G:/xampp/htdocs/yourwebsitedomainname.hopto.org/public/" ###NB My document root is public.  Yours may not be.  Or could have an index.php page before /public###
    ServerName yourwebsitedomainnamee.hopto.org 
    <Directory G:/xampp/htdocs/yourwebsitedomainname.hopto.org>
        Options Indexes FollowSymLinks Includes ExecCGI
        AllowOverride All
        Require all granted
    </Directory>
    ErrorLog "G:/xampp/apache/logs/error.log"
    CustomLog "G:/xampp/apache/logs/access.log" common
    SSLEngine on
SSLCertificateFile "G:\xampp\apache\conf\ssl.crt\abscert.pem"
SSLCertificateKeyFile "G:\xampp\apache\conf\ssl.key\abskey.pem"
</VirtualHost>  
     
  1. Then navigated to G:\xampp\apache\conf\extra\httpd-ssl.conf and did as was advised above. I missed this important step for days until I read this post. Thank you! I.e. entered
<VirtualHost _default_:443>
DocumentRoot "G:/xampp/htdocs/yourwebsitedomainnamee.hopto.org/public/"
###NB My document root is public.  Yours may not be.  Or could have an index.php page before /public###
SSLEngine on
SSLCertificateFile "conf/ssl.crt/abscert.pem"
SSLCertificateKeyFile "conf/ssl.key/abskey.pem"
CustomLog "G:/xampp/apache/logs/ssl_request.log" \
          "%t %h %{SSL_PROTOCOL}x %{SSL_CIPHER}x \"%r\" %b"
</VirtualHost>  

Note1. I used www.noip.com to register the domain name. Note2. Rather then try to get them to give me a ssl certificate, as I could not get it to work, the above worked instead. Note3 I use the noip DUC software to keep my personally hosted web site in sync with noip. Note4. Very important to stop and start xampp server after each change you make in xampp. If xampp fails for some reason instead of starting the xampp consol try the start xampp as this will give you problems you can bug fix. Copy these quickly and paste into note.txt.

Execute function after Ajax call is complete

Append .done() to your ajax request.

$.ajax({
  url: "test.html",
  context: document.body
}).done(function() { //use this
  alert("DONE!");
});

See the JQuery Doc for .done()

bash "if [ false ];" returns true instead of false -- why?

I found that I can do some basic logic by running something like:

A=true
B=true
if ($A && $B); then
    C=true
else
    C=false
fi
echo $C

Working with INTERVAL and CURDATE in MySQL

You need DATE_ADD/DATE_SUB:

AND v.date > (DATE_SUB(CURDATE(), INTERVAL 2 MONTH))
AND v.date < (DATE_SUB(CURDATE(), INTERVAL 1 MONTH))

should work.

How should I load files into my Java application?

public byte[] loadBinaryFile (String name) {
    try {

        DataInputStream dis = new DataInputStream(new FileInputStream(name));
        byte[] theBytes = new byte[dis.available()];
        dis.read(theBytes, 0, dis.available());
        dis.close();
        return theBytes;
    } catch (IOException ex) {
    }
    return null;
} // ()

How to convert an XML file to nice pandas dataframe?

You can also convert by creating a dictionary of elements and then directly converting to a data frame:

import xml.etree.ElementTree as ET
import pandas as pd

# Contents of test.xml
# <?xml version="1.0" encoding="utf-8"?> <tags>   <row Id="1" TagName="bayesian" Count="4699" ExcerptPostId="20258" WikiPostId="20257" />   <row Id="2" TagName="prior" Count="598" ExcerptPostId="62158" WikiPostId="62157" />   <row Id="3" TagName="elicitation" Count="10" />   <row Id="5" TagName="open-source" Count="16" /> </tags>

root = ET.parse('test.xml').getroot()

tags = {"tags":[]}
for elem in root:
    tag = {}
    tag["Id"] = elem.attrib['Id']
    tag["TagName"] = elem.attrib['TagName']
    tag["Count"] = elem.attrib['Count']
    tags["tags"]. append(tag)

df_users = pd.DataFrame(tags["tags"])
df_users.head()

Best way to convert text files between character sets?

Stand-alone utility approach

iconv -f ISO-8859-1 -t UTF-8 in.txt > out.txt
-f ENCODING  the encoding of the input
-t ENCODING  the encoding of the output

You don't have to specify either of these arguments. They will default to your current locale, which is usually UTF-8.

How do I associate file types with an iPhone application?

BIG WARNING: Make ONE HUNDRED PERCENT sure that your extension is not already tied to some mime type.

We used the extension '.icz' for our custom files for, basically, ever, and Safari just never would let you open them saying "Safari cannot open this file." no matter what we did or tried with the UT stuff above.

Eventually I realized that there are some UT* C functions you can use to explore various things, and while .icz gives the right answer (our app):

In app did load at top, just do this...

NSString * UTI = (NSString *)UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, 
                                                                   (CFStringRef)@"icz", 
                                                                   NULL);
CFURLRef ur =UTTypeCopyDeclaringBundleURL(UTI);

and put break after that line and see what UTI and ur are -- in our case, it was our identifier as we wanted), and the bundle url (ur) was pointing to our app's folder.

But the MIME type that Dropbox gives us back for our link, which you can check by doing e.g.

$ curl -D headers THEURLGOESHERE > /dev/null
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100 27393  100 27393    0     0  24983      0  0:00:01  0:00:01 --:--:-- 28926
$ cat headers
HTTP/1.1 200 OK
accept-ranges: bytes
cache-control: max-age=0
content-disposition: attachment; filename="123.icz"
Content-Type: text/calendar
Date: Fri, 24 May 2013 17:41:28 GMT
etag: 872926d
pragma: public
Server: nginx
x-dropbox-request-id: 13bd327248d90fde
X-RequestId: bf9adc56934eff0bfb68a01d526eba1f
x-server-response-time: 379
Content-Length: 27393
Connection: keep-alive

The Content-Type is what we want. Dropbox claims this is a text/calendar entry. Great. But in my case, I've ALREADY TRIED PUTTING text/calendar into my app's mime types, and it still doesn't work. Instead, when I try to get the UTI and bundle url for the text/calendar mimetype,

NSString * UTI = (NSString *)UTTypeCreatePreferredIdentifierForTag(kUTTagClassMIMEType,
                                                                   (CFStringRef)@"text/calendar", 
                                                                   NULL);

CFURLRef ur =UTTypeCopyDeclaringBundleURL(UTI);

I see "com.apple.ical.ics" as the UTI and ".../MobileCoreTypes.bundle/" as the bundle URL. Not our app, but Apple. So I try putting com.apple.ical.ics into the LSItemContentTypes alongside my own, and into UTConformsTo in the export, but no go.

So basically, if Apple thinks they want to at some point handle some form of file type (that could be created 10 years after your app is live, mind you), you will have to change extension cause they'll simply not let you handle the file type.

What is the best way to delete a component with CLI

This is not supported by Angular CLI and they are in no mood to include it any time soon.

Here is the link to the actual created issue - https://github.com/angular/angular-cli/issues/1776

And a screenshot of the solution from the officials - enter image description here

How to prevent form resubmission when page is refreshed (F5 / CTRL+R)

Just redirect it to the same page after making the use of form data, and it works. I have tried it.

header('location:yourpage.php');

Adding items to end of linked list

The above programs might give you NullPointerException. This is an easier way to add an element to the end of linkedList.

public class LinkedList {
    Node head;

    public static class Node{
        int data;
        Node next;

        Node(int item){
            data = item;
            next = null;
        }
    }
    public static void main(String args[]){
        LinkedList ll = new LinkedList();
        ll.head = new Node(1);
        Node second = new Node(2);
        Node third = new Node(3);
        Node fourth = new Node(4);

        ll.head.next = second;
        second.next = third;
        third.next = fourth;
        fourth.next = null;

        ll.printList();
        System.out.println("Add element 100 to the last");
        ll.addLast(100);
        ll.printList();
    }
    public void printList(){
        Node t = head;
        while(n != null){
            System.out.println(t.data);
            t = t.next;
        }

    }

    public void addLast(int item){
        Node new_item = new Node(item);
        if(head == null){
            head = new_item;
            return;
        }
        new_item.next = null;

        Node last = head;
        Node temp = null;
        while(last != null){
            if(last != null)
                temp = last;
            last = last.next;
        }   

        temp.next = new_item;   
        return;
    }
}

How to conditional format based on multiple specific text in Excel

Suppose your "Don't Check" list is on Sheet2 in cells A1:A100, say, and your current client IDs are in Sheet1 in Column A.

What you would do is:

  1. Select the whole data table you want conditionally formatted in Sheet1
  2. Click Conditional Formatting > New Rule > Use a Formula to determine which cells to format
  3. In the formula bar, type in =ISNUMBER(MATCH($A1,Sheet2!$A$1:$A$100,0)) and select how you want those rows formatted

And that should do the trick.

Finding and removing non ascii characters from an Oracle Varchar2

I found the answer here:

http://www.squaredba.com/remove-non-ascii-characters-from-a-column-255.html

CREATE OR REPLACE FUNCTION O1DW.RECTIFY_NON_ASCII(INPUT_STR IN VARCHAR2)
RETURN VARCHAR2
IS
str VARCHAR2(2000);
act number :=0;
cnt number :=0;
askey number :=0;
OUTPUT_STR VARCHAR2(2000);
begin
str:=’^'||TO_CHAR(INPUT_STR)||’^';
cnt:=length(str);
for i in 1 .. cnt loop
askey :=0;
select ascii(substr(str,i,1)) into askey
from dual;
if askey < 32 or askey >=127 then
str :=’^'||REPLACE(str, CHR(askey),”);
end if;
end loop;
OUTPUT_STR := trim(ltrim(rtrim(trim(str),’^'),’^'));
RETURN (OUTPUT_STR);
end;
/

Then run this to update your data

update o1dw.rate_ipselect_p_20110505
set NCANI = RECTIFY_NON_ASCII(NCANI);

What is getattr() exactly and how do I use it?

Quite frequently when I am creating an XML file from data stored in a class I would frequently receive errors if the attribute didn't exist or was of type None. In this case, my issue wasn't not knowing what the attribute name was, as stated in your question, but rather was data ever stored in that attribute.

class Pet:
    def __init__(self):
        self.hair = None
        self.color = None

If I used hasattr to do this, it would return True even if the attribute value was of type None and this would cause my ElementTree set command to fail.

hasattr(temp, 'hair')
>>True

If the attribute value was of type None, getattr would also return it which would cause my ElementTree set command to fail.

c = getattr(temp, 'hair')
type(c)
>> NoneType

I use the following method to take care of these cases now:

def getRealAttr(class_obj, class_attr, default = ''):
    temp = getattr(class_obj, class_attr, default)
    if temp is None:
        temp = default
    elif type(temp) != str:
        temp = str(temp)
    return temp

This is when and how I use getattr.

Iterate through pairs of items in a Python list

You can zip the list with itself sans the first element:

a = [5, 7, 11, 4, 5]

for previous, current in zip(a, a[1:]):
    print(previous, current)

This works even if your list has no elements or only 1 element (in which case zip returns an empty iterable and the code in the for loop never executes). It doesn't work on generators, only sequences (tuple, list, str, etc).

How do I check if a variable is of a certain type (compare two types) in C?

Getting the type of a variable is, as of now, possible in C11 with the _Generic generic selection. It works at compile-time.

The syntax is a bit like that for switch. Here's a sample (from this answer):

    #define typename(x) _Generic((x),                                                 \
            _Bool: "_Bool",                  unsigned char: "unsigned char",          \
             char: "char",                     signed char: "signed char",            \
        short int: "short int",         unsigned short int: "unsigned short int",     \
              int: "int",                     unsigned int: "unsigned int",           \
         long int: "long int",           unsigned long int: "unsigned long int",      \
    long long int: "long long int", unsigned long long int: "unsigned long long int", \
            float: "float",                         double: "double",                 \
      long double: "long double",                   char *: "pointer to char",        \
           void *: "pointer to void",                int *: "pointer to int",         \
          default: "other")

To actually use it for compile-time manual type checking, you can define an enum with all of the types you expect, something like this:

    enum t_typename {
        TYPENAME_BOOL,
        TYPENAME_UNSIGNED_CHAR,
        TYPENAME_CHAR,
        TYPENAME_SIGNED_CHAR,
        TYPENAME_SHORT_INT,
        TYPENAME_UNSIGNED_CHORT_INT,
        TYPENAME_INT,
        /* ... */
        TYPENAME_POINTER_TO_INT,
        TYPENAME_OTHER
    };

And then use _Generic to match types to this enum:

    #define typename(x) _Generic((x),                                                       \
            _Bool: TYPENAME_BOOL,           unsigned char: TYPENAME_UNSIGNED_CHAR,          \
             char: TYPENAME_CHAR,             signed char: TYPENAME_SIGNED_CHAR,            \
        short int: TYPENAME_SHORT_INT, unsigned short int: TYPENAME_UNSIGNED_SHORT_INT,     \
              int: TYPENAME_INT,                     \
        /* ... */                                    \
            int *: TYPENAME_POINTER_TO_INT,          \
          default: TYPENAME_OTHER)

How to update a pull request from forked repo?

I did it using below steps:

  1. git reset --hard <commit key of the pull request>
  2. Did my changes in code I wanted to do
  3. git add
  4. git commit --amend
  5. git push -f origin <name of the remote branch of pull request>

How to mock void methods with Mockito

Take a look at the Mockito API docs. As the linked document mentions (Point # 12) you can use any of the doThrow(),doAnswer(),doNothing(),doReturn() family of methods from Mockito framework to mock void methods.

For example,

Mockito.doThrow(new Exception()).when(instance).methodName();

or if you want to combine it with follow-up behavior,

Mockito.doThrow(new Exception()).doNothing().when(instance).methodName();

Presuming that you are looking at mocking the setter setState(String s) in the class World below is the code uses doAnswer method to mock the setState.

World mockWorld = mock(World.class); 
doAnswer(new Answer<Void>() {
    public Void answer(InvocationOnMock invocation) {
      Object[] args = invocation.getArguments();
      System.out.println("called with arguments: " + Arrays.toString(args));
      return null;
    }
}).when(mockWorld).setState(anyString());

Why do symbols like apostrophes and hyphens get replaced with black diamonds on my website?

It's an encoding problem. You have to set the correct encoding in the HTML head via meta tag:

<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">

Replace "ISO-8859-1" with whatever your encoding is (e.g. 'UTF-8'). You must find out what encoding your HTML files are. If you're on an Unix system, just type file file.html and it should show you the encoding. If this is not possible, you should be able to find out somewhere what encoding your editor produces.

Check status of one port on remote host

Press Windows + R type cmd and Enter

In command prompt type

telnet "machine name/ip" "port number"

If port is not open, this message will display:

"Connecting To "machine name"...Could not open connection to the host, on port "port number":

Otherwise you will be take in to opened port (empty screen will display)

$_POST Array from html form

You should get the array like in $_POST['id']. So you should be able to do this:

foreach ($_POST['id'] as $key => $value) {
    echo $value . "<br />";
}

Input names should be same:

<input name='id[]' type='checkbox' value='1'>
<input name='id[]' type='checkbox' value='2'>
...

Regex using javascript to return just numbers

For number with decimal fraction and minus sign, I use this snippet:

_x000D_
_x000D_
const NUMERIC_REGEXP = /[-]{0,1}[\d]*[.]{0,1}[\d]+/g;

const numbers = '2.2px 3.1px 4px -7.6px obj.key'.match(NUMERIC_REGEXP)

console.log(numbers); // ["2.2", "3.1", "4", "-7.6"]
_x000D_
_x000D_
_x000D_

Update: - 7/9/2018

Found a tool which allows you to edit regular expression visually: JavaScript Regular Expression Parser & Visualizer.

Update:

Here's another one with which you can even debugger regexp: Online regex tester and debugger.

Update:

Another one: RegExr.

Update:

Regexper and Regex Pal.

How to fix corrupt HDFS FIles

the solution here worked for me : https://community.hortonworks.com/articles/4427/fix-under-replicated-blocks-in-hdfs-manually.html

su - <$hdfs_user>

bash-4.1$ hdfs fsck / | grep 'Under replicated' | awk -F':' '{print $1}' >> /tmp/under_replicated_files 

-bash-4.1$ for hdfsfile in `cat /tmp/under_replicated_files`; do echo "Fixing $hdfsfile :" ;  hadoop fs -setrep 3 $hdfsfile; done

How to parse date string to Date?

String target = "27-09-1991 20:29:30";
DateFormat df = new SimpleDateFormat("dd MM yyyy HH:mm:ss");
Date result =  df.parse(target);
System.out.println(result); 

This works fine?

Use 'class' or 'typename' for template parameters?

As far as I know, it doesn't matter which one you use. They're equivalent in the eyes of the compiler. Use whichever one you prefer. I normally use class.

ReferenceError: event is not defined error in Firefox

It is because you forgot to pass in event into the click function:

$('.menuOption').on('click', function (e) { // <-- the "e" for event

    e.preventDefault(); // now it'll work

    var categories = $(this).attr('rel');
    $('.pages').hide();
    $(categories).fadeIn();
});

On a side note, e is more commonly used as opposed to the word event since Event is a global variable in most browsers.

C# - Multiple generic types in one list

public abstract class Metadata
{
}

// extend abstract Metadata class
public class Metadata<DataType> : Metadata where DataType : struct
{
    private DataType mDataType;
}

How to get a subset of a javascript object's properties

  1. convert arguments to array

  2. use Array.forEach() to pick the property

    Object.prototype.pick = function(...args) {
       var obj = {};
       args.forEach(k => obj[k] = this[k])
       return obj
    }
    var a = {0:"a",1:"b",2:"c"}
    var b = a.pick('1','2')  //output will be {1: "b", 2: "c"}
    

Hibernate Union alternatives

You could use id in (select id from ...) or id in (select id from ...)

e.g. instead of non-working

from Person p where p.name="Joe"
union
from Person p join p.children c where c.name="Joe"

you could do

from Person p 
  where p.id in (select p1.id from Person p1 where p1.name="Joe") 
    or p.id in (select p2.id from Person p2 join p2.children c where c.name="Joe");

At least using MySQL, you will run into performance problems with it later, though. It's sometimes easier to do a poor man's join on two queries instead:

// use set for uniqueness
Set<Person> people = new HashSet<Person>((List<Person>) query1.list());
people.addAll((List<Person>) query2.list());
return new ArrayList<Person>(people);

It's often better to do two simple queries than one complex one.

EDIT:

to give an example, here is the EXPLAIN output of the resulting MySQL query from the subselect solution:

mysql> explain 
  select p.* from PERSON p 
    where p.id in (select p1.id from PERSON p1 where p1.name = "Joe") 
      or p.id in (select p2.id from PERSON p2 
        join CHILDREN c on p2.id = c.parent where c.name="Joe") \G
*************************** 1. row ***************************
           id: 1
  select_type: PRIMARY
        table: a
         type: ALL
possible_keys: NULL
          key: NULL
      key_len: NULL
          ref: NULL
         rows: 247554
        Extra: Using where
*************************** 2. row ***************************
           id: 3
  select_type: DEPENDENT SUBQUERY
        table: NULL
         type: NULL
possible_keys: NULL
          key: NULL
      key_len: NULL
          ref: NULL
         rows: NULL
        Extra: Impossible WHERE noticed after reading const tables
*************************** 3. row ***************************
           id: 2
  select_type: DEPENDENT SUBQUERY
        table: a1
         type: unique_subquery
possible_keys: PRIMARY,name,sortname
          key: PRIMARY
      key_len: 4
          ref: func
         rows: 1
        Extra: Using where
3 rows in set (0.00 sec)

Most importantly, 1. row doesn't use any index and considers 200k+ rows. Bad! Execution of this query took 0.7s wheres both subqueries are in the milliseconds.

How to install mongoDB on windows?

You might want to check https://github.com/Thor1Khan/mongo.git it uses a minimal workaround the 32 bit atomic operations on 64 bits operands (could use assembly but it doesn't seem to be mandatory here) Only digital bugs were harmed before committing

How do I left align these Bootstrap form items?

Just my two cents. If you are using Bootstrap 3 then I would just add an extra style into your own site's stylesheet which controls the text-left style of the control-label.

If you were to add text-left to the label, by default there is another style which overrides this .form-horizontal .control-label. So if you add:

.form-horizontal .control-label.text-left{
    text-align: left;
}

Then the built in text-left style is applied to the label correctly.

File name without extension name VBA

You could always use Replace() since you're performing this on the workbook's Name, which will almost certainly end with .xlsm by virtue of using VBA.

Using ActiveWorkbook per your example:

Replace(Application.ActiveWorkbook.Name, ".xlsm", "")

Using ThisWorkbook:

Replace(Application.ThisWorkbook.Name, ".xlsm", "")