Programs & Examples On #Cheetah

Cheetah is an Open Source Python based Templating Framework.

Hibernate Auto Increment ID

@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private int id;

and you leave it null (0) when persisting. (null if you use the Integer / Long wrappers)

In some cases the AUTO strategy is resolved to SEQUENCE rathen than to IDENTITY or TABLE, so you might want to manually set it to IDENTITY or TABLE (depending on the underlying database).

It seems SEQUENCE + specifying the sequence name worked for you.

How to configure Chrome's Java plugin so it uses an existing JDK in the machine

I'm on Windows 7 64 bit and couldn't understand if I can manually enable JRE8 64 bit for Chrome. Turned out that my problem was that Java plugin DLL is 64 bit which wouldn't work in 32 bit Chrome. Therefore you need to install x86 version of JRE. Below are Windows registry settings you need to create

Windows Registry Editor Version 5.00

[HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\MozillaPlugins\@java.com/JavaPlugin,version=11.0.2]
"Description"="Oracle® Next Generation Java™ Plug-In"
"GeckoVersion"="1.9"
"Path"="C:\\Program Files (x86)\\Java\\jre8\\bin\\plugin2\\npjp2.dll"
"ProductName"="Oracle® Java™ Plug-In"
"Vendor"="Oracle Corp."
"Version"="1.8.0"

[HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\MozillaPlugins\@java.com/JavaPlugin,version=11.0.2\MimeTypes]

[HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\MozillaPlugins\@java.com/JavaPlugin,version=11.0.2\MimeTypes\application/x-java-applet]
"Description"="Java™ Applet"

[HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\MozillaPlugins\@java.com/JavaPlugin,version=11.0.2\MimeTypes\application/x-java-applet;jpi-version=1.8.0]
"Description"="Java™ Applet"

[HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\MozillaPlugins\@java.com/JavaPlugin,version=11.0.2\MimeTypes\application/x-java-applet;version=1.1]
"Description"="Java™ Applet"

[HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\MozillaPlugins\@java.com/JavaPlugin,version=11.0.2\MimeTypes\application/x-java-applet;version=1.1.1]
"Description"="Java™ Applet"

[HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\MozillaPlugins\@java.com/JavaPlugin,version=11.0.2\MimeTypes\application/x-java-applet;version=1.1.2]
"Description"="Java™ Applet"

[HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\MozillaPlugins\@java.com/JavaPlugin,version=11.0.2\MimeTypes\application/x-java-applet;version=1.1.3]
"Description"="Java™ Applet"

[HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\MozillaPlugins\@java.com/JavaPlugin,version=11.0.2\MimeTypes\application/x-java-applet;version=1.2]
"Description"="Java™ Applet"

[HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\MozillaPlugins\@java.com/JavaPlugin,version=11.0.2\MimeTypes\application/x-java-applet;version=1.2.1]
"Description"="Java™ Applet"

[HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\MozillaPlugins\@java.com/JavaPlugin,version=11.0.2\MimeTypes\application/x-java-applet;version=1.3]
"Description"="Java™ Applet"

[HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\MozillaPlugins\@java.com/JavaPlugin,version=11.0.2\MimeTypes\application/x-java-applet;version=1.3.1]
"Description"="Java™ Applet"

[HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\MozillaPlugins\@java.com/JavaPlugin,version=11.0.2\MimeTypes\application/x-java-applet;version=1.4]
"Description"="Java™ Applet"

[HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\MozillaPlugins\@java.com/JavaPlugin,version=11.0.2\MimeTypes\application/x-java-applet;version=1.4.1]
"Description"="Java™ Applet"

[HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\MozillaPlugins\@java.com/JavaPlugin,version=11.0.2\MimeTypes\application/x-java-applet;version=1.4.2]
"Description"="Java™ Applet"

[HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\MozillaPlugins\@java.com/JavaPlugin,version=11.0.2\MimeTypes\application/x-java-applet;version=1.5]
"Description"="Java™ Applet"

[HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\MozillaPlugins\@java.com/JavaPlugin,version=11.0.2\MimeTypes\application/x-java-applet;version=1.6]
"Description"="Java™ Applet"

[HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\MozillaPlugins\@java.com/JavaPlugin,version=11.0.2\MimeTypes\application/x-java-applet;version=1.7]
"Description"="Java™ Applet"

[HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\MozillaPlugins\@java.com/JavaPlugin,version=11.0.2\MimeTypes\application/x-java-applet;version=1.8]
"Description"="Java™ Applet"

[HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\MozillaPlugins\@java.com/JavaPlugin,version=11.0.2\MimeTypes\application/x-java-vm]
"Description"="Java™ Virtual Machine"

[HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\MozillaPlugins\@java.com/JavaPlugin,version=11.0.2\MimeTypes\application/x-java-vm-npruntime]
"Description"="Java™ Applet"

[HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\MozillaPlugins\@java.com/JavaPlugin]
"Description"="Oracle® Next Generation Java™ Plug-In"
"GeckoVersion"="1.9"
"ProductName"="Oracle® Java™ Plug-In"
"Vendor"="Oracle Corp."
"Version"="160_29"
"Path"="C:\\Program Files\\Java\\jre8\\bin\\plugin2\\npjp2.dll"

How do I measure the execution time of JavaScript code with callbacks?

Use the Node.js console.time() and console.timeEnd():

var i;
console.time("dbsave");

for(i = 1; i < LIMIT; i++){
    db.users.save({id : i, name : "MongoUser [" + i + "]"}, end);
}

end = function(err, saved) {
    console.log(( err || !saved )?"Error":"Saved");
    if(--i === 1){console.timeEnd("dbsave");}
};

How do you declare an object array in Java?

vehicle[] car = new vehicle[N];

How can I move a tag on a git branch to a different commit?

One other way:

Move tag in remote repo.(Replace HEAD with any other if needed.)

$ git push --force origin HEAD:refs/tags/v0.0.1.2

Fetch changes back.

$ git fetch --tags

What is the difference between <html lang="en"> and <html lang="en-US">?

This should help : http://www.w3.org/International/articles/language-tags/

The golden rule when creating language tags is to keep the tag as short as possible. Avoid region, script or other subtags except where they add useful distinguishing information. For instance, use ja for Japanese and not ja-JP, unless there is a particular reason that you need to say that this is Japanese as spoken in Japan, rather than elsewhere.

The list below shows the various types of subtag that are available. We will work our way through these and how they are used in the sections that follow.

language-extlang-script-region-variant-extension-privateuse

How to define hash tables in Bash?

Prior to bash 4 there is no good way to use associative arrays in bash. Your best bet is to use an interpreted language that actually has support for such things, like awk. On the other hand, bash 4 does support them.

As for less good ways in bash 3, here is a reference than might help: http://mywiki.wooledge.org/BashFAQ/006

WAMP 403 Forbidden message on Windows 7

The access to your Apache server is forbidden from addresses other than 127.0.0.1 in httpd.conf (Apache's config file) :

<Directory "c:/wamp/www/">
    Options Indexes FollowSymLinks
    AllowOverride all
    Order Deny,Allow
    Deny from all
    Allow from 127.0.0.1
</Directory>

The same goes for your PHPMyAdmin access, the config file is phpmyadmin.conf :

<Directory "c:/wamp/apps/phpmyadmin3.4.5/">
    Options Indexes FollowSymLinks MultiViews
    AllowOverride all
        Order Deny,Allow
        Deny from all
        Allow from 127.0.0.1
</Directory>

You can set them to allow connections from all IP addresses like follows :

AllowOverride All
Order allow,deny
Allow from all

How to declare variable and use it in the same Oracle SQL script?

In Toad I use this works:

declare 
    num number;
begin 
    ---- use 'select into' works 
    --select 123 into num from dual;

    ---- also can use :=
    num := 123;
    dbms_output.Put_line(num);
end;

Then the value will be print to DBMS Output Window.

Reference to here and here2.

Removing cordova plugins from the project

From the terminal (osx) I usually use

cordova plugin -l | xargs cordova plugins rm

Pipe, pipe everything!

To expand a bit: this command will loop through the results of cordova plugin -l and feed it to cordova plugins rm.

xargs is one of those commands that you wonder why you didn't know about before. See this tut.

How to sum the values of one column of a dataframe in spark/scala

Not sure this was around when this question was asked but:

df.describe().show("columnName")

gives mean, count, stdtev stats on a column. I think it returns on all columns if you just do .show()

installation app blocked by play protect

There are three options to get rid of this warning:

  1. You need to disable Play Protect in Play Store -> Play Protect -> Settings Icon -> Scan Device for security threats
  2. Publish app at Google Play Store
  3. Submit an Appeal to the Play Protect.

How to include "zero" / "0" results in COUNT aggregate?

To change even less on your original query, you can turn your join into a RIGHT join

SELECT person.person_id, COUNT(appointment.person_id) AS "number_of_appointments"
FROM appointment
RIGHT JOIN person ON person.person_id = appointment.person_id
GROUP BY person.person_id;

This just builds on the selected answer, but as the outer join is in the RIGHT direction, only one word needs to be added and less changes. - Just remember that it's there and can sometimes make queries more readable and require less rebuilding.

BeautifulSoup getting href

You can use find_all in the following way to find every a element that has an href attribute, and print each one:

from BeautifulSoup import BeautifulSoup

html = '''<a href="some_url">next</a>
<span class="class"><a href="another_url">later</a></span>'''

soup = BeautifulSoup(html)

for a in soup.find_all('a', href=True):
    print "Found the URL:", a['href']

The output would be:

Found the URL: some_url
Found the URL: another_url

Note that if you're using an older version of BeautifulSoup (before version 4) the name of this method is findAll. In version 4, BeautifulSoup's method names were changed to be PEP 8 compliant, so you should use find_all instead.


If you want all tags with an href, you can omit the name parameter:

href_tags = soup.find_all(href=True)

Git On Custom SSH Port

(Update: a few years later Google and Qwant "airlines" still send me here when searching for "git non-default ssh port") A probably better way in newer git versions is to use the GIT_SSH_COMMAND ENV.VAR like:

GIT_SSH_COMMAND="ssh -oPort=1234 -i ~/.ssh/myPrivate_rsa.key" \ git clone myuser@myGitRemoteServer:/my/remote/git_repo/path

This has the added advantage of allowing any other ssh suitable option (port, priv.key, IPv6, PKCS#11 device, ...).

Python 3 Float Decimal Points/Precision

The comments state the objective is to print to 2 decimal places.

There's a simple answer for Python 3:

>>> num=3.65
>>> "The number is {:.2f}".format(num)
'The number is 3.65'

or equivalently with f-strings (Python 3.6+):

>>> num = 3.65
>>> f"The number is {num:.2f}"
'The number is 3.65'

As always, the float value is an approximation:

>>> "{}".format(num)
'3.65'
>>> "{:.10f}".format(num)
'3.6500000000'
>>> "{:.20f}".format(num)
'3.64999999999999991118'

I think most use cases will want to work with floats and then only print to a specific precision.

Those that want the numbers themselves to be stored to exactly 2 decimal digits of precision, I suggest use the decimal type. More reading on floating point precision for those that are interested.

Include in SELECT a column that isn't actually in the database

You may want to use:

SELECT Name, 'Unpaid' AS Status FROM table;

The SELECT clause syntax, as defined in MSDN: SELECT Clause (Transact-SQL), is as follows:

SELECT [ ALL | DISTINCT ]
[ TOP ( expression ) [ PERCENT ] [ WITH TIES ] ] 
<select_list> 

Where the expression can be a constant, function, any combination of column names, constants, and functions connected by an operator or operators, or a subquery.

Razor View Engine : An expression tree may not contain a dynamic operation

In this link explain about @model, see a excerpt:

@model (lowercase "m") is a reserved keyword in Razor views to declare the model type at the top of your view. You have put the namespace too, e.g.: @model MyNamespace.Models.MyModel

Later in the file, you can reference the attribute you want with @Model.Attribute (uppercase "M").

How to implement a secure REST API with node.js

I just finished a sample app that does this in a pretty basic, but clear way. It uses mongoose with mongodb to store users and passport for auth management.

https://github.com/Khelldar/Angular-Express-Train-Seed

@Value annotation type casting to Integer from String

I had the exact same situation. It was caused by not having a PropertySourcesPlaceholderConfigurer in the Spring context, which resolves values against the @Value annotation inside of classes.

Include a property placeholder to solve the problem, no need to use Spring expressions for integers (the property file does not have to exist if you use ignore-resource-not-found="true"):

<context:property-placeholder location="/path/to/my/app.properties"
    ignore-resource-not-found="true" />

PHP memcached Fatal error: Class 'Memcache' not found

There are two extensions for memcached in PHP, "memcache" and "memcached".

It looks like you're trying to use one ("memcache"), but the other is installed ("memcached").

HowTo Generate List of SQL Server Jobs and their owners

It's better to use SUSER_SNAME() since when there is no corresponding login on the server the join to syslogins will not match

SELECT  s.name ,
        SUSER_SNAME(s.owner_sid) AS owner
FROM    msdb..sysjobs s 
ORDER BY name

Apply a function to every row of a matrix or a data frame

You simply use the apply() function:

R> M <- matrix(1:6, nrow=3, byrow=TRUE)
R> M
     [,1] [,2]
[1,]    1    2
[2,]    3    4
[3,]    5    6
R> apply(M, 1, function(x) 2*x[1]+x[2])
[1]  4 10 16
R> 

This takes a matrix and applies a (silly) function to each row. You pass extra arguments to the function as fourth, fifth, ... arguments to apply().

3D Plotting from X, Y, Z Data, Excel or other Tools

You really can't display 3 columns of data as a 'surface'. Only having one column of 'Z' data will give you a line in 3 dimensional space, not a surface (Or in the case of your data, 3 separate lines). For Excel to be able to work with this data, it needs to be formatted as shown below:

      13    21   29      37    45   
1000  75.2                              
1000       79.21                            
1000             80.02                      
5000             87.9                   
5000                    88.54               
5000                           88.56            
10000            90.11      
10000                   90.79   
10000                          90.87

Then, to get an actual surface, you would need to fill in all the missing cells with the appropriate Z-values. If you don't have those, then you are better off showing this as 3 separate 2D lines, because there isn't enough data for a surface.

The best 3D representation that Excel will give you of the above data is pretty confusing:

enter image description here

Representing this limited dataset as 2D data might be a better choice:

enter image description here

As a note for future reference, these types of questions usually do a little better on superuser.com.

Disabling tab focus on form elements

A simple way is to put tabindex="-1" in the field(s) you don't want to be tabbed to. Eg

<input type="text" tabindex="-1" name="f1">

Maven won't run my Project : Failed to execute goal org.codehaus.mojo:exec-maven-plugin:1.2.1:exec

Maven needs to be able to access various Maven repositories in order to download artifacts to the local repository. If your local system is accessing the Internet through a proxy host, you might need to explicitly specify the proxy settings for Maven by editing the Maven settings.xml file. Maven builds ignore the IDE proxy settings that are set in the Options window. For many common cases, just passing -Djava.net.useSystemProxies=true to Maven should suffice to download artifacts through the system's configured proxy. NetBeans 7.1 will offer to configure this flag for you if it detects a possible proxy problem. https://netbeans.org/bugzilla/show_bug.cgi?id=194916 has discussion.

How to add a "confirm delete" option in ASP.Net Gridview?

This code is working fine for me.

jQuery("a").filter(function () {
        return this.innerHTML.indexOf("Delete") == 0;
        }).click(function () { return confirm("Are you sure you want to delete this record?"); 
});

How can I declare enums using java

public enum NewEnum {
   ONE("test"),
   TWO("test");

   private String s;

   private NewEnum(String s) {
      this.s = s);
   }

    public String getS() {
        return this.s;
    }
}

How are POST and GET variables handled in Python?

It somewhat depends on what you use as a CGI framework, but they are available in dictionaries accessible to the program. I'd point you to the docs, but I'm not getting through to python.org right now. But this note on mail.python.org will give you a first pointer. Look at the CGI and URLLIB Python libs for more.

Update

Okay, that link busted. Here's the basic wsgi ref

WCF Error - Could not find default endpoint element that references contract 'UserService.UserService'

Do you have an Interface that your "UserService" class implements.

Your endpoints should specify an interface for the contract attribute:

contract="UserService.IUserService"

How to use addTarget method in swift 3

Try this

button.addTarget(self, action:#selector(handleRegister()), for: .touchUpInside). 

Just add parenthesis with name of method.

Also you can refer link : Value of type 'CustomButton' has no member 'touchDown'

Throw away local commits in Git

Before answering let's add some background, explaining what is this HEAD. since some of the options below will result in detached head

First of all what is HEAD?

HEAD is simply a reference to the current commit (latest) on the current branch.
There can only be a single HEAD at any given time. (excluding git worktree)

The content of HEAD is stored inside .git/HEAD and it contains the 40 bytes SHA-1 of the current commit.


detached HEAD

If you are not on the latest commit - meaning that HEAD is pointing to a prior commit in history its called detached HEAD.

enter image description here

On the command line, it will look like this- SHA-1 instead of the branch name since the HEAD is not pointing to the tip of the current branch

enter image description here

enter image description here

A few options on how to recover from a detached HEAD:


git checkout

git checkout <commit_id>
git checkout -b <new branch> <commit_id>
git checkout HEAD~X // x is the number of commits t go back

This will checkout new branch pointing to the desired commit.
This command will checkout to a given commit.
At this point, you can create a branch and start to work from this point on.

# Checkout a given commit. 
# Doing so will result in a `detached HEAD` which mean that the `HEAD`
# is not pointing to the latest so you will need to checkout branch
# in order to be able to update the code.
git checkout <commit-id>

# create a new branch forked to the given commit
git checkout -b <branch name>

git reflog

You can always use the reflog as well.
git reflog will display any change which updated the HEAD and checking out the desired reflog entry will set the HEAD back to this commit.

Every time the HEAD is modified there will be a new entry in the reflog

git reflog
git checkout HEAD@{...}

This will get you back to your desired commit

enter image description here


git reset --hard <commit_id>

"Move" your HEAD back to the desired commit.

# This will destroy any local modifications.
# Don't do it if you have uncommitted work you want to keep.
git reset --hard 0d1d7fc32

# Alternatively, if there's work to keep:
git stash
git reset --hard 0d1d7fc32
git stash pop
# This saves the modifications, then reapplies that patch after resetting.
# You could get merge conflicts if you've modified things which were
# changed since the commit you reset to.
  • Note: (Since Git 2.7)
    you can also use the git rebase --no-autostash as well.

git revert <sha-1>

"Undo" the given commit or commit range.
The reset command will "undo" any changes made in the given commit.
A new commit with the undo patch will be committed while the original commit will remain in the history as well.

# add new commit with the undo of the original one.
# the <sha-1> can be any commit(s) or commit range
git revert <sha-1>

This schema illustrates which command does what.
As you can see there reset && checkout modify the HEAD.

enter image description here

Bootstrap 3 Slide in Menu / Navbar on Mobile

This was for my own project and I'm sharing it here too.

DEMO: http://jsbin.com/OjOTIGaP/1/edit

This one had trouble after 3.2, so the one below may work better for you:

https://jsbin.com/seqola/2/edit --- BETTER VERSION, slightly


CSS

/* adjust body when menu is open */
body.slide-active {
    overflow-x: hidden
}
/*first child of #page-content so it doesn't shift around*/
.no-margin-top {
    margin-top: 0px!important
}
/*wrap the entire page content but not nav inside this div if not a fixed top, don't add any top padding */
#page-content {
    position: relative;
    padding-top: 70px;
    left: 0;
}
#page-content.slide-active {
    padding-top: 0
}
/* put toggle bars on the left :: not using button */
#slide-nav .navbar-toggle {
    cursor: pointer;
    position: relative;
    line-height: 0;
    float: left;
    margin: 0;
    width: 30px;
    height: 40px;
    padding: 10px 0 0 0;
    border: 0;
    background: transparent;
}
/* icon bar prettyup - optional */
#slide-nav .navbar-toggle > .icon-bar {
    width: 100%;
    display: block;
    height: 3px;
    margin: 5px 0 0 0;
}
#slide-nav .navbar-toggle.slide-active .icon-bar {
    background: orange
}
.navbar-header {
    position: relative
}
/* un fix the navbar when active so that all the menu items are accessible */
.navbar.navbar-fixed-top.slide-active {
    position: relative
}
/* screw writing importants and shit, just stick it in max width since these classes are not shared between sizes */
@media (max-width:767px) { 
    #slide-nav .container {
        margin: 0;
        padding: 0!important;
    }
    #slide-nav .navbar-header {
        margin: 0 auto;
        padding: 0 15px;
    }
    #slide-nav .navbar.slide-active {
        position: absolute;
        width: 80%;
        top: -1px;
        z-index: 1000;
    }
    #slide-nav #slidemenu {
        background: #f7f7f7;
        left: -100%;
        width: 80%;
        min-width: 0;
        position: absolute;
        padding-left: 0;
        z-index: 2;
        top: -8px;
        margin: 0;
    }
    #slide-nav #slidemenu .navbar-nav {
        min-width: 0;
        width: 100%;
        margin: 0;
    }
    #slide-nav #slidemenu .navbar-nav .dropdown-menu li a {
        min-width: 0;
        width: 80%;
        white-space: normal;
    }
    #slide-nav {
        border-top: 0
    }
    #slide-nav.navbar-inverse #slidemenu {
        background: #333
    }
    /* this is behind the navigation but the navigation is not inside it so that the navigation is accessible and scrolls*/
    #slide-nav #navbar-height-col {
        position: fixed;
        top: 0;
        height: 100%;
        width: 80%;
        left: -80%;
        background: #eee;
    }
    #slide-nav.navbar-inverse #navbar-height-col {
        background: #333;
        z-index: 1;
        border: 0;
    }
    #slide-nav .navbar-form {
        width: 100%;
        margin: 8px 0;
        text-align: center;
        overflow: hidden;
        /*fast clearfixer*/
    }
    #slide-nav .navbar-form .form-control {
        text-align: center
    }
    #slide-nav .navbar-form .btn {
        width: 100%
    }
}
@media (min-width:768px) { 
    #page-content {
        left: 0!important
    }
    .navbar.navbar-fixed-top.slide-active {
        position: fixed
    }
    .navbar-header {
        left: 0!important
    }
}

HTML

 <div class="navbar navbar-inverse navbar-fixed-top" role="navigation" id="slide-nav">
  <div class="container">
   <div class="navbar-header">
    <a class="navbar-toggle"> 
      <span class="sr-only">Toggle navigation</span>
      <span class="icon-bar"></span>
      <span class="icon-bar"></span>
      <span class="icon-bar"></span>
     </a>
    <a class="navbar-brand" href="#">Project name</a>
   </div>
   <div id="slidemenu">
     
          <form class="navbar-form navbar-right" role="form">
            <div class="form-group">
              <input type="search" placeholder="search" class="form-control">
            </div>
            <button type="submit" class="btn btn-primary">Search</button>
          </form>
     
    <ul class="nav navbar-nav">
     <li class="active"><a href="#">Home</a></li>
     <li><a href="#about">About</a></li>
     <li><a href="#contact">Contact</a></li>
     <li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown">Dropdown <b class="caret"></b></a>
      <ul class="dropdown-menu">
       <li><a href="#">Action</a></li>
       <li><a href="#">Another action</a></li>
       <li><a href="#">Something else here</a></li>
       <li class="divider"></li>
       <li class="dropdown-header">Nav header</li>
       <li><a href="#">Separated link</a></li>
       <li><a href="#">One more separated link</a></li>
       <li><a href="#">Action</a></li>
       <li><a href="#">Another action</a></li>
       <li><a href="#">Something else here</a></li>
       <li class="divider"></li>
       <li class="dropdown-header">Nav header</li>
       <li><a href="#">Separated link</a></li>
       <li><a href="#">One more separated link</a></li>
       <li><a href="#">Action</a></li>
       <li><a href="#">Another action</a></li>
       <li><a href="#">Something else here</a></li>
       <li class="divider"></li>
       <li class="dropdown-header">Nav header</li>
       <li><a href="#">Separated link test long title goes here</a></li>
       <li><a href="#">One more separated link</a></li>
      </ul>
     </li>
    </ul>
          
   </div>
  </div>
 </div>

jQuery

$(document).ready(function () {


    //stick in the fixed 100% height behind the navbar but don't wrap it
    $('#slide-nav.navbar .container').append($('<div id="navbar-height-col"></div>'));

    // Enter your ids or classes
    var toggler = '.navbar-toggle';
    var pagewrapper = '#page-content';
    var navigationwrapper = '.navbar-header';
    var menuwidth = '100%'; // the menu inside the slide menu itself
    var slidewidth = '80%';
    var menuneg = '-100%';
    var slideneg = '-80%';


    $("#slide-nav").on("click", toggler, function (e) {

        var selected = $(this).hasClass('slide-active');

        $('#slidemenu').stop().animate({
            left: selected ? menuneg : '0px'
        });

        $('#navbar-height-col').stop().animate({
            left: selected ? slideneg : '0px'
        });

        $(pagewrapper).stop().animate({
            left: selected ? '0px' : slidewidth
        });

        $(navigationwrapper).stop().animate({
            left: selected ? '0px' : slidewidth
        });


        $(this).toggleClass('slide-active', !selected);
        $('#slidemenu').toggleClass('slide-active');


        $('#page-content, .navbar, body, .navbar-header').toggleClass('slide-active');


    });


    var selected = '#slidemenu, #page-content, body, .navbar, .navbar-header';


    $(window).on("resize", function () {

        if ($(window).width() > 767 && $('.navbar-toggle').is(':hidden')) {
            $(selected).removeClass('slide-active');
        }


    });

});

Favicon: .ico or .png / correct tags?

For compatibility with all browsers stick with .ico.

.png is getting more and more support though as it is easier to create using multiple programs.

for .ico

<link rel="shortcut icon" href="http://example.com/myicon.ico" />

for .png, you need to specify the type

<link rel="icon" type="image/png" href="http://example.com/image.png" />

Double quotes within php script echo

Just escape your quotes:

echo "<script>$('#edit_errors').html('<h3><em><font color=\"red\">Please Correct Errors Before Proceeding</font></em></h3>')</script>";

Definitive way to trigger keypress events with jQuery

I made it work with keyup.

$("#id input").trigger('keyup');

How to set a class attribute to a Symfony2 form input

Renders the HTML widget of a given field. If you apply this to an entire form or collection of fields, each underlying form row will be rendered.

{# render a field row, but display a label with text "foo" #} {{ form_row(form.name, {'label': 'foo'}) }}

The second argument to form_row() is an array of variables. The templates provided in Symfony only allow to override the label as shown in the example above.

See "More about Form Variables" to learn about the variables argument.

Job for httpd.service failed because the control process exited with error code. See "systemctl status httpd.service" and "journalctl -xe" for details

From your output:

no listening sockets available, shutting down

what basically means, that any port in which one apache is going to be listening is already being used by another application.

netstat -punta | grep LISTEN

Will give you a list of all the ports being used and the information needed to recognize which process is so you can kill stop or do whatever you want to do with it.

After doing a nmap of your ip I can see that

80/tcp    open     http

so I guess you sorted it out.

Bash conditionals: how to "and" expressions? (if [ ! -z $VAR && -e $VAR ])

if [ -n "$var" -a -e "$var" ]; then
    do something ...
fi

 

REST vs JSON-RPC?

First, HTTP-REST is a "representational state transfer" architecture. This implies a lot of interesting things:

  • Your API will be stateless and therefore much easier to design (it's really easy to forget a transition in a complex automaton), and to integrate with independent software parts.
  • You will be lead to design read methods as safe ones, which will be easy to cache, and to integrate.
  • You will be lead to design write methods as idempotent ones, which will deal much better with timeouts.

Second, HTTP-REST is fully compliant with HTTP (see "safe" and "idempotent" in the previous part), therefore you will be able to reuse HTTP libraries (existing for every existing language) and HTTP reverse proxies, which will give you the ability to implement advanced features (cache, authentication, compression, redirection, rewriting, logging, etc.) with zero line of code.

Last but not least, using HTTP as an RPC protocol is a huge error according to the designer of HTTP 1.1 (and inventor of REST): http://www.ics.uci.edu/~fielding/pubs/dissertation/evaluation.htm#sec_6_5_2

How to work on UAC when installing XAMPP

You can press ok and it will continue the insallation.

Otherwise, see Trying to reinstall XAMPP on windows 7, getting error messag...

Action bar navigation modes are deprecated in Android L

I found these tutorials helpful while putting together an action bar (now the 'tool bar' - argh) that supports sliding tabs with Material Design:

https://www.youtube.com/watch?v=Fl0xMuo10yA

http://www.exoguru.com/android/material-design/navigation/android-sliding-tabs-with-material-design.html

You sort of have to synthesize these resources to match your particular situation. For example, you may not want to manually create the tabs in the same style that the exoguru.com tutorial did.

Can I force a page break in HTML printing?

Try this (its work in Chrome, Firefox and IE):

... content in page 1 ...
<p style="page-break-after: always;">&nbsp;</p>
<p style="page-break-before: always;">&nbsp;</p>
... content in page 2 ...

Bootstrap 3 Carousel Not Working

Well, Bootstrap Carousel has various parameters to control.

i.e.

Interval: Specifies the delay (in milliseconds) between each slide.

pause: Pauses the carousel from going through the next slide when the mouse pointer enters the carousel, and resumes the sliding when the mouse pointer leaves the carousel.

wrap: Specifies whether the carousel should go through all slides continuously, or stop at the last slide

For your reference:

enter image description here

Fore more details please click here...

Hope this will help you :)

Note: This is for the further help.. I mean how can you customise or change default behaviour once carousel is loaded.

xcode-select active developer directory error

Other solution for those who don't want to install Xcode:

  1. Install Command Line Tools (if you haven't already):

    xcode-select --install

  2. Change the active directory:

    sudo xcode-select -switch /Library/Developer/CommandLineTools

This worked for me (git).

How to get the first word in the string

Use this regex

^\w+

\w+ matches 1 to many characters.

\w is similar to [a-zA-Z0-9_]

^ depicts the start of a string


About Your Regex

Your regex (.*)?[ ] should be ^(.*?)[ ] or ^(.*?)(?=[ ]) if you don't want the space

How to create a cron job using Bash automatically without the interactive editor?

A variant which only edits crontab if the desired string is not found there:

CMD="/sbin/modprobe fcpci"
JOB="@reboot $CMD"
TMPC="mycron"
grep "$CMD" -q <(crontab -l) || (crontab -l>"$TMPC"; echo "$JOB">>"$TMPC"; crontab "$TMPC")

Is there a stopwatch in Java?

Try this...

import java.util.concurrent.TimeUnit;
import com.google.common.base.Stopwatch;

public class StopwatchTest {
     
    public static void main(String[] args) throws Exception {
        Stopwatch stopwatch = Stopwatch.createStarted();
        Thread.sleep(1000 * 60);
        stopwatch.stop(); // optional
        long millis = stopwatch.elapsed(TimeUnit.MILLISECONDS);
        System.out.println("Time in milliseconds "+millis);
        System.out.println("that took: " + stopwatch);
    }
}

Google Maps API: open url by clicking on marker

the previous answers didn't work out for me well. I had persisting problems by setting the marker. So i changed the code slightly.

   <!DOCTYPE html>
   <html>
   <head>
     <meta http-equiv="content-type" content="text/html; charset=ANSI" />
     <title>Google Maps Multiple Markers</title>
     <script src="http://maps.google.com/maps/api/js?sensor=false"
      type="text/javascript"></script>
   </head>
   <body>
     <div id="map" style="width: 1500px; height: 1000px;"></div>

     <script type="text/javascript">
       var locations = [
         ['Goettingen',  51.54128040000001,  9.915803500000038, 'http://www.google.de'],
         ['Kassel', 51.31271139999999,  9.479746100000057,0, 'http://www.stackoverflow.com'],
         ['Witzenhausen', 51.33996819999999,  9.855564299999969,0, 'www.http://developer.mozilla.org.de']

 ];

var map = new google.maps.Map(document.getElementById('map'), {
  zoom: 10,
 center: new google.maps.LatLng(51.54376, 9.910419999999931),
 mapTypeId: google.maps.MapTypeId.ROADMAP
});

var infowindow = new google.maps.InfoWindow();

var marker, i;

for (i = 0; i < locations.length; i++) {
  marker = new google.maps.Marker({
   position: new google.maps.LatLng(locations[i][1], locations[i][2]),
   map: map,
   url: locations[i][4]
  });

 google.maps.event.addListener(marker, 'mouseover', (function(marker, i) {
   return function() {
     infowindow.setContent(locations[i][0]);
     infowindow.open(map, marker);
   }
 })(marker, i));

      google.maps.event.addListener(marker, 'click', (function(marker, i) {
   return function() {
     infowindow.setContent(locations[i][0]);
     infowindow.open(map, marker);
     window.location.href = this.url;
   }
 })(marker, i));

    }

     </script>
   </body>
   </html>

This way worked out for me! You can create Google Maps routing links from your Datebase to to use it as an interactive routing map.

How can I set the font-family & font-size inside of a div?

Append a semicolon to the following line to fix the issue.

font-family:    Arial, Helvetica, sans-serif;

Format a datetime into a string with milliseconds

I assume you mean you're looking for something that is faster than datetime.datetime.strftime(), and are essentially stripping the non-alpha characters from a utc timestamp.

You're approach is marginally faster, and I think you can speed things up even more by slicing the string:

>>> import timeit
>>> t=timeit.Timer('datetime.utcnow().strftime("%Y%m%d%H%M%S%f")','''
... from datetime import datetime''')
>>> t.timeit(number=10000000)
116.15451288223267

>>> def replaceutc(s):
...     return s\
...         .replace('-','') \
...         .replace(':','') \
...         .replace('.','') \
...         .replace(' ','') \
...         .strip()
... 
>>> t=timeit.Timer('replaceutc(str(datetime.datetime.utcnow()))','''
... from __main__ import replaceutc
... import datetime''')
>>> t.timeit(number=10000000)
77.96774983406067

>>> def sliceutc(s):
...     return s[:4] + s[5:7] + s[8:10] + s[11:13] + s[14:16] + s[17:19] + s[20:]
... 
>>> t=timeit.Timer('sliceutc(str(datetime.utcnow()))','''
... from __main__ import sliceutc
... from datetime import datetime''')
>>> t.timeit(number=10000000)
62.378515005111694

React / JSX Dynamic Component Name

Assume we have a flag, no different from the state or props:

import ComponentOne from './ComponentOne';
import ComponentTwo from './ComponentTwo';

~~~

const Compo = flag ? ComponentOne : ComponentTwo;

~~~

<Compo someProp={someValue} />

With flag Compo fill with one of ComponentOne or ComponentTwo and then the Compo can act like a React Component.

Use async await with Array.map

I'd recommend using Promise.all as mentioned above, but if you really feel like avoiding that approach, you can do a for or any other loop:

const arr = [1,2,3,4,5];
let resultingArr = [];
for (let i in arr){
  await callAsynchronousOperation(i);
  resultingArr.push(i + 1)
}

WebSockets and Apache proxy : how to configure mod_proxy_wstunnel?

I finally managed to do it, thanks to this topic.

TODO:

1) Have Apache 2.4 installed (doesn't work with 2.2), and do:

a2enmod proxy
a2enmod proxy_http
a2enmod proxy_wstunnel

2) Have nodejs running on port 3001

3) Do this in the Apache config

<VirtualHost *:80>
  ServerName www.domain2.com

  RewriteEngine On
  RewriteCond %{REQUEST_URI}  ^/socket.io            [NC]
  RewriteCond %{QUERY_STRING} transport=websocket    [NC]
  RewriteRule /(.*)           ws://localhost:3001/$1 [P,L]

  ProxyPass / http://localhost:3001/
  ProxyPassReverse / http://localhost:3001/
</VirtualHost>

Note: if you have more than one service on the same server that uses websockets, you might want to do this to separate them.

How to check if a process is running via a batch script

I like the WMIC and TASKLIST tools but they are not available in home/basic editions of windows.Another way is to use QPROCESS command available on almost every windows machine (for the ones that have terminal services - I think only win XP without SP2 , so practialy every windows machine):

@echo off
:check_process
setlocal
if "%~1" equ "" echo pass the process name as forst argument && exit /b 1
:: first argument is the process you want to check if running
set process_to_check=%~1
:: QPROCESS can display only the first 12 symbols of the running process
:: If other tool is used the line bellow could be deleted
set process_to_check=%process_to_check:~0,12%

QPROCESS * | find /i "%process_to_check%" >nul 2>&1 && (
    echo process %process_to_check%  is running
) || (
    echo process %process_to_check%  is not running
)
endlocal

QPROCESS command is not so powerful as TASKLIST and is limited in showing only 12 symbols of process name but should be taken into consideration if TASKLIST is not available.

More simple usage where it uses the name if the process as an argument (the .exe suffix is mandatory in this case where you pass the executable name):

@echo off
:check_process
setlocal
if "%~1" equ "" echo pass the process name as forst argument && exit /b 1
:: first argument is the process you want to check if running
:: .exe suffix is mandatory
set "process_to_check=%~1"


QPROCESS "%process_to_check%" >nul 2>&1 && (
    echo process %process_to_check%  is running
) || (
    echo process %process_to_check%  is not running
)
endlocal

The difference between two ways of QPROCESS usage is that the QPROCESS * will list all processes while QPROCESS some.exe will filter only the processes for the current user.

Using WMI objects through windows script host exe instead of WMIC is also an option.It should on run also on every windows machine (excluding the ones where the WSH is turned off but this is a rare case).Here bat file that lists all processes through WMI classes and can be used instead of QPROCESS in the script above (it is a jscript/bat hybrid and should be saved as .bat):

@if (@X)==(@Y) @end /* JSCRIPT COMMENT **


@echo off
cscript //E:JScript //nologo "%~f0"
exit /b

************** end of JSCRIPT COMMENT **/


var winmgmts = GetObject("winmgmts:\\\\.\\root\\cimv2");
var colProcess = winmgmts.ExecQuery("Select * from Win32_Process");
var processes =  new Enumerator(colProcess);
for (;!processes.atEnd();processes.moveNext()) {
    var process=processes.item();
    WScript.Echo( process.processID + "   " + process.Name );
}

And a modification that will check if a process is running:

@if (@X)==(@Y) @end /* JSCRIPT COMMENT **


@echo off
if "%~1" equ "" echo pass the process name as forst argument && exit /b 1
:: first argument is the process you want to check if running
set process_to_check=%~1

cscript //E:JScript //nologo "%~f0" | find /i "%process_to_check%" >nul 2>&1 && (
    echo process %process_to_check%  is running
) || (
    echo process %process_to_check%  is not running
)

exit /b

************** end of JSCRIPT COMMENT **/


var winmgmts = GetObject("winmgmts:\\\\.\\root\\cimv2");
var colProcess = winmgmts.ExecQuery("Select * from Win32_Process");
var processes =  new Enumerator(colProcess);
for (;!processes.atEnd();processes.moveNext()) {
    var process=processes.item();
    WScript.Echo( process.processID + "   " + process.Name );
}

The two options could be used on machines that have no TASKLIST.

The ultimate technique is using MSHTA . This will run on every windows machine from XP and above and does not depend on windows script host settings. the call of MSHTA could reduce a little bit the performance though (again should be saved as bat):

@if (@X)==(@Y) @end /* JSCRIPT COMMENT **
@echo off

setlocal
if "%~1" equ "" echo pass the process name as forst argument && exit /b 1
:: first argument is the process you want to check if running

set process_to_check=%~1


mshta "about:<script language='javascript' src='file://%~dpnxf0'></script>" | find /i "%process_to_check%" >nul 2>&1 && (
    echo process %process_to_check%  is running
) || (
    echo process %process_to_check%  is not running
)
endlocal
exit /b
************** end of JSCRIPT COMMENT **/


   var fso= new ActiveXObject('Scripting.FileSystemObject').GetStandardStream(1);


   var winmgmts = GetObject("winmgmts:\\\\.\\root\\cimv2");
   var colProcess = winmgmts.ExecQuery("Select * from Win32_Process");
   var processes =  new Enumerator(colProcess);
   for (;!processes.atEnd();processes.moveNext()) {
    var process=processes.item();
    fso.Write( process.processID + "   " + process.Name + "\n");
   }
   close();

How do you put an image file in a json object?

Use data URL scheme: https://en.wikipedia.org/wiki/Data_URI_scheme

In this case you use that string directly in html : <img src="data:image/png;base64,iVBOR....">

Commit empty folder structure (with git)

You can make an empty commit with git commit --allow-empty, but that will not allow you to commit an empty folder structure as git does not know or care about folders as objects themselves -- just the files they contain.

List all files in one directory PHP

You are looking for the command scandir.

$path    = '/tmp';
$files = scandir($path);

Following code will remove . and .. from the returned array from scandir:

$files = array_diff(scandir($path), array('.', '..'));

Converting string to Date and DateTime

For first Date

$_firstDate = date("m-d-Y", strtotime($_yourDateString));

For New Date

$_newDate = date("Y-m-d",strtotime($_yourDateString));

Represent space and tab in XML tag

If you are talking about the issue where multiple and non-space whitespace characters are stripped specifically from attribute values, then yes, encoding them as character references such as &#9; will fix it.

JavaScript calculate the day of the year (1 - 366)

For those among us who want a fast alternative solution.

_x000D_
_x000D_
(function(){"use strict";_x000D_
function daysIntoTheYear(dateInput){_x000D_
    var fullYear = dateInput.getFullYear()|0;_x000D_
 // "Leap Years are any year that can be exactly divided by 4 (2012, 2016, etc)_x000D_
  // except if it can be exactly divided by 100, then it isn't (2100, 2200, etc)_x000D_
  //  except if it can be exactly divided by 400, then it is (2000, 2400)"_x000D_
 // (https://www.mathsisfun.com/leap-years.html)._x000D_
    var isLeapYear = ((fullYear & 3) | (fullYear/100 & 3)) === 0 ? 1 : 0;_x000D_
 // (fullYear & 3) = (fullYear % 4), but faster_x000D_
    //Alternative:var isLeapYear=(new Date(currentYear,1,29,12)).getDate()===29?1:0_x000D_
    var fullMonth = dateInput.getMonth()|0;_x000D_
    return ((_x000D_
        // Calculate the day of the year in the Gregorian calendar_x000D_
        // The code below works based upon the facts of signed right shifts_x000D_
        //    • (x) >> n: shifts n and fills in the n highest bits with 0s _x000D_
        //    • (-x) >> n: shifts n and fills in the n highest bits with 1s_x000D_
        // (This assumes that x is a positive integer)_x000D_
        (31 & ((-fullMonth) >> 4)) + // January // (-11)>>4 = -1_x000D_
        ((28 + isLeapYear) & ((1-fullMonth) >> 4)) + // February_x000D_
        (31 & ((2-fullMonth) >> 4)) + // March_x000D_
        (30 & ((3-fullMonth) >> 4)) + // April_x000D_
        (31 & ((4-fullMonth) >> 4)) + // May_x000D_
        (30 & ((5-fullMonth) >> 4)) + // June_x000D_
        (31 & ((6-fullMonth) >> 4)) + // July_x000D_
        (31 & ((7-fullMonth) >> 4)) + // August_x000D_
        (30 & ((8-fullMonth) >> 4)) + // September_x000D_
        (31 & ((9-fullMonth) >> 4)) + // October_x000D_
        (30 & ((10-fullMonth) >> 4)) + // November_x000D_
        // There are no months past December: the year rolls into the next._x000D_
        // Thus, fullMonth is 0-based, so it will never be 12 in Javascript_x000D_
_x000D_
        (dateInput.getDate()|0) // get day of the month_x000D_
_x000D_
    )&0xffff);_x000D_
}_x000D_
// Demonstration:_x000D_
var date = new Date(2100, 0, 1)_x000D_
for (var i=0; i<12; i=i+1|0, date.setMonth(date.getMonth()+1|0))_x000D_
    console.log(date.getMonth()+":\tday "+daysIntoTheYear(date)+"\t"+date);_x000D_
date = new Date(1900, 0, 1);_x000D_
for (var i=0; i<12; i=i+1|0, date.setMonth(date.getMonth()+1|0))_x000D_
    console.log(date.getMonth()+":\tday "+daysIntoTheYear(date)+"\t"+date);_x000D_
_x000D_
// Performance Benchmark:_x000D_
console.time("Speed of processing 65536 dates");_x000D_
for (var i=0,month=date.getMonth()|0; i<65536; i=i+1|0)_x000D_
    date.setMonth(month=month+1+(daysIntoTheYear(date)|0)|0);_x000D_
console.timeEnd("Speed of processing 65536 dates");_x000D_
})();
_x000D_
_x000D_
_x000D_

The size of the months of the year and the way that Leap Years work fits perfectly into keeping our time on track with the sun. Heck, it works so perfectly that all we ever do is just adjust mere seconds here and there. Our current system of leap years has been in effect since February 24th, 1582, and will likely stay in effect for the foreseeable future.

DST, however, is very subject to change. It may be that 20 years from now, some country may offset time by a whole day or some other extreme for DST. A whole DST day will almost certainly never happen, but DST is still nevertheless very up-in-the-air and indecisive. Thus, the above solution is future proof in addition to being very very fast.

The above code snippet runs very fast. My computer can process 65536 dates in ~52ms on Chrome.

Is it possible to log all HTTP request headers with Apache?

If you're interested in seeing which specific headers a remote client is sending to your server, and you can cause the request to run a CGI script, then the simplest solution is to have your server script dump the environment variables into a file somewhere.

e.g. run the shell command "env > /tmp/headers" from within your script

Then, look for the environment variables that start with HTTP_...

You will see lines like:

HTTP_ACCEPT=text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
HTTP_ACCEPT_ENCODING=gzip, deflate
HTTP_ACCEPT_LANGUAGE=en-US,en;q=0.5
HTTP_CACHE_CONTROL=max-age=0

Each of those represents a request header.

Note that the header names are modified from the actual request. For example, "Accept-Language" becomes "HTTP_ACCEPT_LANGUAGE", and so on.

javax.net.ssl.SSLHandshakeException: java.security.cert.CertPathValidatorException: Trust anchor for certification path not found

The reason this occur is the JVM/Dalvik haven't not confidence in the CA certificates in the system or in the user certificate stores.

To fix this with Retrofit, If you are used okhttp, with another client it's very similar.
You've to do:

A). Create a cert store contain public Key of CA. To do this you need to launch next script for *nix. You need openssl install in your machine, and download from https://www.bouncycastle.org/ the jar bcprov-jdk16-1.46.jar. Download this version not other, the version 1.5x is not compatible with android 4.0.4.

#!/bin/bash

if [ -z $1 ]; then
  echo "Usage: cert2Android<CA cert PEM file>"
  exit 1
fi

CACERT=$1
BCJAR=bcprov-jdk16-1.46.jar

TRUSTSTORE=mytruststore.bks
ALIAS=`openssl x509 -inform PEM -subject_hash -noout -in $CACERT`

if [ -f $TRUSTSTORE ]; then
    rm $TRUSTSTORE || exit 1
fi

echo "Adding certificate to $TRUSTSTORE..."
keytool -import -v -trustcacerts -alias $ALIAS \
      -file $CACERT \
      -keystore $TRUSTSTORE -storetype BKS \
      -providerclass org.bouncycastle.jce.provider.BouncyCastleProvider \
      -providerpath $BCJAR \
      -storepass secret

echo "" 
echo "Added '$CACERT' with alias '$ALIAS' to $TRUSTSTORE..."

B). Copy the file truststore mytruststore.bks in res/raw of your project truststore location

C). Setting SSLContext of the connection:

.............
okHttpClient = new OkHttpClient();
try {
    KeyStore ksTrust = KeyStore.getInstance("BKS");
    InputStream instream = context.getResources().openRawResource(R.raw.mytruststore);
    ksTrust.load(instream, "secret".toCharArray());

    // TrustManager decides which certificate authorities to use.
    TrustManagerFactory tmf = TrustManagerFactory
        .getInstance(TrustManagerFactory.getDefaultAlgorithm());
    tmf.init(ksTrust);
    SSLContext sslContext = SSLContext.getInstance("TLS");
    sslContext.init(null, tmf.getTrustManagers(), null);

    okHttpClient.setSslSocketFactory(sslContext.getSocketFactory());
} catch (KeyStoreException | IOException | NoSuchAlgorithmException | CertificateException | KeyManagementException e) {
    e.printStackTrace();
}
.................

How can I get a character in a string by index?

Do you mean like this

int index = 2;
string s = "hello";
Console.WriteLine(s[index]);

string also implements IEnumberable<char> so you can also enumerate it like this

foreach (char c in s)
    Console.WriteLine(c);

Oracle Partition - Error ORA14400 - inserted partition key does not map to any partition

select partition_name,column_name,high_value,partition_position
from ALL_TAB_PARTITIONS a , ALL_PART_KEY_COLUMNS b 
where table_name='YOUR_TABLE' and a.table_name = b.name;

This query lists the column name used as key and the allowed values. make sure, you insert the allowed values(high_value). Else, if default partition is defined, it would go there.


EDIT:

I presume, your TABLE DDL would be like this.

CREATE TABLE HE0_DT_INF_INTERFAZ_MES
  (
    COD_PAIS NUMBER,
    FEC_DATA NUMBER,
    INTERFAZ VARCHAR2(100)
  )
  partition BY RANGE(COD_PAIS, FEC_DATA)
  (
    PARTITION PDIA_98_20091023 VALUES LESS THAN (98,20091024)
  );

Which means I had created a partition with multiple columns which holds value less than the composite range (98,20091024);

That is first COD_PAIS <= 98 and Also FEC_DATA < 20091024

Combinations And Result:

98, 20091024     FAIL
98, 20091023     PASS
99, ********     FAIL
97, ********     PASS
 < 98, ********     PASS

So the below INSERT fails with ORA-14400; because (98,20091024) in INSERT is EQUAL to the one in DDL but NOT less than it.

SQL> INSERT INTO HE0_DT_INF_INTERFAZ_MES(COD_PAIS, FEC_DATA, INTERFAZ)
                                  VALUES(98, 20091024, 'CTA');  2
INSERT INTO HE0_DT_INF_INTERFAZ_MES(COD_PAIS, FEC_DATA, INTERFAZ)
            *
ERROR at line 1:
ORA-14400: inserted partition key does not map to any partition

But, we I attempt (97,20091024), it goes through

SQL> INSERT INTO HE0_DT_INF_INTERFAZ_MES(COD_PAIS, FEC_DATA, INTERFAZ)
  2                                    VALUES(97, 20091024, 'CTA');

1 row created.

Visual c++ can't open include file 'iostream'

Microsoft Visual Studio is funny when your using the installer you MUST checkbox a-lot of options to bypass the .netframework(somewhat) to make more c++ instead of c sharp applications, such as the clr options under dekstop development... in visual studio installer.... difference is c++ win32 console project or a c++ CLR console project. So whats the difference? Well i'm not going to list all of the files CLR includes but since most good c++ kernals are in linux... so CLR allows you to bypass a-lot of the windows .netframework b/c visual studio was really meant for you to make apps in C sharp.

Heres a C++ win32 console project!

#include "stdafx.h"
#include <iostream>
using namespace std;
int main( )
{
cout<<"Hello World"<<endl;
return 0;
}

Now heres a c++ CLR console project!

#include "stdafx.h"

using namespace System;

int main(array<System::String ^> ^args)
{
Console::WriteLine("Hello World");
return 0;
}

Both programs do the same thing .... CLR just looks more frameworked class overloading methodology so microsoft can great it's own vast library you should familiarize yourself w/ if so inclined. https://msdn.microsoft.com/en-us/library/2e6a4at9.aspx

other things you'll learn from debugging to add for error avoidance

#ifdef _MRC_VER
#define _CRT_SECURE_NO_WARNINGS
#endif

How to change Android usb connect mode to charge only?

In your phone go to Settings->Connect to PC.

There you will see the option Default Connection Type. Select it and set it to your preference.

How can I convert a .py to .exe for Python?

I can't tell you what's best, but a tool I have used with success in the past was cx_Freeze. They recently updated (on Jan. 7, '17) to version 5.0.1 and it supports Python 3.6.

Here's the pypi https://pypi.python.org/pypi/cx_Freeze

The documentation shows that there is more than one way to do it, depending on your needs. http://cx-freeze.readthedocs.io/en/latest/overview.html

I have not tried it out yet, so I'm going to point to a post where the simple way of doing it was discussed. Some things may or may not have changed though.

How do I use cx_freeze?

Initializing C# auto-properties

In the default constructor (and any non-default ones if you have any too of course):

public foo() {
    Bar = "bar";
}

This is no less performant that your original code I believe, since this is what happens behind the scenes anyway.

Cassandra "no viable alternative at input"

Wrong syntax. Here you are:

insert into user_by_category (game_category,customer_id) VALUES ('Goku','12');

or:

insert into user_by_category ("game_category","customer_id") VALUES ('Kakarot','12');

The second one is normally used for case-sensitive column names.

What are the most widely used C++ vector/matrix math/linear algebra libraries, and their cost and benefit tradeoffs?

If you are looking for high performance matrix/linear algebra/optimization on Intel processors, I'd look at Intel's MKL library.

MKL is carefully optimized for fast run-time performance - much of it based on the very mature BLAS/LAPACK fortran standards. And its performance scales with the number of cores available. Hands-free scalability with available cores is the future of computing and I wouldn't use any math library for a new project doesn't support multi-core processors.

Very briefly, it includes:

  1. Basic vector-vector, vector-matrix, and matrix-matrix operations
  2. Matrix factorization (LU decomp, hermitian,sparse)
  3. Least squares fitting and eigenvalue problems
  4. Sparse linear system solvers
  5. Non-linear least squares solver (trust regions)
  6. Plus signal processing routines such as FFT and convolution
  7. Very fast random number generators (mersenne twist)
  8. Much more.... see: link text

A downside is that the MKL API can be quite complex depending on the routines that you need. You could also take a look at their IPP (Integrated Performance Primitives) library which is geared toward high performance image processing operations, but is nevertheless quite broad.

Paul

CenterSpace Software ,.NET Math libraries, centerspace.net

How can I check if some text exist or not in the page using Selenium?

You could retrieve the body text of the whole page like this:

bodyText = self.driver.find_element_by_tag_name('body').text

then use an assert to check it like this:

self.assertTrue("the text you want to check for" in bodyText)

Of course, you can be specific and retrieve a specific DOM element's text and then check that instead of retrieving the whole page.

How to use execvp()

The first argument is the file you wish to execute, and the second argument is an array of null-terminated strings that represent the appropriate arguments to the file as specified in the man page.

For example:

char *cmd = "ls";
char *argv[3];
argv[0] = "ls";
argv[1] = "-la";
argv[2] = NULL;

execvp(cmd, argv); //This will run "ls -la" as if it were a command

Parse an URL in JavaScript

Try this:

var url = window.location;
var urlAux = url.split('=');
var img_id = urlAux[1]

Hidden property of a button in HTML

It also works without jQuery if you do the following changes:

  1. Add type="button" to the edit button in order not to trigger submission of the form.

  2. Change the name of your function from change() to anything else.

  3. Don't use hidden="hidden", use CSS instead: style="display: none;".

The following code works for me:

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="STYLESHEET" type="text/css" href="dba_style/buttons.css" />
<title>Untitled Document</title>
</head>
<script type="text/javascript">
function do_change(){
document.getElementById("save").style.display = "block";
document.getElementById("change").style.display = "block";
document.getElementById("cancel").style.display = "block";
}
</script>
<body>
<form name="form1" method="post" action="">
<div class="buttons">

<button type="button" class="regular" name="edit" id="edit" onclick="do_change(); return false;">
    <img src="dba_images/textfield_key.png" alt=""/>
    Edit
</button>

<button type="submit" class="positive" name="save" id="save" style="display:none;">
    <img src="dba_images/apply2.png" alt=""/>
    Save
</button>

<button class="regular" name="change" id="change" style="display:none;">
    <img src="dba_images/textfield_key.png" alt=""/>
    change
</button>

    <button class="negative" name="cancel" id="cancel" style="display:none;">
        <img src="dba_images/cross.png" alt=""/>
        Cancel
    </button>
</div>
</form>
</body>
</html>

SQL Developer is returning only the date, not the time. How do I fix this?

To expand on some of the previous answers, I found that Oracle DATE objects behave different from Oracle TIMESTAMP objects. In particular, if you set your NLS_DATE_FORMAT to include fractional seconds, the entire time portion is omitted.

  • Format "YYYY-MM-DD HH24:MI:SS" works as expected, for DATE and TIMESTAMP
  • Format "YYYY-MM-DD HH24:MI:SSXFF" displays just the date portion for DATE, works as expected for TIMESTAMP

My personal preference is to set DATE to "YYYY-MM-DD HH24:MI:SS", and to set TIMESTAMP to "YYYY-MM-DD HH24:MI:SSXFF".

Get the week start date and week end date from week number

Below query will give data between start and end of current week starting from sunday to saturday

SELECT DOB FROM PROFILE_INFO WHERE DAY(DOB) BETWEEN
DAY( CURRENT_DATE() - (SELECT DAYOFWEEK(CURRENT_DATE())-1))
AND
DAY((CURRENT_DATE()+(7 - (SELECT DAYOFWEEK(CURRENT_DATE())) ) ))
AND
MONTH(DOB)=MONTH(CURRENT_DATE())

How many bytes does one Unicode character take?

For UTF-16, the character needs four bytes (two code units) if it starts with 0xD800 or greater; such a character is called a "surrogate pair." More specifically, a surrogate pair has the form:

[0xD800 - 0xDBFF]  [0xDC00 - 0xDFF]

where [...] indicates a two-byte code unit with the given range. Anything <= 0xD7FF is one code unit (two bytes). Anything >= 0xE000 is invalid (except BOM markers, arguably).

See http://unicodebook.readthedocs.io/unicode_encodings.html, section 7.5.

How to fix height of TR?

Your table width is 90% which is relative to it's container.

If you squeeze the page, you are probably squeezing the table width as well. The width of the cells reduce too and the browser compensate by increasing the height.

To have the height untouched, you have to make sure the widths of the cells can hold the intented content. Fixing the table width is probably something you want to try. Or perhaps play around with the min-width of the table.

How do you specify a different port number in SQL Management Studio?

127.0.0.1,6283

Add a comma between the ip and port

Difference between VARCHAR2(10 CHAR) and NVARCHAR2(10)

  • The NVARCHAR2 stores variable-length character data. When you create a table with the NVARCHAR2 column, the maximum size is always in character length semantics, which is also the default and only length semantics for the NVARCHAR2 data type.

    The NVARCHAR2data type uses AL16UTF16character set which encodes Unicode data in the UTF-16 encoding. The AL16UTF16 use 2 bytes to store a character. In addition, the maximum byte length of an NVARCHAR2 depends on the configured national character set.

  • VARCHAR2 The maximum size of VARCHAR2 can be in either bytes or characters. Its column only can store characters in the default character set while the NVARCHAR2 can store virtually any characters. A single character may require up to 4 bytes.

By defining the field as:

  • VARCHAR2(10 CHAR) you tell Oracle it can use enough space to store 10 characters, no matter how many bytes it takes to store each one. A single character may require up to 4 bytes.
  • NVARCHAR2(10) you tell Oracle it can store 10 characters with 2 bytes per character

In Summary:

  • VARCHAR2(10 CHAR) can store maximum of 10 characters and maximum of 40 bytes (depends on the configured national character set).

  • NVARCHAR2(10) can store maximum of 10 characters and maximum of 20 bytes (depends on the configured national character set).

Note: Character set can be UTF-8, UTF-16,....

Please have a look at this tutorial for more detail.

Have a good day!

Add Foreign Key to existing table

MySQL will execute this query:

ALTER TABLE `db`.`table1`
ADD COLUMN `col_table2_fk` INT UNSIGNED NULL,
ADD INDEX `col_table2_fk_idx` (`col_table2_fk` ASC),
ADD CONSTRAINT `col_table2_fk1`
FOREIGN KEY (`col_table2_fk`)
REFERENCES `db`.`table2` (`table2_id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION;

Cheers!

"Sources directory is already netbeans project" error when opening a project from existing sources

This is what I did to solve this error:

1) I copied a folder named "folder1" (and I called the new folder "folder2"). "folder1" was a Netbeans project so it had a folder called "nbproject" inside it.

2) When I tried to create a project out of the "folder2", Netbeans threw an error "Sources directory is already netbeans project (maybe only in memory)."

3) Inside Netbeans delete the project of "folder1". Then, delete the two folders named "nbproject" (one is inside "folder1" and the other is inside "folder2").

4) Inside Netbeans, create two new projects: one for "folder1" and another for "folder2". The error should not appear anymore.

Xcode stuck on Indexing

When using Xcode 6 and it says

Waiting for make

It might be that an instance of make is already running. Kill the process and indexing proceeds. Silly, but worked for me.

Extracting date from a string in Python

If you know the position of the date object in the string (for example in a log file), you can use .split()[index] to extract the date without fully knowing the format.

For example:

>>> string = 'monkey 2010-07-10 love banana'
>>> date = string.split()[1]
>>> date
'2010-07-10'

Detecting an "invalid date" Date instance in JavaScript

For int 1-based components of a date:

var is_valid_date = function(year, month, day) {
    var d = new Date(year, month - 1, day);
    return d.getFullYear() === year && (d.getMonth() + 1) === month && d.getDate() === day
};

Tests:

    is_valid_date(2013, 02, 28)
&&  is_valid_date(2016, 02, 29)
&& !is_valid_date(2013, 02, 29)
&& !is_valid_date(0000, 00, 00)
&& !is_valid_date(2013, 14, 01)

How to validate a form with multiple checkboxes to have atleast one checked

How about this

$.validate.addMethod(cb_selectone,
                   function(value,element){
                           if(element.length>0){
                               for(var i=0;i<element.length;i++){
                                if($(element[i]).val('checked')) return true;
                               }
                           return false;
                           }
                            return false;
                  },
                  'Please select a least one')

Now you ca do

$.validate({rules:{checklist:"cb_selectone"}});

You can even go further a specify the minimum number to select with a third param in the callback function.I have not tested it yet so tell me if it works.

PHP - Get array value with a numeric index

array_values() will do pretty much what you want:

$numeric_indexed_array = array_values($your_array);
// $numeric_indexed_array = array('bar', 'bin', 'ipsum');
print($numeric_indexed_array[0]); // bar

File Explorer in Android Studio

enter image description here

Then the Android Device Monitor window will pop up. Click on the emulator & File Explorer.

Shared Preference files should be in:

DDMS-> File Explorer ->data -> data -> MY_PACKAGE_NAME -> shared_prefs -> YOUR_PREFERENCE_NAME.xml

enter image description here

Use table name in MySQL SELECT "AS"

SELECT field1, field2, 'Test' AS field3 FROM Test; // replace with simple quote '

Python syntax for "if a or b or c but not all of them"

And why not just count them ?

import sys
a = sys.argv
if len(a) = 1 :  
    # No arguments were given, the program name count as one
elif len(a) = 4 :
    # Three arguments were given
else :
    # another amount of arguments was given

How to manually deploy artifacts in Nexus Repository Manager OSS 3

You can upload artifacts via their native publishing capabilities (e.g. maven deploy, npm publish).

You can also upload artifacts to "raw" repositories via a simple curl request, e.g.

curl --fail -u admin:admin123 --upload-file foo.jar 'http://my-nexus-server.com:8081/repository/my-raw-repo/'

How to include files outside of Docker's build context?

In my case, my Dockerfile is written like a template containing placeholders which I'm replacing with real value using my configuration file.

So I couldn't specify this file directly but pipe it into the docker build like this:

sed "s/%email_address%/$EMAIL_ADDRESS/;" ./Dockerfile | docker build -t katzda/bookings:latest . -f -;

But because of the pipe, the COPY command didn't work. But the above way solves it by -f - (explicitly saying file not provided). Doing only - without the -f flag, the context AND the Dockerfile are not provided which is a caveat.

Using :after to clear floating elements

Use

.wrapper:after {
    content : '\n';
}

Much like solution provided by Roko. It allows to insert/change content using : after and :before psuedo. For details check http://www.quirksmode.org/css/content.html

New Line Issue when copying data from SQL Server 2012 to Excel

Changing all my queries because Studio changed version isn't an option. Tried the preferences mentioned above to no effect. It didn't put the quotes in when there was a CR-LF. Perhaps it only triggers when a comma happens.

Copy-paste to Excel is a mainstay of SQL server. Mircosoft either needs a checkbox to revert back to 2008 behavior or they need to enhance the clipboard transfer to Excel such that ONE ROW EQUALS ONE ROW.

How to Compare a long value is equal to Long value

I will share that How do I do it since Java 7 -

Long first = 12345L, second = 123L;
System.out.println(first.equals(second));

output returned : false

and second example of match is -

Long first = 12345L, second = 12345L;
System.out.println(first.equals(second));

output returned : true

So, I believe in equals method for comparing Object's value, Hope it helps you, thanks.

Accessing localhost (xampp) from another computer over LAN network - how to?

Here is what i did and worked for me on windows 10:

1) Hit windows + r and type cmd . In the command prompt type ipconfig
2) find your ipv4 address and rename your website url to that ip eg: http://192.168.0.2/example.
3) Now make sure your firewall has access to Apache HTTP Server. Search windows for "Allow an app through windows firewall" click on it then on the top right click change settings and make sure the Apache HTTP Server has one tick on the left and one on the private or public. Hope it helps

Now you can access the website from other PCs in the lan

Copy-item Files in Folders and subfolders in the same directory structure of source server using PowerShell

I had trouble with the most popular answer (overthinking). It put AFolder in the \Server\MyFolder\AFolder and I wanted the contents of AFolder and below in MyFolder. This didn't work.

Copy-Item -Verbose -Path C:\MyFolder\AFolder -Destination \\Server\MyFolder -recurse -Force

Plus I needed to Filter and only copy *.config files.

This didn't work, with "\*" because it did not recurse

Copy-Item -Verbose -Path C:\MyFolder\AFolder\* -Filter *.config -Destination \\Server\MyFolder -recurse -Force

I ended up lopping off the beginning of the path string, to get the childPath relative to where I was recursing from. This works for the use-case in question and went down many subdirectories, which some other solutions do not.

Get-Childitem -Path "$($sourcePath)/**/*.config" -Recurse | 
ForEach-Object {
  $childPath = "$_".substring($sourcePath.length+1)
  $dest = "$($destPath)\$($childPath)" #this puts a \ between dest and child path
  Copy-Item -Verbose -Path $_ -Destination $dest -Force   
}

must appear in the GROUP BY clause or be used in an aggregate function

Yes, this is a common aggregation problem. Before SQL3 (1999), the selected fields must appear in the GROUP BY clause[*].

To workaround this issue, you must calculate the aggregate in a sub-query and then join it with itself to get the additional columns you'd need to show:

SELECT m.cname, m.wmname, t.mx
FROM (
    SELECT cname, MAX(avg) AS mx
    FROM makerar
    GROUP BY cname
    ) t JOIN makerar m ON m.cname = t.cname AND t.mx = m.avg
;

 cname  | wmname |          mx           
--------+--------+------------------------
 canada | zoro   |     2.0000000000000000
 spain  | usopp  |     5.0000000000000000

But you may also use window functions, which looks simpler:

SELECT cname, wmname, MAX(avg) OVER (PARTITION BY cname) AS mx
FROM makerar
;

The only thing with this method is that it will show all records (window functions do not group). But it will show the correct (i.e. maxed at cname level) MAX for the country in each row, so it's up to you:

 cname  | wmname |          mx           
--------+--------+------------------------
 canada | zoro   |     2.0000000000000000
 spain  | luffy  |     5.0000000000000000
 spain  | usopp  |     5.0000000000000000

The solution, arguably less elegant, to show the only (cname, wmname) tuples matching the max value, is:

SELECT DISTINCT /* distinct here matters, because maybe there are various tuples for the same max value */
    m.cname, m.wmname, t.avg AS mx
FROM (
    SELECT cname, wmname, avg, ROW_NUMBER() OVER (PARTITION BY avg DESC) AS rn 
    FROM makerar
) t JOIN makerar m ON m.cname = t.cname AND m.wmname = t.wmname AND t.rn = 1
;


 cname  | wmname |          mx           
--------+--------+------------------------
 canada | zoro   |     2.0000000000000000
 spain  | usopp  |     5.0000000000000000

[*]: Interestingly enough, even though the spec sort of allows to select non-grouped fields, major engines seem to not really like it. Oracle and SQLServer just don't allow this at all. Mysql used to allow it by default, but now since 5.7 the administrator needs to enable this option (ONLY_FULL_GROUP_BY) manually in the server configuration for this feature to be supported...

batch file to list folders within a folder to one level

print all folders name where batch script file is kept

for /d %%d in (*.*) do (
    set test=%%d
    echo !test!
)
pause

How can I show an element that has display: none in a CSS rule?

I can see that you want to write you own short javascript for this, but have you considered to use Frameworks for HTML manipulation instead? jQuery is my prefered tool for such a task, eventhough its an overkill for your current question as it has SO many extra functionalities.

Have a look at jQuery here

Select count(*) from multiple tables

select (select count() from tab1 where field like 'value') + (select count() from tab2 where field like 'value') count

Why javascript getTime() is not a function?

That's because your dat1 and dat2 variables are just strings.

You should parse them to get a Date object, for that format I always use the following function:

// parse a date in yyyy-mm-dd format
function parseDate(input) {
  var parts = input.match(/(\d+)/g);
  // new Date(year, month [, date [, hours[, minutes[, seconds[, ms]]]]])
  return new Date(parts[0], parts[1]-1, parts[2]); // months are 0-based
}

I use this function because the Date.parse(string) (or new Date(string)) method is implementation dependent, and the yyyy-MM-dd format will work on modern browser but not on IE, so I prefer doing it manually.

How can I tell when HttpClient has timed out?

I am reproducing the same issue and it's really annoying. I've found these useful:

HttpClient - dealing with aggregate exceptions

Bug in HttpClient.GetAsync should throw WebException, not TaskCanceledException

Some code in case the links go nowhere:

var c = new HttpClient();
c.Timeout = TimeSpan.FromMilliseconds(10);
var cts = new CancellationTokenSource();
try
{
    var x = await c.GetAsync("http://linqpad.net", cts.Token);  
}
catch(WebException ex)
{
    // handle web exception
}
catch(TaskCanceledException ex)
{
    if(ex.CancellationToken == cts.Token)
    {
        // a real cancellation, triggered by the caller
    }
    else
    {
        // a web request timeout (possibly other things!?)
    }
}

How do I partially update an object in MongoDB so the new object will overlay / merge with the existing one

Make an update object with the property names including the necessary dot path. ("somekey."+ from OP's example), and then use that do the update.

//the modification that's requested
updateReq = { 
   param2 : "val2_new",
   param3 : "val3_new"   
}

//build a renamed version of the update request
var update = {};
for(var field in updateReq){
    update["somekey."+field] = updateReq[field];
}

//apply the update without modifying fields not originally in the update
db.collection.update({._id:...},{$set:update},{upsert:true},function(err,result){...});

"cannot be used as a function error"

#include "header.h"

int estimatedPopulation (int currentPopulation, float growthRate)
{
    return currentPopulation + currentPopulation * growthRate  / 100;
}

HTML inside Twitter Bootstrap popover

You need to create a popover instance that has the html option enabled (place this in your javascript file after the popover JS code):

$('.popover-with-html').popover({ html : true });

What's the difference between "2*2" and "2**2" in Python?

The ** operator in Python is really "power;" that is, 2**3 = 8.

How to discover number of *logical* cores on Mac OS X?

Use the system_profiler | grep "Cores" command.

I have a:

MacBook Pro Retina, Mid 2012.

Processor: 2.6 GHz Intel Core i7

user$ system_profiler | grep "Cores"
      Total Number of Cores: 4

user$ sysctl -n hw.ncpu
8

According to Wikipedia, (http://en.wikipedia.org/wiki/Intel_Core#Core_i7) there is no Core i7 with 8 physical cores so the Hyperthreading idea must be the case. Ignore sysctl and use the system_profiler value for accuracy. The real question is whether or not you can efficiently run applications with 4 cores (long compile jobs?) without interrupting other processes.

Running a compiler parallelized with 4 cores doesn't appear to dramatically affect regular OS operations. So perhaps treating it as 8 cores is not so bad.

changing textbox border colour using javascript

I'm agree with Vicente Plata you should try using jQuery IMHO is the best javascript library. You can create a class in your CSS file and just do the following with jquery:

$('#fName').addClass('name_of_the_class'); 

and that's all, and of course you won't be worried about incompatibility of the browsers, that's jquery's team problem :D LOL

Bootstrap - floating navbar button right

In bootstrap 4 use:

<ul class="nav navbar-nav ml-auto">

This will push the navbar to the right. Use mr-auto to push it to the left, this is the default behaviour.

Passing data from controller to view in Laravel

$books[] = [
            'title' => 'Mytitle',
            'author' => 'MyAuthor,
            
        ];

//pass data to other view
return view('myView.blade.php')->with('books');
or
return view('myView.blade.php','books');
or
return view('myView.blade.php',compact('books'));

----------------------------------------------------


//to use this on myView.blade.php
<script>
    myVariable = {!! json_encode($books) !!};
    console.log(myVariable);
</script>

How to Check if value exists in a MySQL database

I tried to d this for a while and $sqlcommand = 'SELECT * FROM database WHERE search="'.$searchString.'";';
$sth = $db->prepare($sqlcommand); $sth->execute(); $record = $sth->fetch(); if ($sth->fetchColumn() > 0){}
just works if there are TWO identical entries, but, if you replace if ($sth->fetchColumn() > 0){} with if ($result){} it works with only one matching record, hope this helps.

I get "Http failure response for (unknown url): 0 Unknown Error" instead of actual error message in Angular

For me it was caused by a server side JsonSerializerException.

An unhandled exception has occurred while executing the request Newtonsoft.Json.JsonSerializationException: Self referencing loop detected with type ...

The client said:

POST http://localhost:61495/api/Action net::ERR_INCOMPLETE_CHUNKED_ENCODING
ERROR HttpErrorResponse {headers: HttpHeaders, status: 0, statusText: "Unknown Error", url: null, ok: false, …}

Making the response type simpler by eliminating the loops solved the problem.

How do I add a library (android-support-v7-appcompat) in IntelliJ IDEA

This is my solution, it is very similar to the previous one:

<dependency>
        <groupId>com.google.android</groupId>
        <artifactId>support-v7</artifactId>
        <scope>system</scope>
        <systemPath>${android.home}/support/v7/appcompat/libs/android-support-v7-appcompat.jar</systemPath>
        <version>19.0.1</version>
</dependency>

Where {android.home} is the root directory of the Android SDK and it uses systemPath instead of repository.

How to remove the URL from the printing page?

@media print {
    #Header, #Footer { display: none !important; }
}

Check this link

PHP Warning: POST Content-Length of 8978294 bytes exceeds the limit of 8388608 bytes in Unknown on line 0

1. First u will find the php.ini file.

u can find php.ini file from this path. C:\xampp\php or from xampp folder.

2. Now open php.ini file and change the following:

1. post-max-size (change 8M to 800M).

2. upload-max-filesize (change 2M to 2000M).

3. Now stop the Apache server and MySQL.

4. Now restart Apache server and MySQL.

It worked fine after that.

Enjoy ur working now :)

How to get distinct values from an array of objects in JavaScript?

If this were PHP I'd build an array with the keys and take array_keys at the end, but JS has no such luxury. Instead, try this:

var flags = [], output = [], l = array.length, i;
for( i=0; i<l; i++) {
    if( flags[array[i].age]) continue;
    flags[array[i].age] = true;
    output.push(array[i].age);
}

how to get rid of notification circle in right side of the screen?

This stuff comes from ES file explorer

Just go into this app > settings

Then there is an option that says logging floating window, you just need to disable that and you will get rid of this infernal bubble for good

git revert back to certain commit

git reset --hard 4a155e5 Will move the HEAD back to where you want to be. There may be other references ahead of that time that you would need to remove if you don't want anything to point to the history you just deleted.

What is a database transaction?

In addition to the above responses, it should be noted that there is, at least in theory, no restriction whatsoever as to what kind of resources are involved in a transaction.

Most of the time, it is just a database, or multiple distinct databases, but it is also conceivable that a printer takes part in a transaction, and can cause that transaction to fail, say in the event of a paper jam.

Anaconda export Environment file

The easiest way to save the packages from an environment to be installed in another computer is:

$ conda list -e > req.txt

then you can install the environment using

$ conda create -n <environment-name> --file req.txt

if you use pip, please use the following commands: reference https://pip.pypa.io/en/stable/reference/pip_freeze/

$ env1/bin/pip freeze > requirements.txt
$ env2/bin/pip install -r requirements.txt

Autoincrement VersionCode with gradle extra properties

There are two solutions I really like. The first depends on the Play Store and the other depends on Git.

Using the Play Store, you can increment the version code by looking at the highest available uploaded version code. The benefit of this solution is that an APK upload will never fail since your version code is always one higher than whatever is on the Play Store. The downside is that distributing your APK outside of the Play Store becomes more difficult. You can set this up using Gradle Play Publisher by following the quickstart guide and telling the plugin to resolve version codes automatically:

plugins {
    id 'com.android.application'
    id 'com.github.triplet.play' version 'x.x.x'
}

android {
    ...
}

play {
    serviceAccountCredentials = file("your-credentials.json")
    resolutionStrategy = "auto"
}

Using Git, you can increment the version code based on how many commits and tags your repository has. The benefit here is that your output is reproducible and doesn't depend on anything outside your repo. The downside is that you have to make a new commit or tag to bump your version code. You can set this up by adding the Version Master Gradle plugin:

plugins {
    id 'com.android.application'
    id 'com.supercilex.gradle.versions' version 'x.x.x'
}

android {
    ...
}

How to find the logs on android studio?

C:\Users\bob.AndroidStudio2.3\system\log

SQL Error: ORA-00913: too many values

The 00947 message indicates that the record which you are trying to send to Oracle lacks one or more of the columns which was included at the time the table was created. The 00913 message indicates that the record which you are trying to send to Oracle includes more columns than were included at the time the table was created. You just need to check the number of columns and its type in both the tables ie the tables that are involved in the sql.

How to switch to another domain and get-aduser

Try specifying a DC in DomainB using the -Server property. Ex:

Get-ADUser -Server "dc01.DomainB.local" -Filter {EmailAddress -like "*Smith_Karla*"} -Properties EmailAddress

Java check if boolean is null

boolean is a primitive data type in Java and primitive data types can not be null like other primitives int, float etc, they should be containing default values if not assigned.

In Java, only objects can assigned to null, it means the corresponding object has no reference and so does not contain any representation in memory.

Hence If you want to work with object as null , you should be using Boolean class which wraps a primitive boolean type value inside its object.

These are called wrapper classes in Java

For Example:

Boolean bool = readValue(...); // Read Your Value
if (bool  == null) { do This ...}

Do I really need to encode '&' as '&amp;'?

Yes. Just as the error said, in HTML, attributes are #PCDATA meaning they're parsed. This means you can use character entities in the attributes. Using & by itself is wrong and if not for lenient browsers and the fact that this is HTML not XHTML, would break the parsing. Just escape it as &amp; and everything would be fine.

HTML5 allows you to leave it unescaped, but only when the data that follows does not look like a valid character reference. However, it's better just to escape all instances of this symbol than worry about which ones should be and which ones don't need to be.

Keep this point in mind; if you're not escaping & to &amp;, it's bad enough for data that you create (where the code could very well be invalid), you might also not be escaping tag delimiters, which is a huge problem for user-submitted data, which could very well lead to HTML and script injection, cookie stealing and other exploits.

Please just escape your code. It will save you a lot of trouble in the future.

printf() prints whole array

But still, the memory address for each letter in this address is different.

Memory address is different but as its array of characters they are sequential. When you pass address of first element and use %s, printf will print all characters starting from given address until it finds '\0'.

c++ exception : throwing std::string

In addition to probably throwing something derived from std::exception you should throw anonymous temporaries and catch by reference:

void Foo::Bar(){
  if(!QueryPerformanceTimer(&m_baz)){
    throw std::string("it's the end of the world!");
  }
}

void Foo:Caller(){
  try{
    this->Bar();// should throw
  }catch(std::string& caught){ // not quite sure the syntax is ok here...
    std::cout<<"Got "<<caught<<std::endl;
  }
}
  • You should throw anonymous temporaries so the compiler deals with the object lifetime of whatever you're throwing - if you throw something new-ed off the heap, someone else needs to free the thing.
  • You should catch references to prevent object slicing

.

See Meyer's "Effective C++ - 3rd edition" for details or visit https://www.securecoding.cert.org/.../ERR02-A.+Throw+anonymous+temporaries+and+catch+by+reference

Node: log in a file instead of the console

Straight from nodejs's API docs on Console

const output = fs.createWriteStream('./stdout.log');
const errorOutput = fs.createWriteStream('./stderr.log');
// custom simple logger
const logger = new Console(output, errorOutput);
// use it like console
const count = 5;
logger.log('count: %d', count);
// in stdout.log: count 5

How to join on multiple columns in Pyspark?

An alternative approach would be:

df1 = sqlContext.createDataFrame(
    [(1, "a", 2.0), (2, "b", 3.0), (3, "c", 3.0)],
    ("x1", "x2", "x3"))

df2 = sqlContext.createDataFrame(
    [(1, "f", -1.0), (2, "b", 0.0)], ("x1", "x2", "x4"))

df = df1.join(df2, ['x1','x2'])
df.show()

which outputs:

+---+---+---+---+
| x1| x2| x3| x4|
+---+---+---+---+
|  2|  b|3.0|0.0|
+---+---+---+---+

With the main advantage being that the columns on which the tables are joined are not duplicated in the output, reducing the risk of encountering errors such as org.apache.spark.sql.AnalysisException: Reference 'x1' is ambiguous, could be: x1#50L, x1#57L.


Whenever the columns in the two tables have different names, (let's say in the example above, df2 has the columns y1, y2 and y4), you could use the following syntax:

df = df1.join(df2.withColumnRenamed('y1','x1').withColumnRenamed('y2','x2'), ['x1','x2'])

Command to get time in milliseconds

Nano is 10-9 and milli 10-3. Hence, we can use the three first characters of nanoseconds to get the milliseconds:

date +%s%3N

From man date:

%N nanoseconds (000000000..999999999)

%s seconds since 1970-01-01 00:00:00 UTC

Source: Server Fault's How do I get the current Unix time in milliseconds in Bash?.

Memory address of an object in C#

You can use GCHandleType.Weak instead of Pinned. On the other hand, there is another way to get a pointer to an object:

object o = new object();
TypedReference tr = __makeref(o);
IntPtr ptr = **(IntPtr**)(&tr);

Requires unsafe block and is very, very dangerous and should not be used at all. ?


Back in the day when by-ref locals weren't possible in C#, there was one undocumented mechanism that could accomplish a similar thing – __makeref.

object o = new object();
ref object r = ref o;
//roughly equivalent to
TypedReference tr = __makeref(o);

There is one important difference in that TypedReference is "generic"; it can be used to store a reference to a variable of any type. Accessing such a reference requires to specify its type, e.g. __refvalue(tr, object), and if it doesn't match, an exception is thrown.

To implement the type checking, TypedReference must have two fields, one with the actual address to the variable, and one with a pointer to its type representation. It just so happens that the address is the first field.

Therefore, __makeref is used first to obtain a reference to the variable o. The cast (IntPtr**)(&tr) treats the structure as an array (represented via a pointer) of IntPtr* (pointers to a generic pointer type), accessed via a pointer to it. The pointer is first dereferenced to obtain the first field, then the pointer there is dereferenced again to obtain the value actually stored in the variable o – the pointer to the object itself.

However, since 2012, I have come up with a better and safer solution:

public static class ReferenceHelpers
{
    public static readonly Action<object, Action<IntPtr>> GetPinnedPtr;

    static ReferenceHelpers()
    {
        var dyn = new DynamicMethod("GetPinnedPtr", typeof(void), new[] { typeof(object), typeof(Action<IntPtr>) }, typeof(ReferenceHelpers).Module);
        var il = dyn.GetILGenerator();
        il.DeclareLocal(typeof(object), true);
        il.Emit(OpCodes.Ldarg_0);
        il.Emit(OpCodes.Stloc_0);
        il.Emit(OpCodes.Ldarg_1);
        il.Emit(OpCodes.Ldloc_0);
        il.Emit(OpCodes.Conv_I);
        il.Emit(OpCodes.Call, typeof(Action<IntPtr>).GetMethod("Invoke"));
        il.Emit(OpCodes.Ret);
        GetPinnedPtr = (Action<object, Action<IntPtr>>)dyn.CreateDelegate(typeof(Action<object, Action<IntPtr>>));
    }
}

This creates a dynamic method that first pins the object (so its storage doesn't move in the managed heap), then executes a delegate that receives its address. During the execution of the delegate, the object is still pinned and thus safe to be manipulated via the pointer:

object o = new object();
ReferenceHelpers.GetPinnedPtr(o, ptr => Console.WriteLine(Marshal.ReadIntPtr(ptr) == typeof(object).TypeHandle.Value)); //the first pointer in the managed object header in .NET points to its run-time type info

This is the easiest way to pin an object, since GCHandle requires the type to be blittable in order to pin it. It has the advantage of not using implementation details, undocumented keywords and memory hacking.

MySQL compare DATE string with string from DATETIME field

SELECT * FROM `calendar` WHERE startTime like '2010-04-29%'

You can also use comparison operators on MySQL dates if you want to find something after or before. This is because they are written in such a way (largest value to smallest with leading zeros) that a simple string sort will sort them correctly.

Refreshing page on click of a button

Works for every browser.

<button type="button" onClick="Refresh()">Close</button>

<script>
    function Refresh() {
        window.parent.location = window.parent.location.href;
    }
</script>

PHP PDO with foreach and fetch

$users = $dbh->query($sql);
foreach ($users as $row) {
    print $row["name"] . "-" . $row["sex"] ."<br/>";
}
foreach ($users as $row) {
    print $row["name"] . "-" . $row["sex"] ."<br/>";
}

Here $users is a PDOStatement object over which you can iterate. The first iteration outputs all results, the second does nothing since you can only iterate over the result once. That's because the data is being streamed from the database and iterating over the result with foreach is essentially shorthand for:

while ($row = $users->fetch()) ...

Once you've completed that loop, you need to reset the cursor on the database side before you can loop over it again.

$users = $dbh->query($sql);
foreach ($users as $row) {
    print $row["name"] . "-" . $row["sex"] ."<br/>";
}
echo "<br/>";
$result = $users->fetch(PDO::FETCH_ASSOC);
foreach($result as $key => $value) {
    echo $key . "-" . $value . "<br/>";
}

Here all results are being output by the first loop. The call to fetch will return false, since you have already exhausted the result set (see above), so you get an error trying to loop over false.

In the last example you are simply fetching the first result row and are looping over it.

What is the ellipsis (...) for in this method signature?

The three dot (...) notation is actually borrowed from mathematics, and it means "...and so on".

As for its use in Java, it stands for varargs, meaning that any number of arguments can be added to the method call. The only limitations are that the varargs must be at the end of the method signature and there can only be one per method.

When to use window.opener / window.parent / window.top

I think you need to add some context to your question. However, basic information about these things can be found here:

window.opener https://developer.mozilla.org/en-US/docs/Web/API/Window.opener

I've used window.opener mostly when opening a new window that acted as a dialog which required user input, and needed to pass information back to the main window. However this is restricted by origin policy, so you need to ensure both the content from the dialog and the opener window are loaded from the same origin.

window.parent https://developer.mozilla.org/en-US/docs/Web/API/Window.parent

I've used this mostly when working with IFrames that need to communicate with the window object that contains them.

window.top https://developer.mozilla.org/en-US/docs/Web/API/Window.top

This is useful for ensuring you are interacting with the top level browser window. You can use it for preventing another site from iframing your website, among other things.

If you add some more detail to your question, I can supply other more relevant examples.

UPDATE: There are a few ways you can handle your situation.
You have the following structure:

  • Main Window
    • Dialog 1
      • Dialog 2 Opened By Dialog 1

When Dialog 1 runs the code to open Dialog 2, after creating Dialog 2, have dialog 1 set a property on Dialog 2 that references the Dialog1 opener.

So if "childwindow" is you variable for the dialog 2 window object, and "window" is the variable for the Dialog 1 window object. After opening dialog 2, but before closing dialog 1 make an assignment similar to this:

childwindow.appMainWindow = window.opener

After making the assignment above, close dialog 1. Then from the code running inside dialog2, you should be able to use window.appMainWindow to reference the main window, window object.

Hope this helps.

How to add one column into existing SQL Table

The syntax you need is

ALTER TABLE Products ADD LastUpdate  varchar(200) NULL

This is a metadata only operation

Passing event and argument to v-on in Vue.js

Depending on what arguments you need to pass, especially for custom event handlers, you can do something like this:

<div @customEvent='(arg1) => myCallback(arg1, arg2)'>Hello!</div>

Laravel Fluent Query Builder Join with subquery

Ok for all of you out there that arrived here in desperation searching for the same problem. I hope you will find this quicker then I did ;O.

This is how it is solved. JoostK told me at github that "the first argument to join is the table (or data) you're joining.". And he was right.

Here is the code. Different table and names but you will get the idea right? It t

DB::table('users')
        ->select('first_name', 'TotalCatches.*')

        ->join(DB::raw('(SELECT user_id, COUNT(user_id) TotalCatch,
               DATEDIFF(NOW(), MIN(created_at)) Days,
               COUNT(user_id)/DATEDIFF(NOW(), MIN(created_at))
               CatchesPerDay FROM `catch-text` GROUP BY user_id)
               TotalCatches'), 
        function($join)
        {
           $join->on('users.id', '=', 'TotalCatches.user_id');
        })
        ->orderBy('TotalCatches.CatchesPerDay', 'DESC')
        ->get();

Styling mat-select in Angular Material

Put your class name on the mat-form-field element. This works for all inputs.

How to check for null in a single statement in scala?

If it instead returned Option[QueueObject] you could use a construct like getObject.foreach { QueueManager.add }. You can wrap it right inline with Option(getObject).foreach ... because Option[QueueObject](null) is None.

Is there an easy way to convert jquery code to javascript?

I can see a reason, unrelated to the original post, to automatically compile jQuery code into standard JavaScript:

16k -- or whatever the gzipped, minified jQuery library is -- might be too much for your website that is intended for a mobile browser. The w3c is recommending that all HTTP requests for mobile websites should be a maximum of 20k.

w3c specs for mobile

So I enjoy coding in my nice, terse, chained jQuery. But now I need to optimize for mobile. Should I really go back and do the difficult, tedious work of rewriting all the helper functions I used in the jQuery library? Or is there some kind of convenient app that will help me recompile?

That would be very sweet. Sadly, I don't think such a thing exists.

How to parse JSON in Kotlin?

This uses kotlinx.serialization like Elisha's answer. Meanwhile the API is being stabilized for the upcoming 1.0 release. Note that e.g. JSON.parse was renamed to Json.parse and is now Json.decodeFromString. Also it is imported in gradle differently starting in Kotlin 1.4.0:

dependencies {
    implementation "org.jetbrains.kotlinx:kotlinx-serialization-core:1.0.0-RC"
}
apply plugin: 'kotlinx-serialization'

Example usage:

@Serializable
data class Properties(val nid: Int, val tid: Int)
@Serializable
data class Feature(val pos: List<Double>, val properties: Properties? = null, 
    val count: Int? = null)
@Serializable
data class Root(val features: List<Feature>)


val root = Json.decodeFromString<Root>(jsonStr)
val rootAlt = Json.decodeFromString(Root.serializer(), jsonStr)  // equivalent

val str = Json.encodeToString(root)  // type 'Root' can be inferred!

// For a *top-level* list (does not apply in my case) you would use 
val fList = Json.decodeFromString<List<Feature>>(jsonStr)
val fListAlt = Json.decodeFromString(ListSerializer(Feature.serializer()), jsonStr)

Kotlin's data class defines a class that mainly holds data and has .toString() and other methods (e.g. destructuring declarations) automatically defined. I'm using nullable (?) types here for optional fields.

OAuth2 and Google API: access token expiration time?

You shouldn't design your application based on specific lifetimes of access tokens. Just assume they are (very) short lived.

However, after a successful completion of the OAuth2 installed application flow, you will get back a refresh token. This refresh token never expires, and you can use it to exchange it for an access token as needed. Save the refresh tokens, and use them to get access tokens on-demand (which should then immediately be used to get access to user data).

EDIT: My comments above notwithstanding, there are two easy ways to get the access token expiration time:

  1. It is a parameter in the response (expires_in)when you exchange your refresh token (using /o/oauth2/token endpoint). More details.
  2. There is also an API that returns the remaining lifetime of the access_token:

    https://www.googleapis.com/oauth2/v1/tokeninfo?access_token={accessToken}

    This will return a json array that will contain an expires_in parameter, which is the number of seconds left in the lifetime of the token.

MySQL COUNT DISTINCT

You need to use a group by clause.

SELECT  site_id, MAX(ts) as TIME, count(*) group by site_id

How to prevent Browser cache for php site

I had problem with caching my css files. Setting headers in PHP didn't help me (perhaps because the headers would need to be set in the stylesheet file instead of the page linking to it?).

I found the solution on this page: https://css-tricks.com/can-we-prevent-css-caching/

The solution:

Append timestamp as the query part of the URI for the linked file.
(Can be used for css, js, images etc.)

For development:

<link rel="stylesheet" href="style.css?<?php echo date('Y-m-d_H:i:s'); ?>">

For production (where caching is mostly a good thing):

<link rel="stylesheet" type="text/css" href="style.css?version=3.2">
(and rewrite manually when it is required)

Or combination of these two:

<?php
    define( "DEBUGGING", true ); // or false in production enviroment
?>
<!-- ... -->
<link rel="stylesheet" type="text/css" href="style.css?version=3.2<?php echo (DEBUGGING) ? date('_Y-m-d_H:i:s') : ""; ?>">

EDIT:

Or prettier combination of those two:

<?php
    // Init
    define( "DEBUGGING", true ); // or false in production enviroment
    // Functions
    function get_cache_prevent_string( $always = false ) {
        return (DEBUGGING || $always) ? date('_Y-m-d_H:i:s') : "";
    }
?>
<!-- ... -->
<link rel="stylesheet" type="text/css" href="style.css?version=3.2<?php echo get_cache_prevent_string(); ?>">

How to install the Raspberry Pi cross compiler on my Linux host machine?

I couldn't get the compiler (x64 version) to use the sysroot until I added SET(CMAKE_SYSROOT $ENV{HOME}/raspberrypi/rootfs) to pi.cmake.

How to select the last record of a table in SQL?

Without any further information, which Database etc the best we can do is something like

Sql Server

SELECT TOP 1 * FROM Table ORDER BY ID DESC

MySql

SELECT * FROM Table ORDER BY ID DESC LIMIT 1

transparent navigation bar ios

For those looking for OBJC solution, to be added in App Delegate didFinishLaunchingWithOptions method:

[[UINavigationBar appearance] setBackgroundImage:[UIImage new] forBarMetrics:UIBarMetricsDefault];
[UINavigationBar appearance].shadowImage = [UIImage new];
[UINavigationBar appearance].backgroundColor = [UIColor clearColor];
[UINavigationBar appearance].translucent = YES;

latex large division sign in a math formula

I found the answer I was looking for. The thing to use here is the construct of

\left \middle \right

For example, in this case, two possible solutions are:

$\left( {\frac{a_1}{a_2}} \middle/ {\frac{b_1}{b_2}} \right) $

Or, in case the brackets are not necessary:

$\left. {\frac{a_1}{a_2}} \middle/ {\frac{b_1}{b_2}} \right. $

How to convert wstring into string?

There are two issues with the code:

  1. The conversion in const std::string s( ws.begin(), ws.end() ); is not required to correctly map the wide characters to their narrow counterpart. Most likely, each wide character will just be typecast to char.
    The resolution to this problem is already given in the answer by kem and involves the narrow function of the locale's ctype facet.

  2. You are writing output to both std::cout and std::wcout in the same program. Both cout and wcout are associated with the same stream (stdout) and the results of using the same stream both as a byte-oriented stream (as cout does) and a wide-oriented stream (as wcout does) are not defined.
    The best option is to avoid mixing narrow and wide output to the same (underlying) stream. For stdout/cout/wcout, you can try switching the orientation of stdout when switching between wide and narrow output (or vice versa):

    #include <iostream>
    #include <stdio.h>
    #include <wchar.h>
    
    int main() {
        std::cout << "narrow" << std::endl;
        fwide(stdout, 1); // switch to wide
        std::wcout << L"wide" << std::endl;
        fwide(stdout, -1); // switch to narrow
        std::cout << "narrow" << std::endl;
        fwide(stdout, 1); // switch to wide
        std::wcout << L"wide" << std::endl;
    }
    

Multiline editing in Visual Studio Code

(NO MOUSE) For macOS, I found this to be very quick!

  1. CMD + f To search the (word) you want to change.
  2. Option + Enter To select all word you search for.

Just update the first word and it will update all the selected.

Insert multiple rows into single column

INSERT INTO hr.employees (location_id) VALUE (1000) WHERE first_name LIKE '%D%';

let me know if there is any problem in this statement.

Could not find a base address that matches scheme https for the endpoint with binding WebHttpBinding. Registered base address schemes are [http]

I solved the issue by adding https binding in my IIS websites and adding 443 SSL port and selecting a self signed certificate in binding.

enter image description here

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

The original post might have been true back in 2009, but now it is actually incorrect now, and no linking is even required for the stylesheet as I see mentioned in some of the other responses. Rails will now do this for you by default.

  • Place any new sheet .css (or other) in app/assets/stylesheets
  • Test your server with rails-root/scripts/rails server and you'll see the link is added by rails itself.

You can test this with a path in your browser like testserverpath:3000/assets/filename_to_test.css?body=1

Removing carriage return and new-line from the end of a string in c#

This is what I got to work for me.

s.Replace("\r","").Replace("\n","")

Hide "NFC Tag type not supported" error on Samsung Galaxy devices

Before Android 4.4

What you are trying to do is simply not possible from an app (at least not on a non-rooted/non-modified device). The message "NFC tag type not supported" is displayed by the Android system (or more specifically the NFC system service) before and instead of dispatching the tag to your app. This means that the NFC system service filters MIFARE Classic tags and never notifies any app about them. Consequently, your app can't detect MIFARE Classic tags or circumvent that popup message.

On a rooted device, you may be able to bypass the message using either

  1. Xposed to modify the behavior of the NFC service, or
  2. the CSC (Consumer Software Customization) feature configuration files on the system partition (see /system/csc/. The NFC system service disables the popup and dispatches MIFARE Classic tags to apps if the CSC feature <CscFeature_NFC_EnableSecurityPromptPopup> is set to any value but "mifareclassic" or "all". For instance, you could use:

    <CscFeature_NFC_EnableSecurityPromptPopup>NONE</CscFeature_NFC_EnableSecurityPromptPopup>
    

    You could add this entry to, for instance, the file "/system/csc/others.xml" (within the section <FeatureSet> ... </FeatureSet> that already exists in that file).

Since, you asked for the Galaxy S6 (the question that you linked) as well: I have tested this method on the S4 when it came out. I have not verified if this still works in the latest firmware or on other devices (e.g. the S6).

Since Android 4.4

This is pure guessing, but according to this (link no longer available), it seems that some apps (e.g. NXP TagInfo) are capable of detecting MIFARE Classic tags on affected Samsung devices since Android 4.4. This might mean that foreground apps are capable of bypassing that popup using the reader-mode API (see NfcAdapter.enableReaderMode) possibly in combination with NfcAdapter.FLAG_READER_SKIP_NDEF_CHECK.

Tree view of a directory/folder in Windows?

If it is just viewing in tree view,One workaround is to use the Explorer in Notepad++ or any other tools.

How do the post increment (i++) and pre increment (++i) operators work in Java?

In the above example

int a = 5,i;

i=++a + ++a + a++;        //Ans: i = 6 + 7 + 7 = 20 then a = 8 

i=a++ + ++a + ++a;        //Ans: i = 8 + 10 + 11 = 29 then a = 11

a=++a + ++a + a++;        //Ans: a = 12 + 13 + 13 = 38

System.out.println(a);    //Ans: a = 38

System.out.println(i);    //Ans: i = 29

Writing String to Stream and reading it back does not work

You need to reset the stream to the beginning:

stringAsStream.Seek(0, SeekOrigin.Begin);
Console.WriteLine("Differs from:\t" + (char)stringAsStream.ReadByte());

This can also be done by setting the Position property to 0:

stringAsStream.Position = 0

How to run test methods in specific order in JUnit4?

What you want is perfectly reasonable when test cases are being run as a suite.

Unfortunately no time to give a complete solution right now, but have a look at class:

org.junit.runners.Suite

Which allows you to call test cases (from any test class) in a specific order.

These might be used to create functional, integration or system tests.

This leaves your unit tests as they are without specific order (as recommended), whether you run them like that or not, and then re-use the tests as part of a bigger picture.

We re-use/inherit the same code for unit, integration and system tests, sometimes data driven, sometimes commit driven, and sometimes run as a suite.

How do I generate a constructor from class fields using Visual Studio (and/or ReSharper)?

Here is a macro that I use for that purpose. It will generate a constructor from fields and properties that have a private setter.

Imports System
Imports EnvDTE
Imports EnvDTE80
Imports EnvDTE90
Imports EnvDTE90a
Imports EnvDTE100
Imports System.Diagnostics
Imports System.Collections.Generic

Public Module Temp

    Sub AddConstructorFromFields()
        DTE.UndoContext.Open("Add constructor from fields")

        Dim classElement As CodeClass, index As Integer
        GetClassAndInsertionIndex(classElement, index)

        Dim constructor As CodeFunction
        constructor = classElement.AddFunction(classElement.Name, vsCMFunction.vsCMFunctionConstructor, vsCMTypeRef.vsCMTypeRefVoid, index, vsCMAccess.vsCMAccessPublic)

        Dim visitedNames As New Dictionary(Of String, String)
        Dim element As CodeElement, parameterPosition As Integer, isFirst As Boolean = True
        For Each element In classElement.Children
            Dim fieldType As String
            Dim fieldName As String
            Dim parameterName As String

            Select Case element.Kind
                Case vsCMElement.vsCMElementVariable
                    Dim field As CodeVariable = CType(element, CodeVariable)
                    fieldType = field.Type.AsString
                    fieldName = field.Name
                    parameterName = field.Name.TrimStart("_".ToCharArray())

                Case vsCMElement.vsCMElementProperty
                    Dim field As CodeProperty = CType(element, CodeProperty)
                    If field.Setter.Access = vsCMAccess.vsCMAccessPrivate Then
                        fieldType = field.Type.AsString
                        fieldName = field.Name
                        parameterName = field.Name.Substring(0, 1).ToLower() + field.Name.Substring(1)
                    End If
            End Select

            If Not String.IsNullOrEmpty(parameterName) And Not visitedNames.ContainsKey(parameterName) Then
                visitedNames.Add(parameterName, parameterName)

                constructor.AddParameter(parameterName, fieldType, parameterPosition)

                Dim endPoint As EditPoint
                endPoint = constructor.EndPoint.CreateEditPoint()
                endPoint.LineUp()
                endPoint.EndOfLine()

                If Not isFirst Then
                    endPoint.Insert(Environment.NewLine)
                Else
                    isFirst = False
                End If

                endPoint.Insert(String.Format(MemberAssignmentFormat(constructor.Language), fieldName, parameterName))

                parameterPosition = parameterPosition + 1
            End If
        Next

        DTE.UndoContext.Close()

        Try
            ' This command fails sometimes '
            DTE.ExecuteCommand("Edit.FormatDocument")
        Catch ex As Exception
        End Try
    End Sub
    Private Sub GetClassAndInsertionIndex(ByRef classElement As CodeClass, ByRef index As Integer, Optional ByVal useStartIndex As Boolean = False)
        Dim selection As TextSelection
        selection = CType(DTE.ActiveDocument.Selection, TextSelection)

        classElement = CType(selection.ActivePoint.CodeElement(vsCMElement.vsCMElementClass), CodeClass)

        Dim childElement As CodeElement
        index = 0
        For Each childElement In classElement.Children
            Dim childOffset As Integer
            childOffset = childElement.GetStartPoint(vsCMPart.vsCMPartWholeWithAttributes).AbsoluteCharOffset
            If selection.ActivePoint.AbsoluteCharOffset < childOffset Or useStartIndex Then
                Exit For
            End If
            index = index + 1
        Next
    End Sub
    Private ReadOnly Property MemberAssignmentFormat(ByVal language As String) As String
        Get
            Select Case language
                Case CodeModelLanguageConstants.vsCMLanguageCSharp
                    Return "this.{0} = {1};"

                Case CodeModelLanguageConstants.vsCMLanguageVB
                    Return "Me.{0} = {1}"

                Case Else
                    Return ""
            End Select
        End Get
    End Property
End Module

How to use a servlet filter in Java to change an incoming servlet request url?

  1. Implement javax.servlet.Filter.
  2. In doFilter() method, cast the incoming ServletRequest to HttpServletRequest.
  3. Use HttpServletRequest#getRequestURI() to grab the path.
  4. Use straightforward java.lang.String methods like substring(), split(), concat() and so on to extract the part of interest and compose the new path.
  5. Use either ServletRequest#getRequestDispatcher() and then RequestDispatcher#forward() to forward the request/response to the new URL (server-side redirect, not reflected in browser address bar), or cast the incoming ServletResponse to HttpServletResponse and then HttpServletResponse#sendRedirect() to redirect the response to the new URL (client side redirect, reflected in browser address bar).
  6. Register the filter in web.xml on an url-pattern of /* or /Check_License/*, depending on the context path, or if you're on Servlet 3.0 already, use the @WebFilter annotation for that instead.

Don't forget to add a check in the code if the URL needs to be changed and if not, then just call FilterChain#doFilter(), else it will call itself in an infinite loop.

Alternatively you can also just use an existing 3rd party API to do all the work for you, such as Tuckey's UrlRewriteFilter which can be configured the way as you would do with Apache's mod_rewrite.

Java how to replace 2 or more spaces with single space in string and delete leading and trailing spaces

check this...

public static void main(String[] args) {
    String s = "A B  C   D    E F      G\tH I\rJ\nK\tL";
    System.out.println("Current      : "+s);
    System.out.println("Single Space : "+singleSpace(s));
    System.out.println("Space  count : "+spaceCount(s));
    System.out.format("Replace  all = %s", s.replaceAll("\\s+", ""));

    // Example where it uses the most.
    String s = "My name is yashwanth . M";
    String s2 = "My nameis yashwanth.M";

    System.out.println("Normal  : "+s.equals(s2));
    System.out.println("Replace : "+s.replaceAll("\\s+", "").equals(s2.replaceAll("\\s+", "")));

} 

If String contains only single-space then replace() will not-replace,

If spaces are more than one, Then replace() action performs and removes spacess.

public static String singleSpace(String str){
    return str.replaceAll("  +|   +|\t|\r|\n","");
}

To count the number of spaces in a String.

public static String spaceCount(String str){
    int i = 0;
    while(str.indexOf(" ") > -1){
      //str = str.replaceFirst(" ", ""+(i++));
        str = str.replaceFirst(Pattern.quote(" "), ""+(i++)); 
    }
    return str;
}

Pattern.quote("?") returns literal pattern String.

Counting how many times a certain char appears in a string before any other char appears

You could use the Count method

var count = mystring.Count(x => x == '$')

Parse (split) a string in C++ using string delimiter (standard C++)

You can use the std::string::find() function to find the position of your string delimiter, then use std::string::substr() to get a token.

Example:

std::string s = "scott>=tiger";
std::string delimiter = ">=";
std::string token = s.substr(0, s.find(delimiter)); // token is "scott"
  • The find(const string& str, size_t pos = 0) function returns the position of the first occurrence of str in the string, or npos if the string is not found.

  • The substr(size_t pos = 0, size_t n = npos) function returns a substring of the object, starting at position pos and of length npos.


If you have multiple delimiters, after you have extracted one token, you can remove it (delimiter included) to proceed with subsequent extractions (if you want to preserve the original string, just use s = s.substr(pos + delimiter.length());):

s.erase(0, s.find(delimiter) + delimiter.length());

This way you can easily loop to get each token.

Complete Example

std::string s = "scott>=tiger>=mushroom";
std::string delimiter = ">=";

size_t pos = 0;
std::string token;
while ((pos = s.find(delimiter)) != std::string::npos) {
    token = s.substr(0, pos);
    std::cout << token << std::endl;
    s.erase(0, pos + delimiter.length());
}
std::cout << s << std::endl;

Output:

scott
tiger
mushroom

How to display UTF-8 characters in phpMyAdmin?

First, from the client do

mysql> SHOW VARIABLES LIKE 'character_set%';

This will give you something like

+--------------------------+----------------------------+
| Variable_name            | Value                      |
+--------------------------+----------------------------+
| character_set_client     | latin1                     | 
| character_set_connection | latin1                     | 
| character_set_database   | latin1                     | 
| character_set_filesystem | binary                     | 
| character_set_results    | latin1                     | 
| character_set_server     | latin1                     | 
| character_set_system     | utf8                       | 
| character_sets_dir       | /usr/share/mysql/charsets/ | 
+--------------------------+----------------------------+

where you can inspect the general settings for the client, connection, database

Then you should also inspect the columns from which you are retrieving data with

SHOW CREATE TABLE TableName

and inspecting the charset and collation of CHAR fields (though usually people do not set them explicitly, but it is possible to give CHAR[(length)] [CHARACTER SET charset_name] [COLLATE collation_name] in CREATE TABLE foo ADD COLUMN foo CHAR ...)

I believe that I have listed all relevant settings on the side of mysql. If still getting lost read fine docs and perhaps this question which might shed some light (especially how I though I got it right by looking only at mysql client in the first go).

How to get a list of column names on Sqlite3 database?

In order to get the column information you can use the following snippet:

String sql = "select * from "+oTablename+" LIMIT 0";
Statement statement = connection.createStatement();
ResultSet rs = statement.executeQuery(sql);
ResultSetMetaData mrs = rs.getMetaData();
for(int i = 1; i <= mrs.getColumnCount(); i++)
{
    Object row[] = new Object[3];
    row[0] = mrs.getColumnLabel(i);
    row[1] = mrs.getColumnTypeName(i);
    row[2] = mrs.getPrecision(i);
}

Excel- compare two cell from different sheet, if true copy value from other cell

In your destination field you want to use VLOOKUP like so:

=VLOOKUP(Sheet1!A1:A100,Sheet2!A1:F100,6,FALSE)

VLOOKUP Arguments:

  1. The set fields you want to lookup.
  2. The table range you want to lookup up your value against. The first column of your defined table should be the column you want compared against your lookup field. The table range should also contain the value you want to display (Column F).
  3. This defines what field you want to display upon a match.
  4. FALSE tells VLOOKUP to do an exact match.

How can I view the source code for a function?

UseMethod("t") is telling you that t() is a (S3) generic function that has methods for different object classes.

The S3 method dispatch system

For S3 classes, you can use the methods function to list the methods for a particular generic function or class.

> methods(t)
[1] t.data.frame t.default    t.ts*       

   Non-visible functions are asterisked
> methods(class="ts")
 [1] aggregate.ts     as.data.frame.ts cbind.ts*        cycle.ts*       
 [5] diffinv.ts*      diff.ts          kernapply.ts*    lines.ts        
 [9] monthplot.ts*    na.omit.ts*      Ops.ts*          plot.ts         
[13] print.ts         time.ts*         [<-.ts*          [.ts*           
[17] t.ts*            window<-.ts*     window.ts*      

   Non-visible functions are asterisked

"Non-visible functions are asterisked" means the function is not exported from its package's namespace. You can still view its source code via the ::: function (i.e. stats:::t.ts), or by using getAnywhere(). getAnywhere() is useful because you don't have to know which package the function came from.

> getAnywhere(t.ts)
A single object matching ‘t.ts’ was found
It was found in the following places
  registered S3 method for t from namespace stats
  namespace:stats
with value

function (x) 
{
    cl <- oldClass(x)
    other <- !(cl %in% c("ts", "mts"))
    class(x) <- if (any(other)) 
        cl[other]
    attr(x, "tsp") <- NULL
    t(x)
}
<bytecode: 0x294e410>
<environment: namespace:stats>

The S4 method dispatch system

The S4 system is a newer method dispatch system and is an alternative to the S3 system. Here is an example of an S4 function:

> library(Matrix)
Loading required package: lattice
> chol2inv
standardGeneric for "chol2inv" defined from package "base"

function (x, ...) 
standardGeneric("chol2inv")
<bytecode: 0x000000000eafd790>
<environment: 0x000000000eb06f10>
Methods may be defined for arguments: x
Use  showMethods("chol2inv")  for currently available ones.

The output already offers a lot of information. standardGeneric is an indicator of an S4 function. The method to see defined S4 methods is offered helpfully:

> showMethods(chol2inv)
Function: chol2inv (package base)
x="ANY"
x="CHMfactor"
x="denseMatrix"
x="diagonalMatrix"
x="dtrMatrix"
x="sparseMatrix"

getMethod can be used to see the source code of one of the methods:

> getMethod("chol2inv", "diagonalMatrix")
Method Definition:

function (x, ...) 
{
    chk.s(...)
    tcrossprod(solve(x))
}
<bytecode: 0x000000000ea2cc70>
<environment: namespace:Matrix>

Signatures:
        x               
target  "diagonalMatrix"
defined "diagonalMatrix"

There are also methods with more complex signatures for each method, for example

require(raster)
showMethods(extract)
Function: extract (package raster)
x="Raster", y="data.frame"
x="Raster", y="Extent"
x="Raster", y="matrix"
x="Raster", y="SpatialLines"
x="Raster", y="SpatialPoints"
x="Raster", y="SpatialPolygons"
x="Raster", y="vector"

To see the source code for one of these methods the entire signature must be supplied, e.g.

getMethod("extract" , signature = c( x = "Raster" , y = "SpatialPolygons") )

It will not suffice to supply the partial signature

getMethod("extract",signature="SpatialPolygons")
#Error in getMethod("extract", signature = "SpatialPolygons") : 
#  No method found for function "extract" and signature SpatialPolygons

Functions that call unexported functions

In the case of ts.union, .cbindts and .makeNamesTs are unexported functions from the stats namespace. You can view the source code of unexported functions by using the ::: operator or getAnywhere.

> stats:::.makeNamesTs
function (...) 
{
    l <- as.list(substitute(list(...)))[-1L]
    nm <- names(l)
    fixup <- if (is.null(nm)) 
        seq_along(l)
    else nm == ""
    dep <- sapply(l[fixup], function(x) deparse(x)[1L])
    if (is.null(nm)) 
        return(dep)
    if (any(fixup)) 
        nm[fixup] <- dep
    nm
}
<bytecode: 0x38140d0>
<environment: namespace:stats>

Functions that call compiled code

Note that "compiled" does not refer to byte-compiled R code as created by the compiler package. The <bytecode: 0x294e410> line in the above output indicates that the function is byte-compiled, and you can still view the source from the R command line.

Functions that call .C, .Call, .Fortran, .External, .Internal, or .Primitive are calling entry points in compiled code, so you will have to look at sources of the compiled code if you want to fully understand the function. This GitHub mirror of the R source code is a decent place to start. The function pryr::show_c_source can be a useful tool as it will take you directly to a GitHub page for .Internal and .Primitive calls. Packages may use .C, .Call, .Fortran, and .External; but not .Internal or .Primitive, because these are used to call functions built into the R interpreter.

Calls to some of the above functions may use an object instead of a character string to reference the compiled function. In those cases, the object is of class "NativeSymbolInfo", "RegisteredNativeSymbol", or "NativeSymbol"; and printing the object yields useful information. For example, optim calls .External2(C_optimhess, res$par, fn1, gr1, con) (note that's C_optimhess, not "C_optimhess"). optim is in the stats package, so you can type stats:::C_optimhess to see information about the compiled function being called.

Compiled code in a package

If you want to view compiled code in a package, you will need to download/unpack the package source. The installed binaries are not sufficient. A package's source code is available from the same CRAN (or CRAN compatible) repository that the package was originally installed from. The download.packages() function can get the package source for you.

download.packages(pkgs = "Matrix", 
                  destdir = ".",
                  type = "source")

This will download the source version of the Matrix package and save the corresponding .tar.gz file in the current directory. Source code for compiled functions can be found in the src directory of the uncompressed and untared file. The uncompressing and untaring step can be done outside of R, or from within R using the untar() function. It is possible to combine the download and expansion step into a single call (note that only one package at a time can be downloaded and unpacked in this way):

untar(download.packages(pkgs = "Matrix",
                        destdir = ".",
                        type = "source")[,2])

Alternatively, if the package development is hosted publicly (e.g. via GitHub, R-Forge, or RForge.net), you can probably browse the source code online.

Compiled code in a base package

Certain packages are considered "base" packages. These packages ship with R and their version is locked to the version of R. Examples include base, compiler, stats, and utils. As such, they are not available as separate downloadable packages on CRAN as described above. Rather, they are part of the R source tree in individual package directories under /src/library/. How to access the R source is described in the next section.

Compiled code built into the R interpreter

If you want to view the code built-in to the R interpreter, you will need to download/unpack the R sources; or you can view the sources online via the R Subversion repository or Winston Chang's github mirror.

Uwe Ligges's R news article (PDF) (p. 43) is a good general reference of how to view the source code for .Internal and .Primitive functions. The basic steps are to first look for the function name in src/main/names.c and then search for the "C-entry" name in the files in src/main/*.

How do I set a program to launch at startup

If an application is designed to start when Windows starts (as opposed to when a user logs in), your only option is to involve a Windows Service. Either write the application as a service, or write a simple service that exists only to launch the application.

Writing services can be tricky, and can impose restrictions that may be unacceptable for your particular case. One common design pattern is a front-end/back-end pair, with a service that does the work and an application front-end that communicates with the service to display information to the user.

On the other hand, if you just want your application to start on user login, you can use methods 1 or 2 that Joel Coehoorn listed.

Selenium 2.53 not working on Firefox 47

New Selenium libraries are now out, according to: https://github.com/SeleniumHQ/selenium/issues/2110

The download page http://www.seleniumhq.org/download/ seems not to be updated just yet, but by adding 1 to the minor version in the link, I could download the C# version: http://selenium-release.storage.googleapis.com/2.53/selenium-dotnet-2.53.1.zip

It works for me with Firefox 47.0.1.

As a side note, I was able build just the webdriver.xpi Firefox extension from the master branch in GitHub, by running ./go //javascript/firefox-driver:webdriver:run – which gave an error message but did build the build/javascript/firefox-driver/webdriver.xpi file, which I could rename (to avoid a name clash) and successfully load with the FirefoxProfile.AddExtension method. That was a reasonable workaround without having to rebuild the entire Selenium library.

How to tell if tensorflow is using gpu acceleration from inside python shell?

You have some options to test whether GPU acceleration is being used by your TensorFlow installation.

You can type in the following commands in three different platforms.

import tensorflow as tf
sess = tf.Session(config=tf.ConfigProto(log_device_placement=True))
  1. Jupyter Notebook - Check the console which is running the Jupyter Notebook. You will be able to see the GPU being used.
  2. Python Shell - You will be able to directly see the output. (Note- do not assign the output of the second command to the variable 'sess'; if that helps).
  3. Spyder - Type in the following command in the console.

    import tensorflow as tf tf.test.is_gpu_available()

Keylistener in Javascript

Did you check the small Mousetrap library?

Mousetrap is a simple library for handling keyboard shortcuts in JavaScript.

Ship an application with a database

I wrote a library to simplify this process.

dataBase = new DataBase.Builder(context, "myDb").
//        setAssetsPath(). // default "databases"
//        setDatabaseErrorHandler().
//        setCursorFactory().
//        setUpgradeCallback()
//        setVersion(). // default 1
build();

It will create a dataBase from assets/databases/myDb.db file. In addition you will get all those functionality:

  • Load database from file
  • Synchronized access to the database
  • Using sqlite-android by requery, Android specific distribution of the latest versions of SQLite.

Clone it from github.

Git push error '[remote rejected] master -> master (branch is currently checked out)'

With a few setup steps you can easily deploy changes to your website using a one-liner like

git push production

Which is nice and simple, and you don't have to log into the remote server and do a pull or anything. Note that this will work best if you don't use your production checkout as a working branch! (The OP was working within a slightly different context, and I think @Robert Gould's solution addressed it well. This solution is more appropriate for deployment to a remote server.)

First you need to set up a bare repository somewhere on your server, outside of your webroot.

mkdir mywebsite.git
cd mywebsite.git
git init --bare

Then create file hooks/post-receive:

#!/bin/sh
GIT_WORK_TREE=/path/to/webroot/of/mywebsite git checkout -f

And make the file executable:

chmod +x hooks/post-receive

On your local machine,

git remote add production [email protected]:mywebsite.git
git push production +master:refs/heads/master

All set! Now in the future you can use git push production to deploy your changes!

Credit for this solution goes to http://sebduggan.com/blog/deploy-your-website-changes-using-git/. Look there for a more detailed explanation of what's going on.

Copy all files with a certain extension from all subdirectories

From all of the above, I came up with this version. This version also works for me in the mac recovery terminal.

find ./ -name '*.xsl' -exec cp -prv '{}' '/path/to/targetDir/' ';'

It will look in the current directory and recursively in all of the sub directories for files with the xsl extension. It will copy them all to the target directory.

cp flags are:

  • p - preserve attributes of the file
  • r - recursive
  • v - verbose (shows you whats being copied)

Error: expected type-specifier before 'ClassName'

First of all, let's try to make your code a little simpler:

// No need to create a circle unless it is clearly necessary to
// demonstrate the problem

// Your Rect2f defines a default constructor, so let's use it for simplicity.
shared_ptr<Shape> rect(new Rect2f());

Okay, so now we see that the parentheses are clearly balanced. What else could it be? Let's check the following code snippet's error:

int main() {
    delete new T();
}

This may seem like weird usage, and it is, but I really hate memory leaks. However, the output does seem useful:

In function 'int main()':
Line 2: error: expected type-specifier before 'T'

Aha! Now we're just left with the error about the parentheses. I can't find what causes that; however, I think you are forgetting to include the file that defines Rect2f.

Kendo grid date column not formatting

This might be helpful:

columns.Bound(date=> date.START_DATE).Title("Start Date").Format("{0:MM dd, yyyy}");

Can you force Vue.js to reload/re-render?

Worked for me

    data () {
        return {
            userInfo: null,
            offers: null
        }
    },

    watch: {
        '$route'() {
            this.userInfo = null
            this.offers = null
            this.loadUserInfo()
            this.getUserOffers()
        }
    }

Giving height to table and row in Bootstrap

CSS:

tr {
width: 100%;
display: inline-table;
height:60px;                // <-- the rows height 
}

table{
 height:300px;              // <-- Select the height of the table
 display: -moz-groupbox;    // For firefox bad effect
}
tbody{
  overflow-y: scroll;      
  height: 200px;            //  <-- Select the height of the body
  width: 100%;
  position: absolute;
}

Bootply : http://www.bootply.com/AgI8LpDugl

Hadoop cluster setup - java.net.ConnectException: Connection refused

For me these steps worked

  1. stop-all.sh
  2. hadoop namenode -format
  3. start-all.sh

What is the purpose of the "role" attribute in HTML?

As I understand it, roles were initially defined by XHTML but were deprecated. However, they are now defined by HTML 5, see here: https://www.w3.org/WAI/PF/aria/roles#abstract_roles_header

The purpose of the role attribute is to identify to parsing software the exact function of an element (and its children) as part of a web application. This is mostly as an accessibility thing for screen readers, but I can also see it as being useful for embedded browsers and screen scrapers. In order to be useful to the unusual HTML client, the attribute needs to be set to one of the roles from the spec I linked. If you make up your own, this 'future' functionality can't work - a comment would be better.

Practicalities here: http://www.accessibleculture.org/articles/2011/04/html5-aria-2011/

How to resize an Image C#

This will perform a high quality resize:

/// <summary>
/// Resize the image to the specified width and height.
/// </summary>
/// <param name="image">The image to resize.</param>
/// <param name="width">The width to resize to.</param>
/// <param name="height">The height to resize to.</param>
/// <returns>The resized image.</returns>
public static Bitmap ResizeImage(Image image, int width, int height)
{
    var destRect = new Rectangle(0, 0, width, height);
    var destImage = new Bitmap(width, height);

    destImage.SetResolution(image.HorizontalResolution, image.VerticalResolution);

    using (var graphics = Graphics.FromImage(destImage))
    {
        graphics.CompositingMode = CompositingMode.SourceCopy;
        graphics.CompositingQuality = CompositingQuality.HighQuality;
        graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
        graphics.SmoothingMode = SmoothingMode.HighQuality;
        graphics.PixelOffsetMode = PixelOffsetMode.HighQuality;

        using (var wrapMode = new ImageAttributes())
        {
            wrapMode.SetWrapMode(WrapMode.TileFlipXY);
            graphics.DrawImage(image, destRect, 0, 0, image.Width,image.Height, GraphicsUnit.Pixel, wrapMode);
        }
    }

    return destImage;
}
  • wrapMode.SetWrapMode(WrapMode.TileFlipXY) prevents ghosting around the image borders -- naïve resizing will sample transparent pixels beyond the image boundaries, but by mirroring the image we can get a better sample (this setting is very noticeable)
  • destImage.SetResolution maintains DPI regardless of physical size -- may increase quality when reducing image dimensions or when printing
  • Compositing controls how pixels are blended with the background -- might not be needed since we're only drawing one thing.
  • graphics.InterpolationMode determines how intermediate values between two endpoints are calculated
  • graphics.SmoothingMode specifies whether lines, curves, and the edges of filled areas use smoothing (also called antialiasing) -- probably only works on vectors
  • graphics.PixelOffsetMode affects rendering quality when drawing the new image

Maintaining aspect ratio is left as an exercise for the reader (actually, I just don't think it's this function's job to do that for you).

Also, this is a good article describing some of the pitfalls with image resizing. The above function will cover most of them, but you still have to worry about saving.

groovy: safely find a key in a map and return its value

The whole point of using Maps is direct access. If you know for sure that the value in a map will never be Groovy-false, then you can do this:

def mymap = [name:"Gromit", likes:"cheese", id:1234]
def key = "likes"

if(mymap[key]) {
    println mymap[key]
}

However, if the value could potentially be Groovy-false, you should use:

if(mymap.containsKey(key)) {
    println mymap[key]
}

The easiest solution, though, if you know the value isn't going to be Groovy-false (or you can ignore that), and want a default value, is like this:

def value = mymap[key] ?: "default"

All three of these solutions are significantly faster than your examples, because they don't scan the entire map for keys. They take advantage of the HashMap (or LinkedHashMap) design that makes direct key access nearly instantaneous.

How to remove entry from $PATH on mac

Use sudo pico /etc/paths inside the terminal window and change the entries to the one you want to remove, then open a new terminal session.

Looping through dictionary object

You can do it like this.

Models.TestModels obj = new Models.TestModels();
foreach (var item in obj.sp)
{
    Console.Write(item.Key);
    Console.Write(item.Value.name);
    Console.Write(item.Value.age);
}

The problem you most likely have right now is that the collection is private. If you add public to the beginning of this line

Dictionary<int, dynamic> sp = new Dictionary<int, dynamic> 

You should be able to access it from the function inside your controller.

Edit: Adding functional example of the full TestModels implementation.

Your TestModels class should look something like this.

public class TestModels
{
    public Dictionary<int, dynamic> sp = new Dictionary<int, dynamic>();

    public TestModels()
    {
        sp.Add(0, new {name="Test One", age=5});
        sp.Add(1, new {name="Test Two", age=7});
    }
}

You probably want to read up on the dynamic keyword as well.

Can I execute a function after setState is finished updating?

With hooks in React 16.8 onward, it's easy to do this with useEffect

I've created a CodeSandbox to demonstrate this.

useEffect(() => {
  // code to be run when state variables in
  // dependency array changes
}, [stateVariables, thatShould, triggerChange])

Basically, useEffect synchronises with state changes and this can be used to render the canvas

import React, { useState, useEffect, useRef } from "react";
import { Stage, Shape } from "@createjs/easeljs";
import "./styles.css";

export default function App() {
  const [rows, setRows] = useState(10);
  const [columns, setColumns] = useState(10);
  let stage = useRef()

  useEffect(() => {
    stage.current = new Stage("canvas");
    var rectangles = [];
    var rectangle;
    //Rows
    for (var x = 0; x < rows; x++) {
      // Columns
      for (var y = 0; y < columns; y++) {
        var color = "Green";
        rectangle = new Shape();
        rectangle.graphics.beginFill(color);
        rectangle.graphics.drawRect(0, 0, 32, 44);
        rectangle.x = y * 33;
        rectangle.y = x * 45;

        stage.current.addChild(rectangle);

        var id = rectangle.x + "_" + rectangle.y;
        rectangles[id] = rectangle;
      }
    }
    stage.current.update();
  }, [rows, columns]);

  return (
    <div>
      <div className="canvas-wrapper">
        <canvas id="canvas" width="400" height="300"></canvas>
        <p>Rows: {rows}</p>
        <p>Columns: {columns}</p>
      </div>
      <div className="array-form">
        <form>
          <label>Number of Rows</label>
          <select
            id="numRows"
            value={rows}
            onChange={(e) => setRows(e.target.value)}
          >
            {getOptions()}
          </select>
          <label>Number of Columns</label>
          <select
            id="numCols"
            value={columns}
            onChange={(e) => setColumns(e.target.value)}
          >
            {getOptions()}
          </select>
        </form>
      </div>
    </div>
  );
}

const getOptions = () => {
  const options = [1, 2, 5, 10, 12, 15, 20];
  return (
    <>
      {options.map((option) => (
        <option key={option} value={option}>
          {option}
        </option>
      ))}
    </>
  );
};

Mocking HttpClient in unit tests

Building on the other answers, I suggest this code, which does not have any outside dependencies:

[TestClass]
public class MyTestClass
{
    [TestMethod]
    public async Task MyTestMethod()
    {
        var httpClient = new HttpClient(new MockHttpMessageHandler());

        var content = await httpClient.GetStringAsync("http://some.fake.url");

        Assert.AreEqual("Content as string", content);
    }
}

public class MockHttpMessageHandler : HttpMessageHandler
{
    protected override async Task<HttpResponseMessage> SendAsync(
        HttpRequestMessage request,
        CancellationToken cancellationToken)
    {
        var responseMessage = new HttpResponseMessage(HttpStatusCode.OK)
        {
            Content = new StringContent("Content as string")
        };

        return await Task.FromResult(responseMessage);
    }
}

DB2 Timestamp select statement

You might want to use TRUNC function on your column when comparing with string format, so it compares only till seconds, not milliseconds.

SELECT * FROM <table_name> WHERE id = 1 
AND TRUNC(usagetime, 'SS') = '2012-09-03 08:03:06';

If you wanted to truncate upto minutes, hours, etc. that is also possible, just use appropriate notation instead of 'SS':

hour ('HH'), minute('MI'), year('YEAR' or 'YYYY'), month('MONTH' or 'MM'), Day ('DD')