Programs & Examples On #Bean validation

Bean Validation, previously commonly called just "JSR-303", is an annotation based validation framework for javabean properties and parameters of arbitrary methods. Hibernate Validator is the reference implementation and the most widely used one.

Annotations from javax.validation.constraints not working

In my case i removed these lines

1-import javax.validation.constraints.NotNull;

2-import javax.validation.constraints.Size;

3- @NotNull

4- @Size(max = 3)

Cross field validation with Hibernate Validator (JSR 303)

I like the idea from Jakub Jirutka to use Spring Expression Language. If you don't want to add another library/dependency (assuming that you already use Spring), here is a simplified implementation of his idea.

The constraint:

@Constraint(validatedBy=ExpressionAssertValidator.class)
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface ExpressionAssert {
    String message() default "expression must evaluate to true";
    Class<?>[] groups() default {};
    Class<? extends Payload>[] payload() default {};
    String value();
}

The validator:

public class ExpressionAssertValidator implements ConstraintValidator<ExpressionAssert, Object> {
    private Expression exp;

    public void initialize(ExpressionAssert annotation) {
        ExpressionParser parser = new SpelExpressionParser();
        exp = parser.parseExpression(annotation.value());
    }

    public boolean isValid(Object value, ConstraintValidatorContext context) {
        return exp.getValue(value, Boolean.class);
    }
}

Apply like this:

@ExpressionAssert(value="pass == passVerify", message="passwords must be same")
public class MyBean {
    @Size(min=6, max=50)
    private String pass;
    private String passVerify;
}

Simple conversion between java.util.Date and XMLGregorianCalendar

You can use the this customization to change the default mapping to java.util.Date

<xsd:annotation>
<xsd:appinfo>
    <jaxb:globalBindings>
        <jaxb:javaType name="java.util.Date" xmlType="xsd:dateTime"
                 parseMethod="org.apache.cxf.xjc.runtime.DataTypeAdapter.parseDateTime"
                 printMethod="org.apache.cxf.xjc.runtime.DataTypeAdapter.printDateTime"/>
    </jaxb:globalBindings>
</xsd:appinfo>

Typing the Enter/Return key using Python and Selenium

When you don't want to search any locator, you can use the Robot class. For example,

Robot robot = new Robot();
robot.keyPress(KeyEvent.VK_ENTER);
robot.keyRelease(KeyEvent.VK_ENTER);

jquery get all input from specific form

To iterate through all the inputs in a form you can do this:

$("form#formID :input").each(function(){
 var input = $(this); // This is the jquery object of the input, do what you will
});

This uses the jquery :input selector to get ALL types of inputs, if you just want text you can do :

$("form#formID input[type=text]")//...

etc.

How do I disable the security certificate check in Python requests

To add to Blender's answer, you can disable SSL certificate validation for all requests using Session.verify = False

import requests

session = requests.Session()
session.verify = False
session.post(url='https://example.com', data={'bar':'baz'})

Note that urllib3, (which Requests uses), strongly discourages making unverified HTTPS requests and will raise an InsecureRequestWarning.

Compare two List<T> objects for equality, ignoring order

I use this method )

public delegate bool CompareValue<in T1, in T2>(T1 val1, T2 val2);

public static bool CompareTwoArrays<T1, T2>(this IEnumerable<T1> array1, IEnumerable<T2> array2, CompareValue<T1, T2> compareValue)
{
    return array1.Select(item1 => array2.Any(item2 => compareValue(item1, item2))).All(search => search)
            && array2.Select(item2 => array1.Any(item1 => compareValue(item1, item2))).All(search => search);
}

Visual Studio 2010 shortcut to find classes and methods?

Left click on a method and press the F12 key to Go To Definition. Other Actions also available

ImportError: No module named pythoncom

Just go to cmd and install pip install pywin32 pythoncom is part of pywin32 for API window extension.... good luck

How to draw a rounded Rectangle on HTML Canvas?

The HTML5 canvas doesn't provide a method to draw a rectangle with rounded corners.

How about using the lineTo() and arc() methods?

You can also use the quadraticCurveTo() method instead of the arc() method.

Edit a commit message in SourceTree Windows (already pushed to remote)

On Version 1.9.6.1. For UnPushed commit.

  1. Click on previously committed description
  2. Click Commit icon
  3. Enter new commit message, and choose "Ammend latest commit" from the Commit options dropdown.
  4. Commit your message.

Why is Python running my module when I import it, and how do I stop it?

Try just importing the functions needed from main.py? So,

from main import SomeFunction

It could be that you've named a function in batch.py the same as one in main.py, and when you import main.py the program runs the main.py function instead of the batch.py function; doing the above should fix that. I hope.

Should I use <i> tag for icons instead of <span>?

Quentin's answer clearly states that i tag should not be used to define icons.

But, Holly suggested that span has no meaning in itself and voted in favor of i instead of span tag.

Few suggested to use img as it's semantic and contains alt tag. But, we should not also use img because even empty src sends a request to server. Read here

I think, the correct way would be,

<span class="icon-fb" role="img" aria-label="facebook"></span>

This solves the issue of no alt tag in span and makes it accessible to vision-impaired users. It's semantic and not misusing ( hacking ) any tag.

Get full path without filename from path that includes filename

I used this and it works well:

string[] filePaths = Directory.GetFiles(Path.GetDirectoryName(dialog.FileName));

foreach (string file in filePaths)
{   
    if (comboBox1.SelectedItem.ToString() == "")
    {
        if (file.Contains("c"))
        {
            comboBox2.Items.Add(Path.GetFileName(file));
        }
    }
}

Python Progress Bar

I really like the python-progressbar, as it is very simple to use.

For the most simple case, it is just:

import progressbar
import time

progress = progressbar.ProgressBar()
for i in progress(range(80)):
    time.sleep(0.01)

The appearance can be customized and it can display the estimated remaining time. For an example use the same code as above but with:

progress = progressbar.ProgressBar(widgets=[progressbar.Bar('=', '[', ']'), ' ',
                                            progressbar.Percentage(), ' ',
                                            progressbar.ETA()])

Is it possible to set ENV variables for rails development environment in my code?

Never hardcode sensitive information (account credentials, passwords, etc.). Instead, create a file to store that information as environment variables (key/value pairs), and exclude that file from your source code management system. For example, in terms of Git (source code management system), exclude that file by adding it to .gitignore:

-bash> echo '/config/app_environment_variables.rb' >> .gitignore 

/config/app_environment_variables.rb

ENV['HTTP_USER'] = 'devuser'
ENV['HTTP_PASS'] = 'devpass'

As well, add the following lines to /config/environment.rb, between the require line, and the Application.initialize line:

# Load the app's custom environment variables here, so that they are loaded before environments/*.rb
app_environment_variables = File.join(Rails.root, 'config', 'app_environment_variables.rb')
load(app_environment_variables) if File.exists?(app_environment_variables)

That's it!

As the comment above says, by doing this you will be loading your environment variables before environments/*.rb, which means that you will be able to refer to your variables inside those files (e.g. environments/production.rb). This is a great advantage over putting your environment variables file inside /config/initializers/.

Inside app_environment_variables.rb there's no need to distinguish environments as far as development or production because you will never commit this file into your source code management system, hence it is for the development context by default. But if you need to set something special for the test environment (or for occasions when you test production mode locally), just add a conditional block below all the other variables:

if Rails.env.test?
  ENV['HTTP_USER'] = 'testuser'
  ENV['HTTP_PASS'] = 'testpass'
end

if Rails.env.production?
  ENV['HTTP_USER'] = 'produser'
  ENV['HTTP_PASS'] = 'prodpass'
end

Whenever you update app_environment_variables.rb, restart the app server. Assuming you are using the likes of Apache/Passenger or rails server:

-bash> touch tmp/restart.txt

In your code, refer to the environment variables as follows:

def authenticate
  authenticate_or_request_with_http_basic do |username, password|
    username == ENV['HTTP_USER'] && password == ENV['HTTP_PASS']
  end
end

Note that inside app_environment_variables.rb you must specify booleans and numbers as strings (e.g. ENV['SEND_MAIL'] = 'false' not just false, and ENV['TIMEOUT'] = '30' not just 30), otherwise you will get the errors can't convert false into String and can't convert Fixnum into String, respectively.

Storing and sharing sensitive information

The final knot to tie is: how to share this sensitive information with your clients and/or partners? For the purpose of business continuity (i.e. when you get hit by a falling star, how will your clients and/or partners resume full operations of the site?), your clients and/or partners need to know all the credentials required by your app. Emailing/Skyping these things around is insecure and leads to disarray. Storing it in shared Google Docs is not bad (if everyone uses https), but an app dedicated to storing and sharing small titbits like passwords would be ideal.

How to set environment variables on Heroku

If you have a single environment on Heroku:

-bash> heroku config:add HTTP_USER='herouser'
-bash> heroku config:add HTTP_USER='heropass'

If you have multiple environments on Heroku:

-bash> heroku config:add HTTP_USER='staguser' --remote staging
-bash> heroku config:add HTTP_PASS='stagpass' --remote staging

-bash> heroku config:add HTTP_USER='produser' --remote production
-bash> heroku config:add HTTP_PASS='prodpass' --remote production

Foreman and .env

Many developers use Foreman (installed with the Heroku Toolbelt) to run their apps locally (as opposed to using the likes of Apache/Passenger or rails server). Foreman and Heroku use Procfile for declaring what commands are run by your application, so the transition from local dev to Heroku is seamless in that regard. I use Foreman and Heroku in every Rails project, so this convenience is great. But here's the thing.. Foreman loads environment variables stored in /.env via dotenv but unfortunately dotenv essentially only parses the file for key=value pairs; those pairs don't become variables right there and then, so you can't refer to already set variables (to keep things DRY), nor can you do "Ruby" in there (as noted above with the conditionals), which you can do in /config/app_environment_variables.rb. For instance, in terms of keeping things DRY I sometimes do stuff like this:

ENV['SUPPORT_EMAIL']='Company Support <[email protected]>'
ENV['MAILER_DEFAULT_FROM'] = ENV['SUPPORT_EMAIL']
ENV['MAILER_DEFAULT_TO']   = ENV['SUPPORT_EMAIL']

Hence, I use Foreman to run my apps locally, but I don't use its .env file for loading environment variables; rather I use Foreman in conjunction with the /config/app_environment_variables.rb approach described above.

How to get only the last part of a path in Python?

I was searching for a solution to get the last foldername where the file is located, I just used split two times, to get the right part. It's not the question but google transfered me here.

pathname = "/folderA/folderB/folderC/folderD/filename.py"
head, tail = os.path.split(os.path.split(pathname)[0])
print(head + "   "  + tail)

curl: (35) error:1408F10B:SSL routines:ssl3_get_record:wrong version number

Simple answer

If you are behind a proxy server, please set the proxy for curl. The curl is not able to connect to server so it shows wrong version number. Set proxy by opening subl ~/.curlrc or use any other text editor. Then add the following line to file: proxy= proxyserver:proxyport For e.g. proxy = 10.8.0.1:8080

If you are not behind a proxy, make sure that the curlrc file does not contain the proxy settings.

SQL Server: Filter output of sp_who2

Slight improvement to Astander's answer. I like to put my criteria at top, and make it easier to reuse day to day:

DECLARE @Spid INT, @Status VARCHAR(MAX), @Login VARCHAR(MAX), @HostName VARCHAR(MAX), @BlkBy VARCHAR(MAX), @DBName VARCHAR(MAX), @Command VARCHAR(MAX), @CPUTime INT, @DiskIO INT, @LastBatch VARCHAR(MAX), @ProgramName VARCHAR(MAX), @SPID_1 INT, @REQUESTID INT

    --SET @SPID = 10
    --SET @Status = 'BACKGROUND'
    --SET @LOGIN = 'sa'
    --SET @HostName = 'MSSQL-1'
    --SET @BlkBy = 0
    --SET @DBName = 'master'
    --SET @Command = 'SELECT INTO'
    --SET @CPUTime = 1000
    --SET @DiskIO = 1000
    --SET @LastBatch = '10/24 10:00:00'
    --SET @ProgramName = 'Microsoft SQL Server Management Studio - Query'
    --SET @SPID_1 = 10
    --SET @REQUESTID = 0

    SET NOCOUNT ON 
    DECLARE @Table TABLE(
            SPID INT,
            Status VARCHAR(MAX),
            LOGIN VARCHAR(MAX),
            HostName VARCHAR(MAX),
            BlkBy VARCHAR(MAX),
            DBName VARCHAR(MAX),
            Command VARCHAR(MAX),
            CPUTime INT,
            DiskIO INT,
            LastBatch VARCHAR(MAX),
            ProgramName VARCHAR(MAX),
            SPID_1 INT,
            REQUESTID INT
    )
    INSERT INTO @Table EXEC sp_who2
    SET NOCOUNT OFF
    SELECT  *
    FROM    @Table
    WHERE
    (@Spid IS NULL OR SPID = @Spid)
    AND (@Status IS NULL OR Status = @Status)
    AND (@Login IS NULL OR Login = @Login)
    AND (@HostName IS NULL OR HostName = @HostName)
    AND (@BlkBy IS NULL OR BlkBy = @BlkBy)
    AND (@DBName IS NULL OR DBName = @DBName)
    AND (@Command IS NULL OR Command = @Command)
    AND (@CPUTime IS NULL OR CPUTime >= @CPUTime)
    AND (@DiskIO IS NULL OR DiskIO >= @DiskIO)
    AND (@LastBatch IS NULL OR LastBatch >= @LastBatch)
    AND (@ProgramName IS NULL OR ProgramName = @ProgramName)
    AND (@SPID_1 IS NULL OR SPID_1 = @SPID_1)
    AND (@REQUESTID IS NULL OR REQUESTID = @REQUESTID)

Where to place the 'assets' folder in Android Studio?

File > New > folder > assets Folder

Assets Folder

Call to getLayoutInflater() in places not in activity

LayoutInflater.from(context).inflate(R.layout.row_payment_gateway_item, null);

How can I see which Git branches are tracking which remote / upstream branch?

If you look at the man page for git-rev-parse, you'll see the following syntax is described:

<branchname>@{upstream}, e.g. master@{upstream}, @{u}

The suffix @{upstream} to a branchname (short form <branchname>@{u}) refers to the branch that the branch specified by branchname is set to build on top of. A missing branchname defaults to the current one.

Hence to find the upstream of the branch master, you would do:

git rev-parse --abbrev-ref master@{upstream}
# => origin/master

To print out the information for each branch, you could do something like:

while read branch; do
  upstream=$(git rev-parse --abbrev-ref $branch@{upstream} 2>/dev/null)
  if [[ $? == 0 ]]; then
    echo $branch tracks $upstream
  else
    echo $branch has no upstream configured
  fi
done < <(git for-each-ref --format='%(refname:short)' refs/heads/*)

# Output:
# master tracks origin/master
# ...

This is cleaner than parsing refs and config manually.

Include CSS and Javascript in my django template

Refer django docs on static files.

In settings.py:

import os
CURRENT_PATH = os.path.abspath(os.path.dirname(__file__).decode('utf-8'))

MEDIA_ROOT = os.path.join(CURRENT_PATH, 'media')

MEDIA_URL = '/media/'

STATIC_ROOT = 'static/'

STATIC_URL = '/static/'

STATICFILES_DIRS = (
                    os.path.join(CURRENT_PATH, 'static'),
)

Then place your js and css files static folder in your project. Not in media folder.

In views.py:

from django.shortcuts import render_to_response, RequestContext

def view_name(request):
    #your stuff goes here
    return render_to_response('template.html', locals(), context_instance = RequestContext(request))

In template.html:

<link rel="stylesheet" type="text/css" href="{{ STATIC_URL }}css/style.css" />
<script type="text/javascript" src="{{ STATIC_URL }}js/jquery-1.8.3.min.js"></script>

In urls.py:

from django.conf import settings
urlpatterns += patterns('',
    url(r'^media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT, 'show_indexes': True}),
)

Project file structure can be found here in imgbin.

How to find and restore a deleted file in a Git repository

user@bsd:~/work/git$ rm slides.tex
user@bsd:~/work/git$ git pull 
Already up-to-date.
user@bsd:~/work/git$ ls slides.tex
ls: slides.tex: No such file or directory

Restore the deleted file:

user@bsd:~/work/git$ git checkout
D       .slides.tex.swp
D       slides.tex
user@bsd:~/work/git$ git checkout slides.tex 
user@bsd:~/work/git$ ls slides.tex
slides.tex

How do I find out what version of Sybase is running

Try running below command (Works on both windows and linux)

isql -v

Deleting elements from std::set while iterating

C++20 will have "uniform container erasure", and you'll be able to write:

std::erase_if(numbers, [](int n){ return n % 2 == 0 });

And that will work for vector, set, deque, etc. See cppReference for more info.

SQL Server r2 installation error .. update Visual Studio 2008 to SP1

I used the Visual Studio 2008 Uninstall tool and it worked fine for me.

You can use this tool to uninstall Visual Studio 2008 official release and Visual Studio 2008 Release candidate (Only English version).

Found here, on the MSDN Forum: MSDN forum topic.

I found this answer here

Be sure you run the tool with admin-rights.

Catch browser's "zoom" event in JavaScript

Good news everyone some people! Newer browsers will trigger a window resize event when the zoom is changed.

Subdomain on different host

sub domain is part of the domain, it's like subletting a room of an apartment. A records has to be setup on the dns for the domain e.g

mydomain.com has IP 123.456.789.999 and hosted with Godaddy. Now to get the sub domain

anothersite.mydomain.com

of which the site is actually on another server then

login to Godaddy and add an A record dnsimple anothersite.mydomain.com and point the IP to the other server 98.22.11.11

And that's it.

'dispatch' is not a function when argument to mapToDispatchToProps() in Redux

When you do not provide mapDispatchToProps as a second argument, like this:

export default connect(mapStateToProps)(Checkbox)

then you are automatically getting the dispatch to component's props, so you can just:

class SomeComp extends React.Component {
  constructor(props, context) {
    super(props, context);
  }
  componentDidMount() {
    this.props.dispatch(ACTION GOES HERE);
  }
....

without any mapDispatchToProps

Javascript seconds to minutes and seconds

  function formatSeconds(s: number) {
    let minutes = ~~(s / 60);
    let seconds = ~~(s % 60);
    return minutes + ':' + seconds;
  }

How to make remote REST call inside Node.js? any CURL?

You can use curlrequest to easily set what time of request you want to do... you can even set headers in the options to "fake" a browser call.

Can pandas automatically recognize dates?

pandas read_csv method is great for parsing dates. Complete documentation at http://pandas.pydata.org/pandas-docs/stable/generated/pandas.io.parsers.read_csv.html

you can even have the different date parts in different columns and pass the parameter:

parse_dates : boolean, list of ints or names, list of lists, or dict
If True -> try parsing the index. If [1, 2, 3] -> try parsing columns 1, 2, 3 each as a
separate date column. If [[1, 3]] -> combine columns 1 and 3 and parse as a single date
column. {‘foo’ : [1, 3]} -> parse columns 1, 3 as date and call result ‘foo’

The default sensing of dates works great, but it seems to be biased towards north american Date formats. If you live elsewhere you might occasionally be caught by the results. As far as I can remember 1/6/2000 means 6 January in the USA as opposed to 1 Jun where I live. It is smart enough to swing them around if dates like 23/6/2000 are used. Probably safer to stay with YYYYMMDD variations of date though. Apologies to pandas developers,here but i have not tested it with local dates recently.

you can use the date_parser parameter to pass a function to convert your format.

date_parser : function
Function to use for converting a sequence of string columns to an array of datetime
instances. The default uses dateutil.parser.parser to do the conversion.

Set variable in jinja

Just Set it up like this

{% set active_link = recordtype -%}

Tkinter: How to use threads to preventing main event loop from "freezing"

I have used RxPY which has some nice threading functions to solve this in a fairly clean manner. No queues, and I have provided a function that runs on the main thread after completion of the background thread. Here is a working example:

import rx
from rx.scheduler import ThreadPoolScheduler
import time
import tkinter as tk

class UI:
   def __init__(self):
      self.root = tk.Tk()
      self.pool_scheduler = ThreadPoolScheduler(1) # thread pool with 1 worker thread
      self.button = tk.Button(text="Do Task", command=self.do_task).pack()

   def do_task(self):
      rx.empty().subscribe(
         on_completed=self.long_running_task, 
         scheduler=self.pool_scheduler
      )

   def long_running_task(self):
      # your long running task here... eg:
      time.sleep(3)
      # if you want a callback on the main thread:
      self.root.after(5, self.on_task_complete)

   def on_task_complete(self):
       pass # runs on main thread

if __name__ == "__main__":
    ui = UI()
    ui.root.mainloop()

Another way to use this construct which might be cleaner (depending on preference):

tk.Button(text="Do Task", command=self.button_clicked).pack()

...

def button_clicked(self):

   def do_task(_):
      time.sleep(3) # runs on background thread
             
   def on_task_done():
      pass # runs on main thread

   rx.just(1).subscribe(
      on_next=do_task, 
      on_completed=lambda: self.root.after(5, on_task_done), 
      scheduler=self.pool_scheduler
   )

How can I get the key value in a JSON object?

When you parse the JSON representation, it'll become a JavaScript array of objects.

Because of this, you can use the .length property of the JavaScript array to see how many elements are contained, and use a for loop to enumerate it.

implements Closeable or implements AutoCloseable

Here is the small example

public class TryWithResource {

    public static void main(String[] args) {
        try (TestMe r = new TestMe()) {
            r.generalTest();
        } catch(Exception e) {
            System.out.println("From Exception Block");
        } finally {
            System.out.println("From Final Block");
        }
    }
}



public class TestMe implements AutoCloseable {

    @Override
    public void close() throws Exception {
        System.out.println(" From Close -  AutoCloseable  ");
    }

    public void generalTest() {
        System.out.println(" GeneralTest ");
    }
}

Here is the output:

GeneralTest 
From Close -  AutoCloseable  
From Final Block

How to install "make" in ubuntu?

I have no idea what linux distribution "ubuntu centOS" is. Ubuntu and CentOS are two different distributions.

To answer the question in the header: To install make in ubuntu you have to install build-essentials

sudo apt-get install build-essential

web-api POST body object always null

If using Postman, make sure that:

  • You have set a "Content-Type" header to "application/json"
  • You are sending the body as "raw"
  • You don't need to specify the parameter name anywhere if you are using [FromBody]

I was stupidly trying to send my JSON as form data, duh...

Beautiful Soup and extracting a div and its contents by ID

Here is a code fragment

soup = BeautifulSoup(:"index.html")
titleList = soup.findAll('title')
divList = soup.findAll('div', attrs={ "class" : "article story"})

As you can see I find all tags and then I find all tags with class="article" inside

How to update Ruby to 1.9.x on Mac?

I know it's an older post, but i wanna add some extra informations about that. Firstly, i think that rvm does great BUT it wasn't updating ruby from my system (MAC OS Yosemite).

What rvmwas doing : installing to another location and setting up the path there to my environment variable ... And i was kinda bored, because i had two ruby now on my system.

So to fix that, i uninstalled the rvm, then used the Homebrew package manager available here and installed ruby throw terminal command by doing brew install ruby.

And then, everything was working perfectly ! The ruby from my system was updated ! Hope it will help for the next adventurers !

Callback functions in Java

A little nitpicking:

I've seem people suggesting creating a separate object but that seems overkill

Passing a callback includes creating a separate object in pretty much any OO language, so it can hardly be considered overkill. What you probably mean is that in Java, it requires you to create a separate class, which is more verbose (and more resource-intensive) than in languages with explicit first-class functions or closures. However, anonymous classes at least reduce the verbosity and can be used inline.

Set value of hidden input with jquery

To make it with jquery, make this way:

var test = $("input[name=testing]:hidden");
test.val('work!');

Or

var test = $("input[name=testing]:hidden").val('work!');

See working in this fiddle.

What is the difference between resource and endpoint?

1. Resource description “Resources” refers to the information returned by an API.

2. Endpoints and methods The endpoints indicate how you access the resource, while the method indicates the allowed interactions (such as GET, POST, or DELETE) with the resource.

Additional info: 3. Parameters Parameters are options you can pass with the endpoint (such as specifying the response format or the amount returned) to influence the response.

4. Request example The request example includes a sample request using the endpoint, showing some parameters configured.

5. Response example and schema The response example shows a sample response from the request example; the response schema defines all possible elements in the response.

Source- Reference link

CSS Box Shadow Bottom Only

You can use two elements, one inside the other, and give the outer one overflow: hidden and a width equal to the inner element together with a bottom padding so that the shadow on all the other sides are "cut off"

#outer {
    width: 100px;
    overflow: hidden;
    padding-bottom: 10px;
}

#outer > div {
    width: 100px;
    height: 100px;
    background: orange;

    -moz-box-shadow: 0 4px 4px rgba(0, 0, 0, 0.4);
    -webkit-box-shadow: 0 4px 4px rgba(0, 0, 0, 0.4);
    box-shadow: 0 4px 4px rgba(0, 0, 0, 0.4);
}

Alternatively, float the outer element to cause it to shrink to the size of the inner element. See: http://jsfiddle.net/QJPd5/1/

How to convert "Mon Jun 18 00:00:00 IST 2012" to 18/06/2012?

I hope following program will solve your problem

String dateStr = "Mon Jun 18 00:00:00 IST 2012";
DateFormat formatter = new SimpleDateFormat("E MMM dd HH:mm:ss Z yyyy");
Date date = (Date)formatter.parse(dateStr);
System.out.println(date);        

Calendar cal = Calendar.getInstance();
cal.setTime(date);
String formatedDate = cal.get(Calendar.DATE) + "/" + (cal.get(Calendar.MONTH) + 1) + "/" +         cal.get(Calendar.YEAR);
System.out.println("formatedDate : " + formatedDate);    

ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment

When you use routerLink like this, then you need to pass the value of the route it should go to. But when you use routerLink with the property binding syntax, like this: [routerLink], then it should be assigned a name of the property the value of which will be the route it should navigate the user to.

So to fix your issue, replace this routerLink="['/about']" with routerLink="/about" in your HTML.

There were other places where you used property binding syntax when it wasn't really required. I've fixed it and you can simply use the template syntax below:

<nav class="main-nav>
  <ul 
    class="main-nav__list" 
    ng-sticky 
    addClass="main-sticky-link" 
    [ngClass]="ref.click ? 'Navbar__ToggleShow' : ''">
    <li class="main-nav__item" routerLinkActive="active">
      <a class="main-nav__link" routerLink="/">Home</a>
    </li>
    <li class="main-nav__item" routerLinkActive="active"> 
      <a class="main-nav__link" routerLink="/about">About us</a>
    </li>
  </ul>
</nav>

It also needs to know where exactly should it load the template for the Component corresponding to the route it has reached. So for that, don't forget to add a <router-outlet></router-outlet>, either in your template provided above or in a parent component.

There's another issue with your AppRoutingModule. You need to export the RouterModule from there so that it is available to your AppModule when it imports it. To fix that, export it from your AppRoutingModule by adding it to the exports array.

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { RouterModule, Routes } from '@angular/router';
import { MainLayoutComponent } from './layout/main-layout/main-layout.component';
import { AboutComponent } from './components/about/about.component';
import { WhatwedoComponent } from './components/whatwedo/whatwedo.component';
import { FooterComponent } from './components/footer/footer.component';
import { ProjectsComponent } from './components/projects/projects.component';
const routes: Routes = [
  { path: 'about', component: AboutComponent },
  { path: 'what', component: WhatwedoComponent },
  { path: 'contacts', component: FooterComponent },
  { path: 'projects', component: ProjectsComponent},
];

@NgModule({
  imports: [
    CommonModule,
    RouterModule.forRoot(routes),
  ],
  exports: [RouterModule],
  declarations: []
})
export class AppRoutingModule { }

Forbidden You don't have permission to access /wp-login.php on this server

Make sure your apache .conf files are correct -- then double check your .htaccess files. In this case, my .htaccess were incorrect! I removed some weird stuff no longer needed and it worked. Tada.

The ORDER BY clause is invalid in views, inline functions, derived tables, subqueries, and common table expressions

You do not need to use ORDER BY in inner query after WHERE clause because you have already used it in ROW_NUMBER() OVER (ORDER BY VRDATE DESC).

SELECT 
    * 
FROM (
    SELECT 
        Stockmain.VRNOA, 
        item.description as item_description, 
        party.name as party_name, 
        stockmain.vrdate, 
        stockdetail.qty, 
        stockdetail.rate, 
        stockdetail.amount, 
        ROW_NUMBER() OVER (ORDER BY VRDATE DESC) AS RowNum  --< ORDER BY
    FROM StockMain 
    INNER JOIN StockDetail 
        ON StockMain.stid = StockDetail.stid 
    INNER JOIN party 
        ON party.party_id = stockmain.party_id 
    INNER JOIN item 
        ON item.item_id = stockdetail.item_id 
    WHERE stockmain.etype='purchase' 
) AS MyDerivedTable
WHERE 
    MyDerivedTable.RowNum BETWEEN 1 and 5 

Failed to Connect to MySQL at localhost:3306 with user root

Open System Preference > MySQL > Initialize Database > Use Legacy Password Encription

What should main() return in C and C++?

I was under the impression that standard specifies that main doesn't need a return value as a successful return was OS based (zero in one could be either a success or a failure in another), therefore the absence of return was a cue for the compiler to insert the successful return itself.

However I usually return 0.

Mismatched anonymous define() module

The existing answers explain the problem well but if including your script files using or before requireJS is not an easy option due to legacy code a slightly hacky workaround is to remove require from the window scope before your script tag and then reinstate it afterwords. In our project this is wrapped behind a server-side function call but effectively the browser sees the following:

    <script>
        window.__define = window.define;
        window.__require = window.require;
        window.define = undefined;
        window.require = undefined;
    </script>
    <script src="your-script-file.js"></script>        
    <script>
        window.define = window.__define;
        window.require = window.__require;
        window.__define = undefined;
        window.__require = undefined;
    </script>

Not the neatest but seems to work and has saved a lot of refractoring.

Selecting option by text content with jQuery

If your <option> elements don't have value attributes, then you can just use .val:

$selectElement.val("text_you're_looking_for")

However, if your <option> elements have value attributes, or might do in future, then this won't work, because whenever possible .val will select an option by its value attribute instead of by its text content. There's no built-in jQuery method that will select an option by its text content if the options have value attributes, so we'll have to add one ourselves with a simple plugin:

/*
  Source: https://stackoverflow.com/a/16887276/1709587

  Usage instructions:

  Call

      jQuery('#mySelectElement').selectOptionWithText('target_text');

  to select the <option> element from within #mySelectElement whose text content
  is 'target_text' (or do nothing if no such <option> element exists).
*/
jQuery.fn.selectOptionWithText = function selectOptionWithText(targetText) {
    return this.each(function () {
        var $selectElement, $options, $targetOption;

        $selectElement = jQuery(this);
        $options = $selectElement.find('option');
        $targetOption = $options.filter(
            function () {return jQuery(this).text() == targetText}
        );

        // We use `.prop` if it's available (which it should be for any jQuery
        // versions above and including 1.6), and fall back on `.attr` (which
        // was used for changing DOM properties in pre-1.6) otherwise.
        if ($targetOption.prop) {
            $targetOption.prop('selected', true);
        } 
        else {
            $targetOption.attr('selected', 'true');
        }
    });
}

Just include this plugin somewhere after you add jQuery onto the page, and then do

jQuery('#someSelectElement').selectOptionWithText('Some Target Text');

to select options.

The plugin method uses filter to pick out only the option matching the targetText, and selects it using either .attr or .prop, depending upon jQuery version (see .prop() vs .attr() for explanation).

Here's a JSFiddle you can use to play with all three answers given to this question, which demonstrates that this one is the only one to reliably work: http://jsfiddle.net/3cLm5/1/

Convert txt to csv python script

You need to split the line first.

import csv

with open('log.txt', 'r') as in_file:
    stripped = (line.strip() for line in in_file)
    lines = (line.split(",") for line in stripped if line)
    with open('log.csv', 'w') as out_file:
        writer = csv.writer(out_file)
        writer.writerow(('title', 'intro'))
        writer.writerows(lines)

How to download a file with Node.js (without using third-party libraries)?

You can use https://github.com/douzi8/ajax-request#download

request.download('http://res.m.ctrip.com/html5/Content/images/57.png', 
  function(err, res, body) {}
);

Why doesn't file_get_contents work?

//JUST ADD urlencode();
$url = urlencode("http://maps.googleapis.com/maps/api/geocode/json?address=$adr&sensor=false");
<html>
<head>        
<title>Test File</title>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"> 
</script>
</head>
<body>
<?php    
$adr = 'Sydney+NSW';
echo $adr;
$url = "http://maps.googleapis.com/maps/api/geocode/json?address=$adr&sensor=false";
echo '<p>'.$url.'</p>';
echo file_get_contents($url);
print '<p>'.file_get_contents($url).'</p>';
$jsonData   = file_get_contents($url);
echo $jsonData;
?>
</body>
</html>

Pandas merge two dataframes with different columns

I had this problem today using any of concat, append or merge, and I got around it by adding a helper column sequentially numbered and then doing an outer join

helper=1
for i in df1.index:
    df1.loc[i,'helper']=helper
    helper=helper+1
for i in df2.index:
    df2.loc[i,'helper']=helper
    helper=helper+1
df1.merge(df2,on='helper',how='outer')

Reverse a string in Python

There are a lot of ways to reverse a string but I also created another one just for fun. I think this approach is not that bad.

def reverse(_str):
    list_char = list(_str) # Create a hypothetical list. because string is immutable

    for i in range(len(list_char)/2): # just t(n/2) to reverse a big string
        list_char[i], list_char[-i - 1] = list_char[-i - 1], list_char[i]

    return ''.join(list_char)

print(reverse("Ehsan"))

Cannot find mysql.sock

To refresh the locate's database I ran

/usr/libexec/locate.updatedb

Example of Named Pipes

using System;
using System.IO;
using System.IO.Pipes;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            StartServer();
            Task.Delay(1000).Wait();


            //Client
            var client = new NamedPipeClientStream("PipesOfPiece");
            client.Connect();
            StreamReader reader = new StreamReader(client);
            StreamWriter writer = new StreamWriter(client);

            while (true)
            {
                string input = Console.ReadLine();
                if (String.IsNullOrEmpty(input)) break;
                writer.WriteLine(input);
                writer.Flush();
                Console.WriteLine(reader.ReadLine());
            }
        }

        static void StartServer()
        {
            Task.Factory.StartNew(() =>
            {
                var server = new NamedPipeServerStream("PipesOfPiece");
                server.WaitForConnection();
                StreamReader reader = new StreamReader(server);
                StreamWriter writer = new StreamWriter(server);
                while (true)
                {
                    var line = reader.ReadLine();
                    writer.WriteLine(String.Join("", line.Reverse()));
                    writer.Flush();
                }
            });
        }
    }
}

CRON job to run on the last day of the month

Some cron implementations support the "L" flag to represent the last day of the month.

If you're lucky to be using one of those implementations, it's as simple as:

0 55 23 L * ?

That will run at 11:55 pm on the last day of every month.

http://www.quartz-scheduler.org/documentation/quartz-1.x/tutorials/crontrigger

How to change the background color of a UIButton while it's highlighted?

simple is that use that UIButton Extension ONLY

extension UIButton {

    func setBackgroundColor(color: UIColor, forState: UIControl.State) {
        self.clipsToBounds = true  // add this to maintain corner radius
        UIGraphicsBeginImageContext(CGSize(width: 1, height: 1))
        if let context = UIGraphicsGetCurrentContext() {
            context.setFillColor(color.cgColor)
            context.fill(CGRect(x: 0, y: 0, width: 1, height: 1))
            let colorImage = UIGraphicsGetImageFromCurrentImageContext()
            UIGraphicsEndImageContext()
            self.setBackgroundImage(colorImage, for: forState)
        }
    }

}

and use this

 optionButton.setBackgroundColor(color: UIColor(red:0.09, green:0.42, blue:0.82, alpha:1.0), forState: .selected)

 optionButton.setBackgroundColor(color: UIColor(red:0.96, green:0.96, blue:0.96, alpha:1.0), forState: .highlighted)

 optionButton.setBackgroundColor(color: UIColor(red:0.96, green:0.96, blue:0.96, alpha:1.0), forState: .normal)

Date ticks and rotation in matplotlib

Another way to applyhorizontalalignment and rotation to each tick label is doing a for loop over the tick labels you want to change:

import numpy as np
import matplotlib.pyplot as plt
import datetime as dt

now = dt.datetime.now()
hours = [now + dt.timedelta(minutes=x) for x in range(0,24*60,10)]
days = [now + dt.timedelta(days=x) for x in np.arange(0,30,1/4.)]
hours_value = np.random.random(len(hours))
days_value = np.random.random(len(days))

fig, axs = plt.subplots(2)
fig.subplots_adjust(hspace=0.75)
axs[0].plot(hours,hours_value)
axs[1].plot(days,days_value)

for label in axs[0].get_xmajorticklabels() + axs[1].get_xmajorticklabels():
    label.set_rotation(30)
    label.set_horizontalalignment("right")

enter image description here

And here is an example if you want to control the location of major and minor ticks:

import numpy as np
import matplotlib.pyplot as plt
import datetime as dt

fig, axs = plt.subplots(2)
fig.subplots_adjust(hspace=0.75)
now = dt.datetime.now()
hours = [now + dt.timedelta(minutes=x) for x in range(0,24*60,10)]
days = [now + dt.timedelta(days=x) for x in np.arange(0,30,1/4.)]

axs[0].plot(hours,np.random.random(len(hours)))
x_major_lct = mpl.dates.AutoDateLocator(minticks=2,maxticks=10, interval_multiples=True)
x_minor_lct = matplotlib.dates.HourLocator(byhour = range(0,25,1))
x_fmt = matplotlib.dates.AutoDateFormatter(x_major_lct)
axs[0].xaxis.set_major_locator(x_major_lct)
axs[0].xaxis.set_minor_locator(x_minor_lct)
axs[0].xaxis.set_major_formatter(x_fmt)
axs[0].set_xlabel("minor ticks set to every hour, major ticks start with 00:00")

axs[1].plot(days,np.random.random(len(days)))
x_major_lct = mpl.dates.AutoDateLocator(minticks=2,maxticks=10, interval_multiples=True)
x_minor_lct = matplotlib.dates.DayLocator(bymonthday = range(0,32,1))
x_fmt = matplotlib.dates.AutoDateFormatter(x_major_lct)
axs[1].xaxis.set_major_locator(x_major_lct)
axs[1].xaxis.set_minor_locator(x_minor_lct)
axs[1].xaxis.set_major_formatter(x_fmt)
axs[1].set_xlabel("minor ticks set to every day, major ticks show first day of month")
for label in axs[0].get_xmajorticklabels() + axs[1].get_xmajorticklabels():
    label.set_rotation(30)
    label.set_horizontalalignment("right")

enter image description here

can't start MySql in Mac OS 10.6 Snow Leopard

  1. Change the following to the file /usr/local/mysql/support-files/mysql.server the follow lines:

    basedir="/usr/local/mysql"
    
    datadir="/usr/local/mysql/data"
    

    and save it.

  2. In the file /etc/rc.common add the follow line at end: /usr/local/mysql/bin/mysqld_safe --user=mysql &

How to set response header in JAX-RS so that user sees download popup for Excel?

I figured to set HTTP response header and stream to display download-popup in browser via standard servlet. note: I'm using Excella, excel output API.

package local.test.servlet;

import java.io.IOException;
import java.net.URL;
import java.net.URLDecoder;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import local.test.jaxrs.ExcellaTestResource;
import org.apache.poi.ss.usermodel.Workbook;
import org.bbreak.excella.core.BookData;
import org.bbreak.excella.core.exception.ExportException;
import org.bbreak.excella.reports.exporter.ExcelExporter;
import org.bbreak.excella.reports.exporter.ReportBookExporter;
import org.bbreak.excella.reports.model.ConvertConfiguration;
import org.bbreak.excella.reports.model.ReportBook;
import org.bbreak.excella.reports.model.ReportSheet;
import org.bbreak.excella.reports.processor.ReportProcessor;

@WebServlet(name="ExcelServlet", urlPatterns={"/ExcelServlet"})
public class ExcelServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {


        try {

            URL templateFileUrl = ExcellaTestResource.class.getResource("myTemplate.xls");
            //   /C:/Users/m-hugohugo/Documents/NetBeansProjects/KogaAlpha/build/web/WEB-INF/classes/local/test/jaxrs/myTemplate.xls
            System.out.println(templateFileUrl.getPath());
            String templateFilePath = URLDecoder.decode(templateFileUrl.getPath(), "UTF-8");
            String outputFileDir = "MasatoExcelHorizontalOutput";

            ReportProcessor reportProcessor = new ReportProcessor();
            ReportBook outputBook = new ReportBook(templateFilePath, outputFileDir, ExcelExporter.FORMAT_TYPE);

            ReportSheet outputSheet = new ReportSheet("MySheet");
            outputBook.addReportSheet(outputSheet);

            reportProcessor.addReportBookExporter(new OutputStreamExporter(response));
            System.out.println("wtf???");
            reportProcessor.process(outputBook);


            System.out.println("done!!");
        }
        catch(Exception e) {
            System.out.println(e);
        }

    } //end doGet()

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

}//end class



class OutputStreamExporter extends ReportBookExporter {

    private HttpServletResponse response;

    public OutputStreamExporter(HttpServletResponse response) {
        this.response = response;
    }

    @Override
    public String getExtention() {
        return null;
    }

    @Override
    public String getFormatType() {
        return ExcelExporter.FORMAT_TYPE;
    }

    @Override
    public void output(Workbook book, BookData bookdata, ConvertConfiguration configuration) throws ExportException {

        System.out.println(book.getFirstVisibleTab());
        System.out.println(book.getSheetName(0));

        //TODO write to stream
        try {
            response.setContentType("application/vnd.ms-excel");
            response.setHeader("Content-Disposition", "attachment; filename=masatoExample.xls");
            book.write(response.getOutputStream());
            response.getOutputStream().close();
            System.out.println("booya!!");
        }
        catch(Exception e) {
            System.out.println(e);
        }
    }
}//end class

What's the best way to identify hidden characters in the result of a query in SQL Server (Query Analyzer)?

To find them, you can use this

;WITH cte AS
(
   SELECT 0 AS CharCode
   UNION ALL
   SELECT CharCode + 1 FROM cte WHERE CharCode <31
)
SELECT
   *
FROM
   mytable T
     cross join cte
WHERE
   EXISTS (SELECT *
        FROM mytable Tx
        WHERE Tx.PKCol = T.PKCol
             AND
              Tx.MyField LIKE '%' + CHAR(cte.CharCode) + '%'
         )

Replacing the EXISTS with a JOIN will allow you to REPLACE them, but you'll get multiple rows... I can't think of a way around that...

Showing the same file in both columns of a Sublime Text window

Inside sublime editor,Find the Tab named View,

View --> Layout --> "select your need"

Encrypting & Decrypting a String in C#

The easiest way that I've seen to do encryption is through RSA

Check out the MSDN on it: http://msdn.microsoft.com/en-us/library/system.security.cryptography.rsacryptoserviceprovider.aspx

It does involve using bytes, but when it comes down to it you kind of do want encryption and decryption to be tough to figure out otherwise it will be easy to hack.

How do I create a simple 'Hello World' module in Magento?

I was trying to make my module from magaplaza hello world tutorial, but something went wrong. I imported code of this module https://github.com/astorm/magento2-hello-world from github and it worked. from that module, i created it a categories subcategories ajax select drop downs Module. After installing it in aap/code directory of your magento2 installation follow this URL.. http://www.example.com/hello_mvvm/hello/world You can download its code from here https://github.com/sanaullahAhmad/Magento2_cat_subcat_ajax_select_dropdowns and place it in your aap/code folder. than run these commands...

php bin/magento setup:update
php bin/magento setup:static-content:deploy -f
php bin/magento c:c

Now you can check module functionality with following URL http://{{www.example.com}}/hello_mvvm/hello/world

Postgresql column reference "id" is ambiguous

You need the table name/alias in the SELECT part (maybe (vg.id, name)) :

SELECT (vg.id, name) FROM v_groups vg 
inner join people2v_groups p2vg on vg.id = p2vg.v_group_id
where p2vg.people_id =0;

How to use DbContext.Database.SqlQuery<TElement>(sql, params) with stored procedure? EF Code First CTP5

I had the same error message when I was working with calling a stored procedure that takes two input parameters and returns 3 values using SELECT statement and I solved the issue like below in EF Code First Approach

 SqlParameter @TableName = new SqlParameter()
        {
            ParameterName = "@TableName",
            DbType = DbType.String,
            Value = "Trans"
        };

SqlParameter @FieldName = new SqlParameter()
        {
            ParameterName = "@FieldName",
            DbType = DbType.String,
            Value = "HLTransNbr"
        };


object[] parameters = new object[] { @TableName, @FieldName };

List<Sample> x = this.Database.SqlQuery<Sample>("EXEC usp_NextNumberBOGetMulti @TableName, @FieldName", parameters).ToList();


public class Sample
{
    public string TableName { get; set; }
    public string FieldName { get; set; }
    public int NextNum { get; set; }
}

UPDATE: It looks like with SQL SERVER 2005 missing EXEC keyword is creating problem. So to allow it to work with all SQL SERVER versions I updated my answer and added EXEC in below line

 List<Sample> x = this.Database.SqlQuery<Sample>(" EXEC usp_NextNumberBOGetMulti @TableName, @FieldName", param).ToList();

Skipping error in for-loop

One (dirty) way to do it is to use tryCatch with an empty function for error handling. For example, the following code raises an error and breaks the loop :

for (i in 1:10) {
    print(i)
    if (i==7) stop("Urgh, the iphone is in the blender !")
}

[1] 1
[1] 2
[1] 3
[1] 4
[1] 5
[1] 6
[1] 7
Erreur : Urgh, the iphone is in the blender !

But you can wrap your instructions into a tryCatch with an error handling function that does nothing, for example :

for (i in 1:10) {
  tryCatch({
    print(i)
    if (i==7) stop("Urgh, the iphone is in the blender !")
  }, error=function(e){})
}

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

But I think you should at least print the error message to know if something bad happened while letting your code continue to run :

for (i in 1:10) {
  tryCatch({
    print(i)
    if (i==7) stop("Urgh, the iphone is in the blender !")
  }, error=function(e){cat("ERROR :",conditionMessage(e), "\n")})
}

[1] 1
[1] 2
[1] 3
[1] 4
[1] 5
[1] 6
[1] 7
ERROR : Urgh, the iphone is in the blender ! 
[1] 8
[1] 9
[1] 10

EDIT : So to apply tryCatch in your case would be something like :

for (v in 2:180){
    tryCatch({
        mypath=file.path("C:", "file1", (paste("graph",names(mydata[columnname]), ".pdf", sep="-")))
        pdf(file=mypath)
        mytitle = paste("anything")
        myplotfunction(mydata[,columnnumber]) ## this function is defined previously in the program
        dev.off()
    }, error=function(e){cat("ERROR :",conditionMessage(e), "\n")})
}

Assign one struct to another in C

Yes, assignment is supported for structs. However, there are problems:

struct S {
   char * p;
};

struct S s1, s2;
s1.p = malloc(100);
s2 = s1;

Now the pointers of both structs point to the same block of memory - the compiler does not copy the pointed to data. It is now difficult to know which struct instance owns the data. This is why C++ invented the concept of user-definable assignment operators - you can write specific code to handle this case.

Easy way to convert a unicode list to a list containing python strings?

There are several ways to do this. I converted like this

def clean(s):
    s = s.replace("u'","")
    return re.sub("[\[\]\'\s]", '', s)

EmployeeList = [clean(i) for i in str(EmployeeList).split(',')]

After that you can check

if '1001' in EmployeeList:
    #do something

Hope it will help you.

Python: Ignore 'Incorrect padding' error when base64 decoding

It seems you just need to add padding to your bytes before decoding. There are many other answers on this question, but I want to point out that (at least in Python 3.x) base64.b64decode will truncate any extra padding, provided there is enough in the first place.

So, something like: b'abc=' works just as well as b'abc==' (as does b'abc=====').

What this means is that you can just add the maximum number of padding characters that you would ever need—which is three (b'===')—and base64 will truncate any unnecessary ones.

This lets you write:

base64.b64decode(s + b'===')

which is simpler than:

base64.b64decode(s + b'=' * (-len(s) % 4))

How can I get log4j to delete old rotating log files?

You can achieve it using custom log4j appender.
MaxNumberOfDays - possibility to set amount of days of rotated log files.
CompressBackups - possibility to archive old logs with zip extension.

package com.example.package;

import org.apache.log4j.FileAppender;
import org.apache.log4j.Layout;
import org.apache.log4j.helpers.LogLog;
import org.apache.log4j.spi.LoggingEvent;

import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Locale;
import java.util.Optional;
import java.util.TimeZone;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class CustomLog4jAppender extends FileAppender {

    private static final int TOP_OF_TROUBLE = -1;
    private static final int TOP_OF_MINUTE = 0;
    private static final int TOP_OF_HOUR = 1;
    private static final int HALF_DAY = 2;
    private static final int TOP_OF_DAY = 3;
    private static final int TOP_OF_WEEK = 4;
    private static final int TOP_OF_MONTH = 5;

    private String datePattern = "'.'yyyy-MM-dd";
    private String compressBackups = "false";
    private String maxNumberOfDays = "7";
    private String scheduledFilename;
    private long nextCheck = System.currentTimeMillis() - 1;
    private Date now = new Date();
    private SimpleDateFormat sdf;
    private RollingCalendar rc = new RollingCalendar();

    private static final TimeZone gmtTimeZone = TimeZone.getTimeZone("GMT");

    public CustomLog4jAppender() {
    }

    public CustomLog4jAppender(Layout layout, String filename, String datePattern) throws IOException {
        super(layout, filename, true);
        this.datePattern = datePattern;
        activateOptions();
    }

    public void setDatePattern(String pattern) {
        datePattern = pattern;
    }

    public String getDatePattern() {
        return datePattern;
    }

    @Override
    public void activateOptions() {
        super.activateOptions();
        if (datePattern != null && fileName != null) {
            now.setTime(System.currentTimeMillis());
            sdf = new SimpleDateFormat(datePattern);
            int type = computeCheckPeriod();
            printPeriodicity(type);
            rc.setType(type);
            File file = new File(fileName);
            scheduledFilename = fileName + sdf.format(new Date(file.lastModified()));
        } else {
            LogLog.error("Either File or DatePattern options are not set for appender [" + name + "].");
        }
    }

    private void printPeriodicity(int type) {
        String appender = "Log4J Appender: ";
        switch (type) {
            case TOP_OF_MINUTE:
                LogLog.debug(appender + name + " to be rolled every minute.");
                break;
            case TOP_OF_HOUR:
                LogLog.debug(appender + name + " to be rolled on top of every hour.");
                break;
            case HALF_DAY:
                LogLog.debug(appender + name + " to be rolled at midday and midnight.");
                break;
            case TOP_OF_DAY:
                LogLog.debug(appender + name + " to be rolled at midnight.");
                break;
            case TOP_OF_WEEK:
                LogLog.debug(appender + name + " to be rolled at start of week.");
                break;
            case TOP_OF_MONTH:
                LogLog.debug(appender + name + " to be rolled at start of every month.");
                break;
            default:
                LogLog.warn("Unknown periodicity for appender [" + name + "].");
        }
    }

    private int computeCheckPeriod() {
        RollingCalendar rollingCalendar = new RollingCalendar(gmtTimeZone, Locale.ENGLISH);
        Date epoch = new Date(0);
        if (datePattern != null) {
            for (int i = TOP_OF_MINUTE; i <= TOP_OF_MONTH; i++) {
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat(datePattern);
                simpleDateFormat.setTimeZone(gmtTimeZone);
                String r0 = simpleDateFormat.format(epoch);
                rollingCalendar.setType(i);
                Date next = new Date(rollingCalendar.getNextCheckMillis(epoch));
                String r1 = simpleDateFormat.format(next);
                if (!r0.equals(r1)) {
                    return i;
                }
            }
        }
        return TOP_OF_TROUBLE;
    }

    private void rollOver() throws IOException {
        if (datePattern == null) {
            errorHandler.error("Missing DatePattern option in rollOver().");
            return;
        }
        String datedFilename = fileName + sdf.format(now);
        if (scheduledFilename.equals(datedFilename)) {
            return;
        }
        this.closeFile();
        File target = new File(scheduledFilename);
        if (target.exists()) {
            Files.delete(target.toPath());
        }
        File file = new File(fileName);
        boolean result = file.renameTo(target);
        if (result) {
            LogLog.debug(fileName + " -> " + scheduledFilename);
        } else {
            LogLog.error("Failed to rename [" + fileName + "] to [" + scheduledFilename + "].");
        }
        try {
            this.setFile(fileName, false, this.bufferedIO, this.bufferSize);
        } catch (IOException e) {
            errorHandler.error("setFile(" + fileName + ", false) call failed.");
        }
        scheduledFilename = datedFilename;
    }

    @Override
    protected void subAppend(LoggingEvent event) {
        long n = System.currentTimeMillis();
        if (n >= nextCheck) {
            now.setTime(n);
            nextCheck = rc.getNextCheckMillis(now);
            try {
                cleanupAndRollOver();
            } catch (IOException ioe) {
                LogLog.error("cleanupAndRollover() failed.", ioe);
            }
        }
        super.subAppend(event);
    }

    public String getCompressBackups() {
        return compressBackups;
    }

    public void setCompressBackups(String compressBackups) {
        this.compressBackups = compressBackups;
    }

    public String getMaxNumberOfDays() {
        return maxNumberOfDays;
    }

    public void setMaxNumberOfDays(String maxNumberOfDays) {
        this.maxNumberOfDays = maxNumberOfDays;
    }

    protected void cleanupAndRollOver() throws IOException {
        File file = new File(fileName);
        Calendar cal = Calendar.getInstance();
        int maxDays = 7;
        try {
            maxDays = Integer.parseInt(getMaxNumberOfDays());
        } catch (Exception e) {
            // just leave it at 7.
        }
        cal.add(Calendar.DATE, -maxDays);
        Date cutoffDate = cal.getTime();
        if (file.getParentFile().exists()) {
            File[] files = file.getParentFile().listFiles(new StartsWithFileFilter(file.getName(), false));
            int nameLength = file.getName().length();
            for (File value : Optional.ofNullable(files).orElse(new File[0])) {
                String datePart;
                try {
                    datePart = value.getName().substring(nameLength);
                    Date date = sdf.parse(datePart);
                    if (date.before(cutoffDate)) {
                        Files.delete(value.toPath());
                    } else if (getCompressBackups().equalsIgnoreCase("YES") || getCompressBackups().equalsIgnoreCase("TRUE")) {
                        zipAndDelete(value);
                    }
                } catch (Exception pe) {
                    // This isn't a file we should touch (it isn't named correctly)
                }
            }
        }
        rollOver();
    }

    private void zipAndDelete(File file) throws IOException {
        if (!file.getName().endsWith(".zip")) {
            File zipFile = new File(file.getParent(), file.getName() + ".zip");
            try (FileInputStream fis = new FileInputStream(file);
                 FileOutputStream fos = new FileOutputStream(zipFile);
                 ZipOutputStream zos = new ZipOutputStream(fos)) {
                ZipEntry zipEntry = new ZipEntry(file.getName());
                zos.putNextEntry(zipEntry);
                byte[] buffer = new byte[4096];
                while (true) {
                    int bytesRead = fis.read(buffer);
                    if (bytesRead == -1) {
                        break;
                    } else {
                        zos.write(buffer, 0, bytesRead);
                    }
                }
                zos.closeEntry();
            }
            Files.delete(file.toPath());
        }
    }

    class StartsWithFileFilter implements FileFilter {
        private String startsWith;
        private boolean inclDirs;

        StartsWithFileFilter(String startsWith, boolean includeDirectories) {
            super();
            this.startsWith = startsWith.toUpperCase();
            inclDirs = includeDirectories;
        }

        public boolean accept(File pathname) {
            if (!inclDirs && pathname.isDirectory()) {
                return false;
            } else {
                return pathname.getName().toUpperCase().startsWith(startsWith);
            }
        }
    }

    class RollingCalendar extends GregorianCalendar {
        private static final long serialVersionUID = -3560331770601814177L;

        int type = CustomLog4jAppender.TOP_OF_TROUBLE;

        RollingCalendar() {
            super();
        }

        RollingCalendar(TimeZone tz, Locale locale) {
            super(tz, locale);
        }

        void setType(int type) {
            this.type = type;
        }

        long getNextCheckMillis(Date now) {
            return getNextCheckDate(now).getTime();
        }

        Date getNextCheckDate(Date now) {
            this.setTime(now);

            switch (type) {
                case CustomLog4jAppender.TOP_OF_MINUTE:
                    this.set(Calendar.SECOND, 0);
                    this.set(Calendar.MILLISECOND, 0);
                    this.add(Calendar.MINUTE, 1);
                    break;
                case CustomLog4jAppender.TOP_OF_HOUR:
                    this.set(Calendar.MINUTE, 0);
                    this.set(Calendar.SECOND, 0);
                    this.set(Calendar.MILLISECOND, 0);
                    this.add(Calendar.HOUR_OF_DAY, 1);
                    break;
                case CustomLog4jAppender.HALF_DAY:
                    this.set(Calendar.MINUTE, 0);
                    this.set(Calendar.SECOND, 0);
                    this.set(Calendar.MILLISECOND, 0);
                    int hour = get(Calendar.HOUR_OF_DAY);
                    if (hour < 12) {
                        this.set(Calendar.HOUR_OF_DAY, 12);
                    } else {
                        this.set(Calendar.HOUR_OF_DAY, 0);
                        this.add(Calendar.DAY_OF_MONTH, 1);
                    }
                    break;
                case CustomLog4jAppender.TOP_OF_DAY:
                    this.set(Calendar.HOUR_OF_DAY, 0);
                    this.set(Calendar.MINUTE, 0);
                    this.set(Calendar.SECOND, 0);
                    this.set(Calendar.MILLISECOND, 0);
                    this.add(Calendar.DATE, 1);
                    break;
                case CustomLog4jAppender.TOP_OF_WEEK:
                    this.set(Calendar.DAY_OF_WEEK, getFirstDayOfWeek());
                    this.set(Calendar.HOUR_OF_DAY, 0);
                    this.set(Calendar.MINUTE, 0);
                    this.set(Calendar.SECOND, 0);
                    this.set(Calendar.MILLISECOND, 0);
                    this.add(Calendar.WEEK_OF_YEAR, 1);
                    break;
                case CustomLog4jAppender.TOP_OF_MONTH:
                    this.set(Calendar.DATE, 1);
                    this.set(Calendar.HOUR_OF_DAY, 0);
                    this.set(Calendar.MINUTE, 0);
                    this.set(Calendar.SECOND, 0);
                    this.set(Calendar.MILLISECOND, 0);
                    this.add(Calendar.MONTH, 1);
                    break;
                default:
                    throw new IllegalStateException("Unknown periodicity type.");
            }
            return getTime();
        }
    }    
}

And use this properties in your log4j config file:

log4j.appender.[appenderName]=com.example.package.CustomLog4jAppender
log4j.appender.[appenderName].File=/logs/app-daily.log
log4j.appender.[appenderName].Append=true
log4j.appender.[appenderName].encoding=UTF-8
log4j.appender.[appenderName].layout=org.apache.log4j.EnhancedPatternLayout
log4j.appender.[appenderName].layout.ConversionPattern=%-5.5p %d %C{1.} - %m%n
log4j.appender.[appenderName].DatePattern='.'yyyy-MM-dd
log4j.appender.[appenderName].MaxNumberOfDays=7
log4j.appender.[appenderName].CompressBackups=true

Setting default value for TypeScript object passed as argument

This can be a nice way to do it that does not involve long constructors

class Person {
    firstName?: string = 'Bob';
    lastName?: string = 'Smith';

    // Pass in this class as the required params
    constructor(params: Person) {
        // object.assign will overwrite defaults if params exist
        Object.assign(this, params)
    }
}

// you can still use the typing 
function sayName(params: Person){ 
    let name = params.firstName + params.lastName
    alert(name)
}

// you do have to call new but for my use case this felt better
sayName(new Person({firstName: 'Gordon'}))
sayName(new Person({lastName: 'Thomas'}))

How to convert numbers to words without using num2word library?

    def giveText(num):
    pairs={1:'one',2:'two',3:'three',4:'four',5:'five',6:'six',7:'seven',8:'eight',9:'nine',10:'ten',
    11:'eleven',12:'twelve',13:'thirteen',14:'fourteen',15:'fifteen',16:'sixteen',17:'seventeen',18:'eighteen',19:'nineteen',20:'twenty',
    30:'thirty',40:'fourty',50:'fifty',60:'sixty',70:'seventy',80:'eighty',90:'ninety',0:''} # this and above 2 lines are actually single line
    return pairs[num]

def toText(num,unit):
    n=int(num)# this line can be removed
    ans=""
    if n <=20:
        ans= giveText(n)
    else:
        ans= giveText(n-(n%10))+" "+giveText((n%10))
    ans=ans.strip()
    if len(ans)>0:
        return " "+ans+" "+unit
    else:
        return " "

num="99,99,99,999"# use raw_input()
num=num.replace(",","")# to remove ','
try:
    num=str(int(num)) # to check valid number
except:
    print "Invalid"
    exit()

while len(num)<9: # i want fix length so no need to check it again
    num="0"+num

ans=toText( num[0:2],"Crore")+toText(num[2:4],"Lakh")+toText(num[4:6],"Thousand")+toText(num[6:7],"Hundred")+toText(num[7:9],"")
print ans.strip()

What is the scope of variables in JavaScript?

run the code. hope this will give an idea about scoping

Name = 'global data';
document.Name = 'current document data';
(function(window,document){
var Name = 'local data';
var myObj = {
    Name: 'object data',
    f: function(){
        alert(this.Name);
    }
};

myObj.newFun = function(){
    alert(this.Name);
}

function testFun(){
    alert("Window Scope : " + window.Name + 
          "\nLocal Scope : " + Name + 
          "\nObject Scope : " + this.Name + 
          "\nCurrent document Scope : " + document.Name
         );
}


testFun.call(myObj);
})(window,document);

Android global variable

Easy!!!!

Those variable you wanna access as global variable, you can declare them as static variables. And now, you can access those variables by using

classname.variablename;

public class MyProperties {
private static MyProperties mInstance= null;

static int someValueIWantToKeep;

protected MyProperties(){}

public static synchronized MyProperties getInstance(){
    if(null == mInstance){
        mInstance = new MyProperties();
    }
    return mInstance;
}

}

MyProperites.someValueIWantToKeep;

Thats It! ;)

redirect to current page in ASP.Net

Why Server.Transfer? Response.Redirect(Request.RawUrl) would get you what you need.

Spring Boot War deployed to Tomcat

After following the guide (or using Spring Initializr), I had a WAR that worked on my local computer, but didn't work remote (running on Tomcat).

There was no error message, it just said "Spring servlet initializer was found", but didn't do anything at all.

17-Aug-2016 16:58:13.552 INFO [main] org.apache.catalina.core.StandardEngine.startInternal Starting Servlet Engine: Apache Tomcat/8.5.4
17-Aug-2016 16:58:13.593 INFO [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployWAR Deploying web application archive /opt/tomcat/webapps/ROOT.war
17-Aug-2016 16:58:16.243 INFO [localhost-startStop-1] org.apache.jasper.servlet.TldScanner.scanJars At least one JAR was scanned for TLDs yet contained no TLDs. Enable debug logging for this logger for a complete list of JARs that were scanned but no TLDs were found in them. Skipping unneeded JARs during scanning can improve startup time and JSP compilation time.

and

17-Aug-2016 16:58:16.301 INFO [localhost-startStop-1] org.apache.catalina.core.ApplicationContext.log 2 Spring WebApplicationInitializers detected on classpath
17-Aug-2016 16:58:21.471 INFO [localhost-startStop-1] org.apache.catalina.core.ApplicationContext.log Initializing Spring embedded WebApplicationContext
17-Aug-2016 16:58:25.133 INFO [localhost-startStop-1] org.apache.catalina.core.ApplicationContext.log ContextListener: contextInitialized()
17-Aug-2016 16:58:25.133 INFO [localhost-startStop-1] org.apache.catalina.core.ApplicationContext.log SessionListener: contextInitialized()

Nothing else happened. Spring Boot just didn't run.

Apparently I compiled the server with Java 1.8, and the remote computer had Java 1.7.

After compiling with Java 1.7, it started working.

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    <java.version>1.7</java.version> <!-- added this line -->
    <start-class>myapp.SpringApplication</start-class>
</properties>

How to identify a strong vs weak relationship on ERD?

The relationship Room to Class is considered weak (non-identifying) because the primary key components CID and DATE of entity Class doesn't contain the primary key RID of entity Room (in this case primary key of Room entity is a single component, but even if it was a composite key, one component of it also fulfills the condition).

However, for instance, in the case of the relationship Class and Class_Ins we see that is a strong (identifying) relationship because the primary key components EmpID and CID and DATE of Class_Ins contains a component of the primary key Class (in this case it contains both components CID and DATE).

What's the best way to validate an XML file against an XSD file?

I had to validate an XML against XSD just one time, so I tried XMLFox. I found it to be very confusing and weird. The help instructions didn't seem to match the interface.

I ended up using LiquidXML Studio 2008 (v6) which was much easier to use and more immediately familiar (the UI is very similar to Visual Basic 2008 Express, which I use frequently). The drawback: the validation capability is not in the free version, so I had to use the 30 day trial.

Appending a vector to a vector

a.insert(a.end(), b.begin(), b.end());

or

a.insert(std::end(a), std::begin(b), std::end(b));

The second variant is a more generically applicable solution, as b could also be an array. However, it requires C++11. If you want to work with user-defined types, use ADL:

using std::begin, std::end;
a.insert(end(a), begin(b), end(b));

format a number with commas and decimals in C# (asp.net MVC3)

All that is needed is "#,0.00", c# does the rest.

Num.ToString("#,0.00"")

  • The "#,0" formats the thousand separators
  • "0.00" forces two decimal points

PHP "pretty print" json_encode

Hmmm $array = json_decode($json, true); will make your string an array which is easy to print nicely with print_r($array, true);

But if you really want to prettify your json... Check this out

Reading file using fscanf() in C

In your code:

while(fscanf(fp,"%s %c",item,&status) == 1)  

why 1 and not 2? The scanf functions return the number of objects read.

Check if number is prime number

This is the simplest way to find prime number is

for(i=2; i<num; i++)
        {
            if(num%i == 0)
            {
                count++;
                break;
            }
        }
        if(count == 0)
        {
            Console.WriteLine("This is a Prime Number");
        }
        else
        {
            Console.WriteLine("This is not a Prime Number");
        }

Helpful Link: https://codescracker.com/java/program/java-program-check-prime.htm

syntax for creating a dictionary into another dictionary in python

You can declare a dictionary inside a dictionary by nesting the {} containers:

d = {'dict1': {'foo': 1, 'bar': 2}, 'dict2': {'baz': 3, 'quux': 4}}

And then you can access the elements using the [] syntax:

print d['dict1']           # {'foo': 1, 'bar': 2}
print d['dict1']['foo']    # 1
print d['dict2']['quux']   # 4

Given the above, if you want to add another dictionary to the dictionary, it can be done like so:

d['dict3'] = {'spam': 5, 'ham': 6}

or if you prefer to add items to the internal dictionary one by one:

d['dict4'] = {}
d['dict4']['king'] = 7
d['dict4']['queen'] = 8

Where do I configure log4j in a JUnit test class?

The LogManager class determines which log4j config to use in a static block which runs when the class is loaded. There are three options intended for end-users:

  1. If you specify log4j.defaultInitOverride to false, it will not configure log4j at all.
  2. Specify the path to the configuration file manually yourself and override the classpath search. You can specify the location of the configuration file directly by using the following argument to java:

    -Dlog4j.configuration=<path to properties file>

    in your test runner configuration.

  3. Allow log4j to scan the classpath for a log4j config file during your test. (the default)

See also the online documentation.

Safely turning a JSON string into an object

Try this.This one is written in typescript.

         export function safeJsonParse(str: string) {
               try {
                 return JSON.parse(str);
                   } catch (e) {
                 return str;
                 }
           }

Is std::vector copying the objects with a push_back?

Yes, std::vector<T>::push_back() creates a copy of the argument and stores it in the vector. If you want to store pointers to objects in your vector, create a std::vector<whatever*> instead of std::vector<whatever>.

However, you need to make sure that the objects referenced by the pointers remain valid while the vector holds a reference to them (smart pointers utilizing the RAII idiom solve the problem).

Get List of connected USB Devices

This is a much simpler example for people only looking for removable usb drives.

using System.IO;

foreach (DriveInfo drive in DriveInfo.GetDrives())
{
    if (drive.DriveType == DriveType.Removable)
    {
        Console.WriteLine(string.Format("({0}) {1}", drive.Name.Replace("\\",""), drive.VolumeLabel));
    }
}

SQL JOIN, GROUP BY on three tables to get totals

I am not sure I got you but this might be what you are looking for:

SELECT i.invoiceid, sum(case when i.amount is not null then i.amount else 0 end), sum(case when i.amount is not null then i.amount else 0 end) - sum(case when p.amount is not null then p.amount else 0 end) AS amountdue
FROM invoices i
LEFT JOIN invoicepayments ip ON i.invoiceid = ip.invoiceid
LEFT JOIN payments p ON ip.paymentid = p.paymentid
LEFT JOIN customers c ON p.customerid = c.customerid
WHERE c.customernumber = '100'
GROUP BY i.invoiceid

This would get you the amounts sums in case there are multiple payment rows for each invoice

Create a File object in memory from a string in Java

The File class represents the "idea" of a file, not an actual handle to use for I/O. This is why the File class has a .exists() method, to tell you if the file exists or not. (How can you have a File object that doesn't exist?)

By contrast, constructing a new FileInputStream(new File("/my/file")) gives you an actual stream to read bytes from.

How to convert an object to a byte array in C#

To convert an object to a byte array:

// Convert an object to a byte array
public static byte[] ObjectToByteArray(Object obj)
{
    BinaryFormatter bf = new BinaryFormatter();
    using (var ms = new MemoryStream())
    {
        bf.Serialize(ms, obj);
        return ms.ToArray();
    }
}

You just need copy this function to your code and send to it the object that you need to convert to a byte array. If you need convert the byte array to an object again you can use the function below:

// Convert a byte array to an Object
public static Object ByteArrayToObject(byte[] arrBytes)
{
    using (var memStream = new MemoryStream())
    {
        var binForm = new BinaryFormatter();
        memStream.Write(arrBytes, 0, arrBytes.Length);
        memStream.Seek(0, SeekOrigin.Begin);
        var obj = binForm.Deserialize(memStream);
        return obj;
    }
}

You can use these functions with custom classes. You just need add the [Serializable] attribute in your class to enable serialization

Embedding JavaScript engine into .NET

V8.NET is a new kid on the block (as of April 2013) that more closely wraps the native V8 engine functionality. It allows for more control over the implementation.

How to split a file into equal parts, without breaking individual lines?

A simple solution for a simple question:

split -n l/5 your_file.txt

no need for scripting here.

From the man file, CHUNKS may be:

l/N     split into N files without splitting lines

Update

Not all unix dist include this flag. For example, it will not work in OSX. To use it, you can consider replacing the Mac OS X utilities with GNU core utilities.

Sorting an Array of int using BubbleSort

You need two loops to implement the Bubble Sort .

Sample code :

public static void bubbleSort(int[] numArray) {

    int n = numArray.length;
    int temp = 0;

    for (int i = 0; i < n; i++) {
        for (int j = 1; j < (n - i); j++) {

            if (numArray[j - 1] > numArray[j]) {
                temp = numArray[j - 1];
                numArray[j - 1] = numArray[j];
                numArray[j] = temp;
            }

        }
    }
}

How does jQuery work when there are multiple elements with the same ID value?

If you have multiple elements with same id or same name, just assign same class to those multiple elements and access them by index & perform your required operation.

  <div>
        <span id="a" class="demo">1</span>
        <span id="a" class="demo">2</span>
        <span>3</span>
    </div>

JQ:

$($(".demo")[0]).val("First span");
$($(".demo")[1]).val("Second span");

How do I get the Back Button to work with an AngularJS ui-router state machine?

browser's back/forward button solution
I encountered the same problem and I solved it using the popstate event from the $window object and ui-router's $state object. A popstate event is dispatched to the window every time the active history entry changes.
The $stateChangeSuccess and $locationChangeSuccess events are not triggered on browser's button click even though the address bar indicates the new location.
So, assuming you've navigated from states main to folder to main again, when you hit back on the browser, you should be back to the folder route. The path is updated but the view is not and still displays whatever you have on main. try this:

angular
.module 'app', ['ui.router']
.run($state, $window) {

     $window.onpopstate = function(event) {

        var stateName = $state.current.name,
            pathname = $window.location.pathname.split('/')[1],
            routeParams = {};  // i.e.- $state.params

        console.log($state.current.name, pathname); // 'main', 'folder'

        if ($state.current.name.indexOf(pathname) === -1) {
            // Optionally set option.notify to false if you don't want 
            // to retrigger another $stateChangeStart event
            $state.go(
              $state.current.name, 
              routeParams,
              {reload:true, notify: false}
            );
        }
    };
}

back/forward buttons should work smoothly after that.

note: check browser compatibility for window.onpopstate() to be sure

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

On Mac OS X Yosemite just install:

Java SE Development Kit 8

and

Java Version 8 Update 25

It's all, work for me too! like gehev said , so simple !

Disable browsers vertical and horizontal scrollbars

(I can't comment yet, but wanted to share this):

Lyncee's code worked for me in desktop browser. However, on iPad (Chrome, iOS 9), it crashed the application. To fix it, I changed

document.documentElement.style.overflow = ...

to

document.body.style.overflow = ...

which solved my problem.

Git error when trying to push -- pre-receive hook declined

I'd bet that you are trying a non-fast-forward push and the hook blocks it. If that's the case, simply run git pull --rebase before pushing to rebase your local changes on the newest codebase.

What is the difference between server side cookie and client side cookie?

  1. Yes you can create cookies that can only be read on the server-side. These are called "HTTP Only" -cookies, as explained in other answers already

  2. No, there is no way (I know of) to create "cookies" that can be read only on the client-side. Cookies are meant to facilitate client-server communication.

  3. BUT, if you want something LIKE "client-only-cookies" there is a simple answer: Use "Local Storage".

Local Storage is actually syntactically simpler to use than cookies. A good simple summary of cookies vs. local storage can be found at:

https://courses.cs.washington.edu/courses/cse154/12au/lectures/slides/lecture21-client-storage.shtml#slide8

A point: You might use cookies created in JavaScript to store GUI-related things you only need on the client-side. BUT the cookie is sent to the server for EVERY request made, it becomes part of the http-request headers thus making the request contain more data and thus slower to send.

If your page has 50 resources like images and css-files and scripts then the cookie is (typically) sent with each request. More on this in Does every web request send the browser cookies?

Local storage does not have those data-transfer related disadvantages, it sends no data. It is great.

String to list in Python

Or for fun:

>>> ast.literal_eval('[%s]'%','.join(map(repr,s.split())))
['QH', 'QD', 'JC', 'KD', 'JS']
>>> 

ast.literal_eval

fatal error LNK1104: cannot open file 'kernel32.lib'

I just met and solved this problem by myself. My problem is a little different. I'm using visual studio on Windows 10. When I create the project, the Target Platform Version was automatically set to 10.0.15063.0. But there is no kernel32.lib for this version of SDK, neither are other necessary header files and lib files. So I modified the Target Platform Version to 8.1. And it worked.

Environment:

  • Windows 10
  • Visual Studio 2015
  • Visual C++

Solution:

  1. Open the project's Property Page;
  2. Navigate to General page;
  3. Modify Target Platform Version to the desired target platform (e.g. 8.1).

What is the difference between =Empty and IsEmpty() in VBA (Excel)?

I believe IsEmpty is just method that takes return value of Cell and checks if its Empty so: IsEmpty(.Cell(i,1)) does ->

return .Cell(i,1) <> Empty

@RequestParam vs @PathVariable

If the URL http://localhost:8080/MyApp/user/1234/invoices?date=12-05-2013 gets the invoices for user 1234 on December 5th, 2013, the controller method would look like:

@RequestMapping(value="/user/{userId}/invoices", method = RequestMethod.GET)
public List<Invoice> listUsersInvoices(
            @PathVariable("userId") int user,
            @RequestParam(value = "date", required = false) Date dateOrNull) {
  ...
}

Also, request parameters can be optional, and as of Spring 4.3.3 path variables can be optional as well. Beware though, this might change the URL path hierarchy and introduce request mapping conflicts. For example, would /user/invoices provide the invoices for user null or details about a user with ID "invoices"?

How to add default signature in Outlook

I have made this a Community Wiki answer because I could not have created it without PowerUser's research and the help in earlier comments.

I took PowerUser's Sub X and added

Debug.Print "n------"    'with different values for n
Debug.Print ObjMail.HTMLBody

after every statement. From this I discovered the signature is not within .HTMLBody until after ObjMail.Display and then only if I haven't added anything to the body.

I went back to PowerUser's earlier solution that used C:\Users\" & Environ("username") & "\AppData\Roaming\Microsoft\Signatures\Mysig.txt"). PowerUser was unhappy with this because he wanted his solution to work for others who would have different signatures.

My signature is in the same folder and I cannot find any option to change this folder. I have only one signature so by reading the only HTM file in this folder, I obtained my only/default signature.

I created an HTML table and inserted it into the signature immediately following the <body> element and set the html body to the result. I sent the email to myself and the result was perfectly acceptable providing you like my formatting which I included to check that I could.

My modified subroutine is:

Sub X()

  Dim OlApp As Outlook.Application
  Dim ObjMail As Outlook.MailItem

  Dim BodyHtml As String
  Dim DirSig As String
  Dim FileNameHTMSig As String
  Dim Pos1 As Long
  Dim Pos2 As Long
  Dim SigHtm As String

  DirSig = "C:\Users\" & Environ("username") & _
                               "\AppData\Roaming\Microsoft\Signatures"

  FileNameHTMSig = Dir$(DirSig & "\*.htm")

  ' Code to handle there being no htm signature or there being more than one

  SigHtm = GetBoiler(DirSig & "\" & FileNameHTMSig)
  Pos1 = InStr(1, LCase(SigHtm), "<body")

  ' Code to handle there being no body

  Pos2 = InStr(Pos1, LCase(SigHtm), ">")

  ' Code to handle there being no closing > for the body element

   BodyHtml = "<table border=0 width=""100%"" style=""Color: #0000FF""" & _
         " bgColor=#F0F0F0><tr><td align= ""center"">HTML table</td>" & _
         "</tr></table><br>"
  BodyHtml = Mid(SigHtm, 1, Pos2 + 1) & BodyHtml & Mid(SigHtm, Pos2 + 2)

  Set OlApp = Outlook.Application
  Set ObjMail = OlApp.CreateItem(olMailItem)
  ObjMail.BodyFormat = olFormatHTML
  ObjMail.Subject = "Subject goes here"
  ObjMail.Recipients.Add "my email address"
  ObjMail.Display

End Sub

Since both PowerUser and I have found our signatures in C:\Users\" & Environ("username") & "\AppData\Roaming\Microsoft\Signatures I suggest this is the standard location for any Outlook installation. Can this default be changed? I cannot find anything to suggest it can. The above code clearly needs some development but it does achieve PowerUser's objective of creating an email body containing an HTML table above a signature.

Insert json file into mongodb

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

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

JSON File: card_type_authorization.json

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

How does Subquery in select statement work in oracle

It's simple-

SELECT empname,
       empid,
       (SELECT COUNT (profileid)
          FROM profile
         WHERE profile.empid = employee.empid)
           AS number_of_profiles
  FROM employee;

It is even simpler when you use a table join like this:

  SELECT e.empname, e.empid, COUNT (p.profileid) AS number_of_profiles
    FROM employee e LEFT JOIN profile p ON e.empid = p.empid
GROUP BY e.empname, e.empid;

Explanation for the subquery:

Essentially, a subquery in a select gets a scalar value and passes it to the main query. A subquery in select is not allowed to pass more than one row and more than one column, which is a restriction. Here, we are passing a count to the main query, which, as we know, would always be only a number- a scalar value. If a value is not found, the subquery returns null to the main query. Moreover, a subquery can access columns from the from clause of the main query, as shown in my query where employee.empid is passed from the outer query to the inner query.


Edit:

When you use a subquery in a select clause, Oracle essentially treats it as a left join (you can see this in the explain plan for your query), with the cardinality of the rows being just one on the right for every row in the left.


Explanation for the left join

A left join is very handy, especially when you want to replace the select subquery due to its restrictions. There are no restrictions here on the number of rows of the tables in either side of the LEFT JOIN keyword.

For more information read Oracle Docs on subqueries and left join or left outer join.

How do I separate an integer into separate digits in an array in JavaScript?

This will work for a number greater than 0. You don't need to convert the number into string:

function convertNumberToDigitArray(number) {
    const arr = [];
    while (number > 0) {
        let lastDigit = number % 10;
        arr.push(lastDigit);
        number = Math.floor(number / 10);
    }
    return arr;
}

Force Internet Explorer to use a specific Java Runtime Environment install?

For the server-side solution (which your question was originally ambiguous about), this page at sun lists one way to specify a JRE. Specifically,

<OBJECT 
  classid="clsid:8AD9C840-044E-11D1-B3E9-00805F499D93"
  width="200" height="200">
  <PARAM name="code" value="Applet1.class">
</OBJECT>

The classid attribute identifies which version of Java Plug-in to use.

Following is an alternative form of the classid attribute:

classid="clsid:CAFEEFAC-xxxx-yyyy-zzzz-ABCDEFFEDCBA"

In this form, "xxxx", "yyyy", and "zzzz" are four-digit numbers that identify the specific version of Java Plug-in to be used.

For example, to use Java Plug-in version 1.5.0, you specify:

classid="clsid:CAFEEFAC-0015-0000-0000-ABCDEFFEDCBA"

Get a list of all the files in a directory (recursive)

This code works for me:

import groovy.io.FileType

def list = []

def dir = new File("path_to_parent_dir")
dir.eachFileRecurse (FileType.FILES) { file ->
  list << file
}

Afterwards the list variable contains all files (java.io.File) of the given directory and its subdirectories:

list.each {
  println it.path
}

How can I list all collections in the MongoDB shell?

You can do...

JavaScript (shell):

db.getCollectionNames()

Node.js:

db.listCollections()

Non-JavaScript (shell only):

show collections

The reason I call that non-JavaScript is because:

$ mongo prodmongo/app --eval "show collections"
MongoDB shell version: 3.2.10
connecting to: prodmongo/app
2016-10-26T19:34:34.886-0400 E QUERY    [thread1] SyntaxError: missing ; before statement @(shell eval):1:5

$ mongo prodmongo/app --eval "db.getCollectionNames()"
MongoDB shell version: 3.2.10
connecting to: prodmongo/app
[
    "Profiles",
    "Unit_Info"
]

If you really want that sweet, sweet show collections output, you can:

$ mongo prodmongo/app --eval "db.getCollectionNames().join('\n')"
MongoDB shell version: 3.2.10
connecting to: prodmongo/app
Profiles
Unit_Info

Angular2: Cannot read property 'name' of undefined

This line

<h2>{{hero.name}} details!</h2>

is outside *ngFor and there is no hero therefore hero.name fails.

How can I check the current status of the GPS receiver?

The GPS icon seems to change its state according to received broadcast intents. You can change its state yourself with the following code samples:

Notify that the GPS has been enabled:

Intent intent = new Intent("android.location.GPS_ENABLED_CHANGE");
intent.putExtra("enabled", true);
sendBroadcast(intent);

Notify that the GPS is receiving fixes:

Intent intent = new Intent("android.location.GPS_FIX_CHANGE");
intent.putExtra("enabled", true);
sendBroadcast(intent);

Notify that the GPS is no longer receiving fixes:

Intent intent = new Intent("android.location.GPS_FIX_CHANGE");
intent.putExtra("enabled", false);
sendBroadcast(intent);

Notify that the GPS has been disabled:

Intent intent = new Intent("android.location.GPS_ENABLED_CHANGE");
intent.putExtra("enabled", false);
sendBroadcast(intent);

Example code to register receiver to the intents:

// MyReceiver must extend BroadcastReceiver
MyReceiver receiver = new MyReceiver();
IntentFilter filter = new IntentFilter("android.location.GPS_ENABLED_CHANGE");
filter.addAction("android.location.GPS_FIX_CHANGE");
registerReceiver(receiver, filter);

By receiving these broadcast intents you can notice the changes in GPS status. However, you will be notified only when the state changes. Thus it is not possible to determine the current state using these intents.

How to declare a constant map in Golang?

And as suggested above by Siu Ching Pong -Asuka Kenji with the function which in my opinion makes more sense and leaves you with the convenience of the map type without the function wrapper around:

   // romanNumeralDict returns map[int]string dictionary, since the return
       // value is always the same it gives the pseudo-constant output, which
       // can be referred to in the same map-alike fashion.
       var romanNumeralDict = func() map[int]string { return map[int]string {
            1000: "M",
            900:  "CM",
            500:  "D",
            400:  "CD",
            100:  "C",
            90:   "XC",
            50:   "L",
            40:   "XL",
            10:   "X",
            9:    "IX",
            5:    "V",
            4:    "IV",
            1:    "I",
          }
        }

        func printRoman(key int) {
          fmt.Println(romanNumeralDict()[key])
        }

        func printKeyN(key, n int) {
          fmt.Println(strings.Repeat(romanNumeralDict()[key], n))
        }

        func main() {
          printRoman(1000)
          printRoman(50)
          printKeyN(10, 3)
        }

Try this at play.golang.org.

SQL Server 2008- Get table constraints

I used the following query to retrieve the information of constraints in the SQL Server 2012, and works perfectly. I hope it would be useful for you.

SELECT 
    tab.name AS [Table]
    ,tab.id AS [Table Id]
    ,constr.name AS [Constraint Name]
    ,constr.xtype AS [Constraint Type]
    ,CASE constr.xtype WHEN 'PK' THEN 'Primary Key' WHEN 'UQ' THEN 'Unique' ELSE '' END AS [Constraint Name]
    ,i.index_id AS [Index ID]
    ,ic.column_id AS [Column ID]
    ,clmns.name AS [Column Name]
    ,clmns.max_length AS [Column Max Length]
    ,clmns.precision AS [Column Precision]
    ,CASE WHEN clmns.is_nullable = 0 THEN 'NO' ELSE 'YES' END AS [Column Nullable]
    ,CASE WHEN clmns.is_identity = 0 THEN 'NO' ELSE 'YES' END AS [Column IS IDENTITY]
FROM SysObjects AS tab
INNER JOIN SysObjects AS constr ON(constr.parent_obj = tab.id AND constr.type = 'K')
INNER JOIN sys.indexes AS i ON( (i.index_id > 0 and i.is_hypothetical = 0) AND (i.object_id=tab.id) AND i.name = constr.name )
INNER JOIN sys.index_columns AS ic ON (ic.column_id > 0 and (ic.key_ordinal > 0 or ic.partition_ordinal = 0 or ic.is_included_column != 0)) 
                                    AND (ic.index_id=CAST(i.index_id AS int) 
                                    AND ic.object_id=i.object_id)
INNER JOIN sys.columns AS clmns ON clmns.object_id = ic.object_id and clmns.column_id = ic.column_id
WHERE tab.xtype = 'U'
ORDER BY tab.name

SQL Server 2008 - IF NOT EXISTS INSERT ELSE UPDATE

You need to replace it as WHERE clockDate = { fn CURRENT_DATE() } AND userName = 'test'. Please remove extra ")" from { fn CURRENT_DATE() })

How to workaround 'FB is not defined'?

Assuming FB is a variable containing the Facebook object, I'd try something like this:

if (typeof(FB) != 'undefined'
     && FB != null ) {
    // run the app
} else {
    // alert the user
}

In order to test that something is undefined in plain old JavaScript, you should use the "typeof" operator. The sample you show where you just compare it to the string 'undefined' will evaluate to false unless your FB object really does contain the string 'undefined'!

As an aside, you may wish to use various tools like Firebug (in Firefox) to see if you can work out why the Facebook file is not loading.

How to add image in a TextView text?

com/xyz/customandroid/ TextViewWithImages .java:

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.content.Context;
import android.text.Spannable;
import android.text.style.ImageSpan;
import android.util.AttributeSet;
import android.util.Log;
import android.widget.TextView;

public class TextViewWithImages extends TextView {

    public TextViewWithImages(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }
    public TextViewWithImages(Context context, AttributeSet attrs) {
        super(context, attrs);
    }
    public TextViewWithImages(Context context) {
        super(context);
    }
    @Override
    public void setText(CharSequence text, BufferType type) {
        Spannable s = getTextWithImages(getContext(), text);
        super.setText(s, BufferType.SPANNABLE);
    }

    private static final Spannable.Factory spannableFactory = Spannable.Factory.getInstance();

    private static boolean addImages(Context context, Spannable spannable) {
        Pattern refImg = Pattern.compile("\\Q[img src=\\E([a-zA-Z0-9_]+?)\\Q/]\\E");
        boolean hasChanges = false;

        Matcher matcher = refImg.matcher(spannable);
    while (matcher.find()) {
        boolean set = true;
        for (ImageSpan span : spannable.getSpans(matcher.start(), matcher.end(), ImageSpan.class)) {
            if (spannable.getSpanStart(span) >= matcher.start()
             && spannable.getSpanEnd(span) <= matcher.end()
               ) {
                spannable.removeSpan(span);
            } else {
                set = false;
                break;
            }
        }
        String resname = spannable.subSequence(matcher.start(1), matcher.end(1)).toString().trim();
        int id = context.getResources().getIdentifier(resname, "drawable", context.getPackageName());
        if (set) {
            hasChanges = true;
            spannable.setSpan(  new ImageSpan(context, id),
                                matcher.start(),
                                matcher.end(),
                                Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
                             );
        }
    }

        return hasChanges;
    }
    private static Spannable getTextWithImages(Context context, CharSequence text) {
        Spannable spannable = spannableFactory.newSpannable(text);
        addImages(context, spannable);
        return spannable;
    }
}

Use:

in res/layout/mylayout.xml:

            <com.xyz.customandroid.TextViewWithImages
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textColor="#FFFFFF00"
                android:text="@string/can_try_again"
                android:textSize="12dip"
                style=...
                />

Note that if you place TextViewWithImages.java in some location other than com/xyz/customandroid/, you also must change the package name, com.xyz.customandroid above.

in res/values/strings.xml:

<string name="can_try_again">Press [img src=ok16/] to accept or [img src=retry16/] to retry</string>

where ok16.png and retry16.png are icons in the res/drawable/ folder

BULK INSERT with identity (auto-increment) column

My solution is to add the ID field as the LAST field in the table, thus bulk insert ignores it and it gets automatic values. Clean and simple ...

For instance, if inserting into a temp table:

CREATE TABLE #TempTable 
(field1 varchar(max), field2 varchar(max), ... 
ROW_ID int IDENTITY(1,1) NOT NULL)

Note that the ROW_ID field MUST always be specified as LAST field!

Excel VBA select range at last row and column

Is this what you are trying? I have commented the code so that you will not have any problem understanding it.

Sub Sample()
    Dim ws As Worksheet
    Dim lRow As Long, lCol As Long
    Dim rng As Range

    '~~> Set this to the relevant worksheet
    Set ws = [Sheet1]

    With ws
        '~~> Get the last row and last column
        lRow = .Range("A" & .Rows.Count).End(xlUp).Row
        lCol = .Cells(1, .Columns.Count).End(xlToLeft).Column

        '~~> Set the range
        Set rng = .Range(.Cells(lRow, 1), .Cells(lRow, lCol))

        With rng
            Debug.Print .Address
            '
            '~~> What ever you want to do with the address
            '
        End With
    End With
End Sub

BTW I am assuming that LastRow is the same for all rows and same goes for the columns. If that is not the case then you will have use .Find to find the Last Row and the Last Column. You might want to see THIS

What is "Connect Timeout" in sql server connection string?

Connection Timeout=30 means that the database server has 30 seconds to establish a connection.

Connection Timeout specifies the time limit (in seconds), within which the connection to the specified server must be made, otherwise an exception is thrown i.e. It specifies how long you will allow your program to be held up while it establishes a database connection.

DataSource=server;
InitialCatalog=database;
UserId=username;
Password=password;
Connection Timeout=30

SqlConnection.ConnectionTimeout. specifies how many seconds the SQL Server service has to respond to a connection attempt. This is always set as part of the connection string.

Notes:

  • The value is expressed in seconds, not milliseconds.

  • The default value is 30 seconds.

  • A value of 0 means to wait indefinitely and never time out.

In addition, SqlCommand.CommandTimeout specifies the timeout value of a specific query running on SQL Server, however this is set via the SqlConnection object/setting (depending on your programming language), and not in the connection string i.e. It specifies how long you will allow your program to be held up while the command is run.

Send file using POST from a Python script

The only thing that stops you from using urlopen directly on a file object is the fact that the builtin file object lacks a len definition. A simple way is to create a subclass, which provides urlopen with the correct file. I have also modified the Content-Type header in the file below.

import os
import urllib2
class EnhancedFile(file):
    def __init__(self, *args, **keyws):
        file.__init__(self, *args, **keyws)

    def __len__(self):
        return int(os.fstat(self.fileno())[6])

theFile = EnhancedFile('a.xml', 'r')
theUrl = "http://example.com/abcde"
theHeaders= {'Content-Type': 'text/xml'}

theRequest = urllib2.Request(theUrl, theFile, theHeaders)

response = urllib2.urlopen(theRequest)

theFile.close()


for line in response:
    print line

How to sort by Date with DataTables jquery plugin?

Datatables only can order by DateTime in "ISO-8601" format, so you have to convert your date in "date-order" to this format (example using Razor):

<td data-sort="@myDate.ToString("o")">@myDate.ToShortDateString() - @myDate.ToShortTimeString()</td>

How to get the public IP address of a user in C#

For Web Applications ( ASP.NET MVC and WebForm )

/// <summary>
/// Get current user ip address.
/// </summary>
/// <returns>The IP Address</returns>
public static string GetUserIPAddress()
{
    var context = System.Web.HttpContext.Current;
    string ip = String.Empty;

    if (context.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != null)
        ip = context.Request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString();
    else if (!String.IsNullOrWhiteSpace(context.Request.UserHostAddress))
        ip = context.Request.UserHostAddress;

    if (ip == "::1")
        ip = "127.0.0.1";

    return ip;
}

For Windows Applications ( Windows Form, Console, Windows Service , ... )

    static void Main(string[] args)
    {
        HTTPGet req = new HTTPGet();
        req.Request("http://checkip.dyndns.org");
        string[] a = req.ResponseBody.Split(':');
        string a2 = a[1].Substring(1);
        string[] a3=a2.Split('<');
        string a4 = a3[0];
        Console.WriteLine(a4);
        Console.ReadLine();
    }

Run java jar file on a server as background process

You can try this:

#!/bin/sh
nohup java -jar /web/server.jar &

The & symbol, switches the program to run in the background.

The nohup utility makes the command passed as an argument run in the background even after you log out.

How to decrypt hash stored by bcrypt

You simply can't.

bcrypt uses salting, of different rounds, I use 10 usually.

bcrypt.hash(req.body.password,10,function(error,response){ }

This 10 is salting random string into your password.

live output from subprocess command

Solution 1: Log stdout AND stderr concurrently in realtime

A simple solution which logs both stdout AND stderr concurrently, line-by-line in realtime into a log file.

import subprocess as sp
from concurrent.futures import ThreadPoolExecutor


def log_popen_pipe(p, stdfile):

    with open("mylog.txt", "w") as f:

        while p.poll() is None:
            f.write(stdfile.readline())
            f.flush()

        # Write the rest from the buffer
        f.write(stdfile.read())


with sp.Popen(["ls"], stdout=sp.PIPE, stderr=sp.PIPE, text=True) as p:

    with ThreadPoolExecutor(2) as pool:
        r1 = pool.submit(log_popen_pipe, p, p.stdout)
        r2 = pool.submit(log_popen_pipe, p, p.stderr)
        r1.result()
        r2.result()

Solution 2: A function read_popen_pipes() that allows you to iterate over both pipes (stdout/stderr), concurrently in realtime

import subprocess as sp
from queue import Queue, Empty
from concurrent.futures import ThreadPoolExecutor


def enqueue_output(file, queue):
    for line in iter(file.readline, ''):
        queue.put(line)
    file.close()


def read_popen_pipes(p):

    with ThreadPoolExecutor(2) as pool:
        q_stdout, q_stderr = Queue(), Queue()

        pool.submit(enqueue_output, p.stdout, q_stdout)
        pool.submit(enqueue_output, p.stderr, q_stderr)

        while True:

            if p.poll() is not None and q_stdout.empty() and q_stderr.empty():
                break

            out_line = err_line = ''

            try:
                out_line = q_stdout.get_nowait()
                err_line = q_stderr.get_nowait()
            except Empty:
                pass

            yield (out_line, err_line)

# The function in use:

with sp.Popen(["ls"], stdout=sp.PIPE, stderr=sp.PIPE, text=True) as p:

    for out_line, err_line in read_popen_pipes(p):
        print(out_line, end='')
        print(err_line, end='')

    p.poll()

how to add button click event in android studio

Different ways to handle button event

Button btn1 = (Button)findViewById(R.id.button1);
btn1.setOnClickListener(new View.OnClickListener() {            
        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            Toast.makeText(context, "Button 1", 
     Toast.LENGTH_LONG).show();
        }
    });

[Check this article for more details about button event handlers]

Android Color Picker

You can use the following code, it will give you same look as http://code.google.com/p/color-picker-view/

public class ColorPickerDialog extends Dialog {

public interface OnColorChangedListener {
    void colorChanged(String key, int color);
}

private OnColorChangedListener mListener;
private int mInitialColor, mDefaultColor;
private String mKey;

private static class ColorPickerView extends View {
    private Paint mPaint;
    private float mCurrentHue = 0;
    private int mCurrentX = 0, mCurrentY = 0;
    private int mCurrentColor, mDefaultColor;
    private final int[] mHueBarColors = new int[258];
    private int[] mMainColors = new int[65536];
    private OnColorChangedListener mListener;

    ColorPickerView(Context c, OnColorChangedListener l, int color,
            int defaultColor) {
        super(c);
        mListener = l;
        mDefaultColor = defaultColor;

        // Get the current hue from the current color and update the main
        // color field
        float[] hsv = new float[3];
        Color.colorToHSV(color, hsv);
        mCurrentHue = hsv[0];
        updateMainColors();

        mCurrentColor = color;

        // Initialize the colors of the hue slider bar
        int index = 0;
        for (float i = 0; i < 256; i += 256 / 42) // Red (#f00) to pink
                                                    // (#f0f)
        {
            mHueBarColors[index] = Color.rgb(255, 0, (int) i);
            index++;
        }
        for (float i = 0; i < 256; i += 256 / 42) // Pink (#f0f) to blue
                                                    // (#00f)
        {
            mHueBarColors[index] = Color.rgb(255 - (int) i, 0, 255);
            index++;
        }
        for (float i = 0; i < 256; i += 256 / 42) // Blue (#00f) to light
                                                    // blue (#0ff)
        {
            mHueBarColors[index] = Color.rgb(0, (int) i, 255);
            index++;
        }
        for (float i = 0; i < 256; i += 256 / 42) // Light blue (#0ff) to
                                                    // green (#0f0)
        {
            mHueBarColors[index] = Color.rgb(0, 255, 255 - (int) i);
            index++;
        }
        for (float i = 0; i < 256; i += 256 / 42) // Green (#0f0) to yellow
                                                    // (#ff0)
        {
            mHueBarColors[index] = Color.rgb((int) i, 255, 0);
            index++;
        }
        for (float i = 0; i < 256; i += 256 / 42) // Yellow (#ff0) to red
                                                    // (#f00)
        {
            mHueBarColors[index] = Color.rgb(255, 255 - (int) i, 0);
            index++;
        }

        // Initializes the Paint that will draw the View
        mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        mPaint.setTextAlign(Paint.Align.CENTER);
        mPaint.setTextSize(12);
    }

    // Get the current selected color from the hue bar
    private int getCurrentMainColor() {
        int translatedHue = 255 - (int) (mCurrentHue * 255 / 360);
        int index = 0;
        for (float i = 0; i < 256; i += 256 / 42) {
            if (index == translatedHue)
                return Color.rgb(255, 0, (int) i);
            index++;
        }
        for (float i = 0; i < 256; i += 256 / 42) {
            if (index == translatedHue)
                return Color.rgb(255 - (int) i, 0, 255);
            index++;
        }
        for (float i = 0; i < 256; i += 256 / 42) {
            if (index == translatedHue)
                return Color.rgb(0, (int) i, 255);
            index++;
        }
        for (float i = 0; i < 256; i += 256 / 42) {
            if (index == translatedHue)
                return Color.rgb(0, 255, 255 - (int) i);
            index++;
        }
        for (float i = 0; i < 256; i += 256 / 42) {
            if (index == translatedHue)
                return Color.rgb((int) i, 255, 0);
            index++;
        }
        for (float i = 0; i < 256; i += 256 / 42) {
            if (index == translatedHue)
                return Color.rgb(255, 255 - (int) i, 0);
            index++;
        }
        return Color.RED;
    }

    // Update the main field colors depending on the current selected hue
    private void updateMainColors() {
        int mainColor = getCurrentMainColor();
        int index = 0;
        int[] topColors = new int[256];
        for (int y = 0; y < 256; y++) {
            for (int x = 0; x < 256; x++) {
                if (y == 0) {
                    mMainColors[index] = Color.rgb(
                            255 - (255 - Color.red(mainColor)) * x / 255,
                            255 - (255 - Color.green(mainColor)) * x / 255,
                            255 - (255 - Color.blue(mainColor)) * x / 255);
                    topColors[x] = mMainColors[index];
                } else
                    mMainColors[index] = Color.rgb(
                            (255 - y) * Color.red(topColors[x]) / 255,
                            (255 - y) * Color.green(topColors[x]) / 255,
                            (255 - y) * Color.blue(topColors[x]) / 255);
                index++;
            }
        }
    }

    @Override
    protected void onDraw(Canvas canvas) {
        int translatedHue = 255 - (int) (mCurrentHue * 255 / 360);
        // Display all the colors of the hue bar with lines
        for (int x = 0; x < 256; x++) {
            // If this is not the current selected hue, display the actual
            // color
            if (translatedHue != x) {
                mPaint.setColor(mHueBarColors[x]);
                mPaint.setStrokeWidth(1);
            } else // else display a slightly larger black line
            {
                mPaint.setColor(Color.BLACK);
                mPaint.setStrokeWidth(3);
            }
            canvas.drawLine(x + 10, 0, x + 10, 40, mPaint);
            // canvas.drawLine(0, x+10, 40, x+10, mPaint);
        }

        // Display the main field colors using LinearGradient
        for (int x = 0; x < 256; x++) {
            int[] colors = new int[2];
            colors[0] = mMainColors[x];
            colors[1] = Color.BLACK;
            Shader shader = new LinearGradient(0, 50, 0, 306, colors, null,
                    Shader.TileMode.REPEAT);
            mPaint.setShader(shader);
            canvas.drawLine(x + 10, 50, x + 10, 306, mPaint);
        }
        mPaint.setShader(null);

        // Display the circle around the currently selected color in the
        // main field
        if (mCurrentX != 0 && mCurrentY != 0) {
            mPaint.setStyle(Paint.Style.STROKE);
            mPaint.setColor(Color.BLACK);
            canvas.drawCircle(mCurrentX, mCurrentY, 10, mPaint);
        }

        // Draw a 'button' with the currently selected color
        mPaint.setStyle(Paint.Style.FILL);
        mPaint.setColor(mCurrentColor);
        canvas.drawRect(10, 316, 138, 356, mPaint);

        // Set the text color according to the brightness of the color
        if (Color.red(mCurrentColor) + Color.green(mCurrentColor)
                + Color.blue(mCurrentColor) < 384)
            mPaint.setColor(Color.WHITE);
        else
            mPaint.setColor(Color.BLACK);
        canvas.drawText(
                getResources()
                        .getString(R.string.settings_bg_color_confirm), 74,
                340, mPaint);

        // Draw a 'button' with the default color
        mPaint.setStyle(Paint.Style.FILL);
        mPaint.setColor(mDefaultColor);
        canvas.drawRect(138, 316, 266, 356, mPaint);

        // Set the text color according to the brightness of the color
        if (Color.red(mDefaultColor) + Color.green(mDefaultColor)
                + Color.blue(mDefaultColor) < 384)
            mPaint.setColor(Color.WHITE);
        else
            mPaint.setColor(Color.BLACK);
        canvas.drawText(
                getResources().getString(
                        R.string.settings_default_color_confirm), 202, 340,
                mPaint);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        setMeasuredDimension(276, 366);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (event.getAction() != MotionEvent.ACTION_DOWN)
            return true;
        float x = event.getX();
        float y = event.getY();

        // If the touch event is located in the hue bar
        if (x > 10 && x < 266 && y > 0 && y < 40) {
            // Update the main field colors
            mCurrentHue = (255 - x) * 360 / 255;
            updateMainColors();

            // Update the current selected color
            int transX = mCurrentX - 10;
            int transY = mCurrentY - 60;
            int index = 256 * (transY - 1) + transX;
            if (index > 0 && index < mMainColors.length)
                mCurrentColor = mMainColors[256 * (transY - 1) + transX];

            // Force the redraw of the dialog
            invalidate();
        }

        // If the touch event is located in the main field
        if (x > 10 && x < 266 && y > 50 && y < 306) {
            mCurrentX = (int) x;
            mCurrentY = (int) y;
            int transX = mCurrentX - 10;
            int transY = mCurrentY - 60;
            int index = 256 * (transY - 1) + transX;
            if (index > 0 && index < mMainColors.length) {
                // Update the current color
                mCurrentColor = mMainColors[index];
                // Force the redraw of the dialog
                invalidate();
            }
        }

        // If the touch event is located in the left button, notify the
        // listener with the current color
        if (x > 10 && x < 138 && y > 316 && y < 356)
            mListener.colorChanged("", mCurrentColor);

        // If the touch event is located in the right button, notify the
        // listener with the default color
        if (x > 138 && x < 266 && y > 316 && y < 356)
            mListener.colorChanged("", mDefaultColor);

        return true;
    }
}

public ColorPickerDialog(Context context, OnColorChangedListener listener,
        String key, int initialColor, int defaultColor) {
    super(context);

    mListener = listener;
    mKey = key;
    mInitialColor = initialColor;
    mDefaultColor = defaultColor;
}

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    OnColorChangedListener l = new OnColorChangedListener() {
        public void colorChanged(String key, int color) {
            mListener.colorChanged(mKey, color);
            dismiss();
        }
    };

    setContentView(new ColorPickerView(getContext(), l, mInitialColor,
            mDefaultColor));
    setTitle(R.string.settings_bg_color_dialog);

    }
}

Can someone explain __all__ in Python?

__all__ is used to document the public API of a Python module. Although it is optional, __all__ should be used.

Here is the relevant excerpt from the Python language reference:

The public names defined by a module are determined by checking the module’s namespace for a variable named __all__; if defined, it must be a sequence of strings which are names defined or imported by that module. The names given in __all__ are all considered public and are required to exist. If __all__ is not defined, the set of public names includes all names found in the module’s namespace which do not begin with an underscore character ('_'). __all__ should contain the entire public API. It is intended to avoid accidentally exporting items that are not part of the API (such as library modules which were imported and used within the module).

PEP 8 uses similar wording, although it also makes it clear that imported names are not part of the public API when __all__ is absent:

To better support introspection, modules should explicitly declare the names in their public API using the __all__ attribute. Setting __all__ to an empty list indicates that the module has no public API.

[...]

Imported names should always be considered an implementation detail. Other modules must not rely on indirect access to such imported names unless they are an explicitly documented part of the containing module's API, such as os.path or a package's __init__ module that exposes functionality from submodules.

Furthermore, as pointed out in other answers, __all__ is used to enable wildcard importing for packages:

The import statement uses the following convention: if a package’s __init__.py code defines a list named __all__, it is taken to be the list of module names that should be imported when from package import * is encountered.

Select top 1 result using JPA

Try like this

String sql = "SELECT t FROM table t";
Query query = em.createQuery(sql);
query.setFirstResult(firstPosition);
query.setMaxResults(numberOfRecords);
List result = query.getResultList();

It should work

UPDATE*

You can also try like this

query.setMaxResults(1).getResultList();

How do I insert multiple checkbox values into a table?

I think this should work .. :)

<input type="checkbox" name="Days[]" value="Daily">Daily<br>
<input type="checkbox" name="Days[]" value="Sunday">Sunday<br>

Git stash pop- needs merge, unable to refresh index

The stash has already been applied to other files.

It is only app.coffee that you have to merge manually. Afterwards just run

git reset

to unstage the changes and keep on hacking.

Catching multiple exception types in one catch block

In PHP >= 7.1 this is possible. See this answer.


If you can modify the exceptions, use this answer.

If you can't, you could try catching all with Exception and then check which exception was thrown with instanceof.

try
{
    /* something */
}
catch( Exception $e )
{
    if ($e instanceof AError OR $e instanceof BError) {
       // It's either an A or B exception.
    } else {
        // Keep throwing it.
        throw $e;
    }
}

But it would probably be better to use multiple catch blocks as described in aforementioned answer.

try
{
    /* something */
}
catch( AError $e )
{
   handler1( $e );
}
catch ( BError $b )
{
   handler2( $e );
}

How to set standard encoding in Visual Studio

What

It is possible with EditorConfig.

EditorConfig helps developers define and maintain consistent coding styles between different editors and IDEs.

This also includes file encoding.

EditorConfig is built-in Visual Studio 2017 by default, and I there were plugins available for versions as old as VS2012. Read more from EditorConfig Visual Studio Plugin page.

How

You can set up a EditorConfig configuration file high enough in your folder structure to span all your intended repos (up to your drive root should your files be really scattered everywhere) and configure the setting charset:

charset: set to latin1, utf-8, utf-8-bom, utf-16be or utf-16le to control the character set.

You can add filters and exceptions etc on every folder level or by file name/type should you wish for finer control.

Once configured then compatible IDEs should automatically do it's thing to make matching files comform to set rules. Note that Visual Studio does not automatically convert all your files but do its bit when you work with files in IDE (open and save).

What next

While you could have a Visual-studio-wide setup, I strongly suggest to still include an EditorConfig root to your solution version control, so that explicit settings are automatically synced to all team members as well. Your drive root editorconfig file can be the fallback should some project not have their own editorconfig files set up yet.

How to send email to multiple recipients using python smtplib?

I use python 3.6 and the following code works for me

email_send = '[email protected],[email protected]'
server.sendmail(email_user,email_send.split(','),text)    

Python AttributeError: 'module' object has no attribute 'Serial'

This error can also happen if you have circular dependencies. Check your imports and make sure you do not have any cycles.

Making sure at least one checkbox is checked

Prevent user from deselecting last checked checkbox.
jQuery (original answer).

$('input[type="checkbox"][name="chkBx"]').on('change',function(){
    var getArrVal = $('input[type="checkbox"][name="chkBx"]:checked').map(function(){
        return this.value;
    }).toArray();

    if(getArrVal.length){
        //execute the code
        $('#msg').html(getArrVal.toString());

    } else {
        $(this).prop("checked",true);
        $('#msg').html("At least one value must be checked!");
        return false;

    }
});

UPDATED ANSWER 2019-05-31
Plain JS

_x000D_
_x000D_
let i,_x000D_
    el = document.querySelectorAll('input[type="checkbox"][name="chkBx"]'),_x000D_
    msg = document.getElementById('msg'),_x000D_
    onChange = function(ev){_x000D_
        ev.preventDefault();_x000D_
        let _this = this,_x000D_
            arrVal = Array.prototype.slice.call(_x000D_
                document.querySelectorAll('input[type="checkbox"][name="chkBx"]:checked'))_x000D_
                    .map(function(cur){return cur.value});_x000D_
_x000D_
        if(arrVal.length){_x000D_
            msg.innerHTML = JSON.stringify(arrVal);_x000D_
        } else {_x000D_
            _this.checked=true;_x000D_
            msg.innerHTML = "At least one value must be checked!";_x000D_
        }_x000D_
    };_x000D_
_x000D_
for(i=el.length;i--;){el[i].addEventListener('change',onChange,false);}
_x000D_
<label><input type="checkbox" name="chkBx" value="value1" checked> Value1</label>_x000D_
<label><input type="checkbox" name="chkBx" value="value2"> Value2</label>_x000D_
<label><input type="checkbox" name="chkBx" value="value3"> Value3</label>_x000D_
<div id="msg"></div>
_x000D_
_x000D_
_x000D_

Make flex items take content width, not width of parent container

In addtion to align-self you can also consider auto margin which will do almost the same thing

_x000D_
_x000D_
.container {_x000D_
  background: red;_x000D_
  height: 200px;_x000D_
  flex-direction: column;_x000D_
  padding: 10px;_x000D_
  display: flex;_x000D_
}_x000D_
a {_x000D_
  margin-right:auto;_x000D_
  padding: 10px 40px;_x000D_
  background: pink;_x000D_
}
_x000D_
<div class="container">_x000D_
  <a href="#">Test</a>_x000D_
</div>
_x000D_
_x000D_
_x000D_

HTML form do some "action" when hit submit button

index.html

<!DOCTYPE html>
<html>
   <body>
       <form action="submit.php" method="POST">
         First name: <input type="text" name="firstname" /><br /><br />
         Last name: <input type="text" name="lastname" /><br />
         <input type="submit" value="Submit" />
      </form> 
   </body>
</html>

After that one more file which page you want to display after pressing the submit button

submit.php

<html>
  <body>

    Your First Name is -  <?php echo $_POST["firstname"]; ?><br>
    Your Last Name is -   <?php echo $_POST["lastname"]; ?>

  </body>
</html>

Pdf.js: rendering a pdf file using a base64 file source instead of url

According to the examples base64 encoding is directly supported, although I've not tested it myself. Take your base64 string (derived from a file or loaded with any other method, POST/GET, websockets etc), turn it to a binary with atob, and then parse this to getDocument on the PDFJS API likePDFJS.getDocument({data: base64PdfData}); Codetoffel answer does work just fine for me though.

What's the best strategy for unit-testing database-driven applications?

I've actually used your first approach with quite some success, but in a slightly different ways that I think would solve some of your problems:

  1. Keep the entire schema and scripts for creating it in source control so that anyone can create the current database schema after a check out. In addition, keep sample data in data files that get loaded by part of the build process. As you discover data that causes errors, add it to your sample data to check that errors don't re-emerge.

  2. Use a continuous integration server to build the database schema, load the sample data, and run tests. This is how we keep our test database in sync (rebuilding it at every test run). Though this requires that the CI server have access and ownership of its own dedicated database instance, I say that having our db schema built 3 times a day has dramatically helped find errors that probably would not have been found till just before delivery (if not later). I can't say that I rebuild the schema before every commit. Does anybody? With this approach you won't have to (well maybe we should, but its not a big deal if someone forgets).

  3. For my group, user input is done at the application level (not db) so this is tested via standard unit tests.

Loading Production Database Copy:
This was the approach that was used at my last job. It was a huge pain cause of a couple of issues:

  1. The copy would get out of date from the production version
  2. Changes would be made to the copy's schema and wouldn't get propagated to the production systems. At this point we'd have diverging schemas. Not fun.

Mocking Database Server:
We also do this at my current job. After every commit we execute unit tests against the application code that have mock db accessors injected. Then three times a day we execute the full db build described above. I definitely recommend both approaches.

Mysql password expired. Can't connect

First, I use:

 mysql -u root -p

Giving my current password for the 'root'. Next:

mysql> ALTER USER `root`@`localhost` IDENTIFIED BY 'new_password',
       `root`@`localhost` PASSWORD EXPIRE NEVER;

Change 'new_password' to a new password for the user 'root'.
It solved my problem.

How to scroll to the bottom of a RecyclerView? scrollToPosition doesn't work

If you want just starting from the end use:

layoutManager.stackFromEnd = true

(Kotlin solution)

How to validate GUID is a GUID

Use GUID constructor standard functionality

Public Function IsValid(pString As String) As Boolean

    Try
        Dim mGuid As New Guid(pString)
    Catch ex As Exception
        Return False
    End Try
    Return True

End Function

Uncaught TypeError: Cannot read property 'length' of undefined

console.log(typeof json_data !== 'undefined'
    ? json_data.length : 'There is no spoon.');

...or more simply...

console.log(json_data ? json_data.length : 'json_data is null or undefined');

Can you set a border opacity in CSS?

No, there is no way to only set the opacity of a border with css.

For example, if you did not know the color, there is no way to only change the opacity of the border by simply using rgba().

How to determine the version of Gradle?

You can also add the following line to your build script:

println "Running gradle version: $gradle.gradleVersion"

or (it won't be printed with -q switch)

logger.lifecycle "Running gradle version: $gradle.gradleVersion"

How to find out the MySQL root password

thanks to @thusharaK I could reset the root password without knowing the old password.

On ubuntu I did the following:

sudo service mysql stop
sudo mysqld_safe --skip-grant-tables --skip-syslog --skip-networking

Then run mysql in a new terminal:

mysql -u root

And run the following queries to change the password:

UPDATE mysql.user SET authentication_string=PASSWORD('password') WHERE User='root';
FLUSH PRIVILEGES;

In MySQL 5.7, the password field in mysql.user table field was removed, now the field name is 'authentication_string'.

Quit the mysql safe mode and start mysql service by:

mysqladmin shutdown
sudo service mysql start

Where does Hive store files in HDFS?

It's also very possible that typing show create table <table_name> in the hive cli will give you the exact location of your hive table.

HTML Image not displaying, while the src url works

My images were not getting displayed even after putting them in the correct folder, problem was they did not have the right permission, I changed the permission to read write execute. I used chmod 777 image.png. All worked then, images were getting displayed. :)

How to set the current working directory?

Perhaps this is what you are looking for:

import os
os.chdir(default_path)

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

on command line type journalctl -xe and the results will be

SELinux is preventing /usr/sbin/httpd from name_bind access on the tcp_socket port 83 or 80

This means that the SELinux is running on your machine and you need to disable it. then edit the configuration file by type the following

nano /etc/selinux/config

Then find the line SELINUX=enforce and change to SELINUX=disabled

Then type the following and run the command to start httpd

setenforce 0

Lastly start a server

systemctl start httpd

How can I get an int from stdio in C?

The typical way is with scanf:

int input_value;

scanf("%d", &input_value);

In most cases, however, you want to check whether your attempt at reading input succeeded. scanf returns the number of items it successfully converted, so you typically want to compare the return value against the number of items you expected to read. In this case you're expecting to read one item, so:

if (scanf("%d", &input_value) == 1)
    // it succeeded
else
    // it failed

Of course, the same is true of all the scanf family (sscanf, fscanf and so on).

Understanding [TCP ACKed unseen segment] [TCP Previous segment not captured]

Another cause of "TCP ACKed Unseen" is the number of packets that may get dropped in a capture. If I run an unfiltered capture for all traffic on a busy interface, I will sometimes see a large number of 'dropped' packets after stopping tshark.

On the last capture I did when I saw this, I had 2893204 packets captured, but once I hit Ctrl-C, I got a 87581 packets dropped message. Thats a 3% loss, so when wireshark opens the capture, its likely to be missing packets and report "unseen" packets.

As I mentioned, I captured a really busy interface with no capture filter, so tshark had to sort all packets, when I use a capture filter to remove some of the noise, I no longer get the error.

Is nested function a good approach when required by only one function?

You can use it to avoid defining global variables. This gives you an alternative for other designs. 3 designs presenting a solution to a problem.

A) Using functions without globals

def calculate_salary(employee, list_with_all_employees):
    x = _calculate_tax(list_with_all_employees)

    # some other calculations done to x
    pass

    y = # something 

    return y

def _calculate_tax(list_with_all_employees):
    return 1.23456 # return something

B) Using functions with globals

_list_with_all_employees = None

def calculate_salary(employee, list_with_all_employees):

    global _list_with_all_employees
    _list_with_all_employees = list_with_all_employees

    x = _calculate_tax()

    # some other calculations done to x
    pass

    y = # something

    return y

def _calculate_tax():
    return 1.23456 # return something based on the _list_with_all_employees var

C) Using functions inside another function

def calculate_salary(employee, list_with_all_employees):

    def _calculate_tax():
        return 1.23456 # return something based on the list_with_a--Lemployees var

    x = _calculate_tax()

    # some other calculations done to x
    pass
    y = # something 

    return y

Solution C) allows to use variables in the scope of the outer function without having the need to declare them in the inner function. Might be useful in some situations.

Show empty string when date field is 1/1/1900

An alternate solution that covers both min (1/1/1900) and max (6/6/2079) dates:

ISNULL(NULLIF(NULLIF(CONVERT(VARCHAR(10), CreatedDate, 120), '1900-01-01'), '2079-06-06'), '').

Whatever solution you use, you should do a conversion of your date (or datetime) field to a specific format to bulletproof against different default server configurations.

See CAST and CONVERT on MSDN: https://msdn.microsoft.com/en-us/library/ms187928.aspx

Definitive way to trigger keypress events with jQuery

In case you need to take into account the current cursor and text selection...

This wasn't working for me for an AngularJS app on Chrome. As Nadia points out in the original comments, the character is never visible in the input field (at least, that was my experience). In addition, the previous solutions don't take into account the current text selection in the input field. I had to use a wonderful library jquery-selection.

I have a custom on-screen numeric keypad that fills in multiple input fields. I had to...

  1. On focus, save the lastFocus.element
  2. On blur, save the current text selection (start and stop)

    var pos = element.selection('getPos')
    lastFocus.pos = { start: pos.start, end: pos.end}
    
  3. When a button on the my keypad is pressed:

    lastFocus.element.selection( 'setPos', lastFocus.pos)
    lastFocus.element.selection( 'replace', {text: myKeyPadChar, caret: 'end'})
    

How to render pdfs using C#

The easiest lib I have used is Paolo Gios's library. It's basically

Create GiosPDFDocument object
Create TextArea object
Add text, images, etc to TextArea object
Add TextArea object to PDFDocument object
Write to stream

This is a great tutorial to get you started.

Calling a class function inside of __init__

Call the function in this way:

self.parse_file()

You also need to define your parse_file() function like this:

def parse_file(self):

The parse_file method has to be bound to an object upon calling it (because it's not a static method). This is done by calling the function on an instance of the object, in your case the instance is self.

Are there best practices for (Java) package organization?

I organize packages by feature, not by patterns or implementation roles. I think packages like:

  • beans
  • factories
  • collections

are wrong.

I prefer, for example:

  • orders
  • store
  • reports

so I can hide implementation details through package visibility. Factory of orders should be in the orders package so details about how to create an order are hidden.

Compiling LaTex bib source

I am using texmaker as the editor. you have to compile it in terminal as following:

  1. pdflatex filename (with or without extensions)
  2. bibtex filename (without extensions)
  3. pdflatex filename (with or without extensions)
  4. pdflatex filename (with or without extensions)

but sometimes, when you use \citep{}, the names of the references don't show up. In this case, I had to open the references.bib file , so that texmaker could capture the references from the references.bib file. After every edition of the bib file, I had to close and reopen it!! So that texmaker could capture the content of new .bbl file each time. But remember, you have to also run your code in texmaker too.

Print: Entry, ":CFBundleIdentifier", Does Not Exist

I also get same error while running project react-native run-ios

But when i run project from xcode, that is work for me.

How to focus on a form input text field on page load using jQuery?

You can use HTML5 autofocus for this. You don't need jQuery or other JavaScript.

<input type="text" name="some_field" autofocus>

Note this will not work on IE9 and lower.

How to solve Permission denied (publickey) error when using Git?

The basic GIT instructions did not make a reference to the SSH key stuff. Following some of the links above, I found a git help page that explains, step-by-step, exactly how to do this for various operating systems (the link will detect your OS and redirect, accordingly):

http://help.github.com/set-up-git-redirect/

It walks through everything needed for GITHub and also gives detailed explanations such as "why add a passphrase when creating an RSA key." I figured I'd post it, in case it helps someone else...

changing iframe source with jquery

Should work.

Here's a working example:

http://jsfiddle.net/rhpNc/

Excerpt:

function loadIframe(iframeName, url) {
    var $iframe = $('#' + iframeName);
    if ($iframe.length) {
        $iframe.attr('src',url);
        return false;
    }
    return true;
}

How can I write an anonymous function in Java?

Here's an example of an anonymous inner class.

System.out.println(new Object() {
    @Override public String toString() {
        return "Hello world!";
    }
}); // prints "Hello world!"

This is not very useful as it is, but it shows how to create an instance of an anonymous inner class that extends Object and @Override its toString() method.

See also


Anonymous inner classes are very handy when you need to implement an interface which may not be highly reusable (and therefore not worth refactoring to its own named class). An instructive example is using a custom java.util.Comparator<T> for sorting.

Here's an example of how you can sort a String[] based on String.length().

import java.util.*;
//...

String[] arr = { "xxx", "cd", "ab", "z" };
Arrays.sort(arr, new Comparator<String>() {
    @Override public int compare(String s1, String s2) {
        return s1.length() - s2.length();
    }           
});
System.out.println(Arrays.toString(arr));
// prints "[z, cd, ab, xxx]"

Note the comparison-by-subtraction trick used here. It should be said that this technique is broken in general: it's only applicable when you can guarantee that it will not overflow (such is the case with String lengths).

See also

Combine two tables for one output

In your expected output, you've got the second last row sum incorrect, it should be 40 according to the data in your tables, but here is the query:

Select  ChargeNum, CategoryId, Sum(Hours)
From    (
    Select  ChargeNum, CategoryId, Hours
    From    KnownHours
    Union
    Select  ChargeNum, 'Unknown' As CategoryId, Hours
    From    UnknownHours
) As a
Group By ChargeNum, CategoryId
Order By ChargeNum, CategoryId

And here is the output:

ChargeNum  CategoryId 
---------- ---------- ----------------------
111111     1          40
111111     2          50
111111     Unknown    70
222222     1          40
222222     Unknown    25.5

Add a CSS class to <%= f.submit %>

<%= f.submit 'name of button here', :class => 'submit_class_name_here' %>

This should do. If you're getting an error, chances are that you're not supplying the name.

Alternatively, you can style the button without a class:

form#form_id_here input[type=submit]

Try that, as well.

Automatically get loop index in foreach loop in Perl

Oh yes, you can! (sort of, but you shouldn't). each(@array) in a scalar context gives you the current index of the array.

@a = (a..z);
for (@a) { 
  print each(@a) . "\t" . $_ . "\n"; 
}

Here each(@a) is in a scalar context and returns only the index, not the value at that index. Since we're in a for loop, we have the value in $_ already. The same mechanism is often used in a while-each loop. Same problem.

The problem comes if you do for(@a) again. The index isn't back to 0 like you'd expect; it's undef followed by 0,1,2... one count off. The perldoc of each() says to avoid this issue. Use a for loop to track the index.

each

Basically:

for(my $i=0; $i<=$#a; $i++) {
  print "The Element at $i is $a[$i]\n";
}

I'm a fan of the alternate method:

my $index=0;
for (@a) {
  print "The Element at $index is $a[$index]\n";
  $index++;
}

How to secure phpMyAdmin

The simplest approach would be to edit the webserver, most likely an Apache2 installation, configuration and give phpmyadmin a different name.

A second approach would be to limit the IP addresses from where phpmyadmin may be accessed (e.g. only local lan or localhost).

How do I get a div to float to the bottom of its container?

I know it is a very old thread but still I would like to answer. If anyone follow the below css & html then it works. The child footer div will stick with bottom like glue.

<style>
        #MainDiv
        {
            height: 300px;
            width: 300px;
            background-color: Red;
            position: relative;
        }

        #footerDiv
        {
            height: 50px;
            width: 300px;
            background-color: green;
            float: right;
            position: absolute;
            bottom: 0px;
        }
    </style>


<div id="MainDiv">
     <div id="footerDiv">
     </div>
</div>

Export data from Chrome developer tool

You can use fiddler web debugger to import the HAR and then it is very easy from their on... Ctrl+A (select all) then Ctrl+c (copy summary) then paste in excel and have fun

When to use HashMap over LinkedList or ArrayList and vice-versa

I will put here some real case examples and scenarios when to use one or another, it might be of help for somebody else:

HashMap

When you have to use cache in your application. Redis and membase are some type of extended HashMap. (Doesn't matter the order of the elements, you need quick ( O(1) ) read access (a value), using a key).

LinkedList

When the order is important (they are ordered as they were added to the LinkedList), the number of elements are unknown (don't waste memory allocation) and you require quick insertion time ( O(1) ). A list of to-do items that can be listed sequentially as they are added is a good example.

Cannot find module '@angular/compiler'

I just run npm install and then ok.

Is it better in C++ to pass by value or pass by constant reference?

As a rule passing by const reference is better. But if you need to modify you function argument locally you should better use passing by value. For some basic types the performance in general the same both for passing by value and by reference. Actually reference internally represented by pointer, that is why you can expect for instance that for pointer both passing are the same in terms of performance, or even passing by value can be faster because of needless dereference.

Convert JSONArray to String Array

String[] arr = jsonArray.toString().replace("},{", " ,").split(" ");

How to deploy a React App on Apache web server

Before making the npm build,
1) Go to your React project root folder and open package.json.
2) Add "homepage" attribute to package.json

  • if you want to provide absolute path

    "homepage": "http://hostName.com/appLocation",
    "name": "react-app",
    "version": "1.1.0",
    
  • if you want to provide relative path

    "homepage": "./",
    "name": "react-app",
    

    Using relative path method may warn a syntax validation error in your IDE. But the build is made without any errors during compilation.

3) Save the package.json , and in terminal run npm run-script build
4) Copy the contents of build/ folder to your server directory.

PS: It is easy to use relative path method if you want to change the build file location in your server frequently.

How to clone ArrayList and also clone its contents?

I think the current green answer is bad , why you might ask?

  • It can require to add a lot of code
  • It requires you to list all Lists to be copied and do this

The way serialization is also bad imo, you might have to add Serializable all over the place.

So what is the solution:

Java Deep-Cloning library The cloning library is a small, open source (apache licence) java library which deep-clones objects. The objects don't have to implement the Cloneable interface. Effectivelly, this library can clone ANY java objects. It can be used i.e. in cache implementations if you don't want the cached object to be modified or whenever you want to create a deep copy of objects.

Cloner cloner=new Cloner();
XX clone = cloner.deepClone(someObjectOfTypeXX);

Check it out at https://github.com/kostaskougios/cloning

An unhandled exception was generated during the execution of the current web request

In my case, I created a new project and when I ran it the first time, it gave me the following error:

An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.

So my solution was to go to the Package Manager Console inside the Visual Studio and run:Update-Package

Problem solved!!

Set min-width either by content or 200px (whichever is greater) together with max-width

The problem is that flex: 1 sets flex-basis: 0. Instead, you need

.container .box {
  min-width: 200px;
  max-width: 400px;
  flex-basis: auto; /* default value */
  flex-grow: 1;
}

_x000D_
_x000D_
.container {_x000D_
  display: -webkit-flex;_x000D_
  display: flex;_x000D_
  -webkit-flex-wrap: wrap;_x000D_
  flex-wrap: wrap;_x000D_
}_x000D_
_x000D_
.container .box {_x000D_
  -webkit-flex-grow: 1;_x000D_
  flex-grow: 1;_x000D_
  min-width: 100px;_x000D_
  max-width: 400px;_x000D_
  height: 200px;_x000D_
  background-color: #fafa00;_x000D_
  overflow: hidden;_x000D_
}
_x000D_
<div class="container">_x000D_
  <div class="box">_x000D_
    <table>_x000D_
      <tr>_x000D_
        <td>Content</td>_x000D_
        <td>Content</td>_x000D_
        <td>Content</td>_x000D_
      </tr>_x000D_
    </table>    _x000D_
  </div>_x000D_
  <div class="box">_x000D_
    <table>_x000D_
      <tr>_x000D_
        <td>Content</td>_x000D_
      </tr>_x000D_
    </table>    _x000D_
  </div>_x000D_
  <div class="box">_x000D_
    <table>_x000D_
      <tr>_x000D_
        <td>Content</td>_x000D_
        <td>Content</td>_x000D_
      </tr>_x000D_
    </table>    _x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

In Java, how can I determine if a char array contains a particular character?

This method does the trick.

boolean contains(char c, char[] array) {
    for (char x : array) {
        if (x == c) {
            return true;
        }
    }
    return false;
}

Example of usage:

class Main {

    static boolean contains(char c, char[] array) {
        for (char x : array) {
            if (x == c) {
                return true;
            }
        }
        return false;
    }

    public static void main(String[] a) {
        char[] charArray = new char[] {'h','e','l','l','o'};
        if (!contains('q', charArray)) {
            // Do something...
            System.out.println("Hello world!");
        }
    }

}

Alternative way:

if (!String.valueOf(charArray).contains("q")) {
    // do something...
}

No 'Access-Control-Allow-Origin' header is present on the requested resource error

cors unblock works great for chrome 78 [COrs unb] [1] https://chrome.google.com/webstore/detail/cors-unblock/lfhmikememgdcahcdlaciloancbhjino

it's a plugin for google chrome called "cors unblock"

Summary: No more CORS error by appending 'Access-Control-Allow-Origin: *' header to local and remote web requests when enabled

This extension provides control over XMLHttpRequest and fetch methods by providing custom "access-control-allow-origin" and "access-control-allow-methods" headers to every requests that the browser receives. A user can toggle the extension on and off from the toolbar button. To modify how these headers are altered, use the right-click context menu items. You can customize what method are allowed. The default option is to allow 'GET', 'PUT', 'POST', 'DELETE', 'HEAD', 'OPTIONS', 'PATCH' methods. You can also ask the extension not to overwrite these headers when the server already fills them.

Equivalent of SQL ISNULL in LINQ?

Since aa is the set/object that might be null, can you check aa == null ?

(aa / xx might be interchangeable (a typo in the question); the original question talks about xx but only defines aa)

i.e.

select new {
    AssetID = x.AssetID,
    Status = aa == null ? (bool?)null : aa.Online; // a Nullable<bool>
}

or if you want the default to be false (not null):

select new {
    AssetID = x.AssetID,
    Status = aa == null ? false : aa.Online;
}

Update; in response to the downvote, I've investigated more... the fact is, this is the right approach! Here's an example on Northwind:

        using(var ctx = new DataClasses1DataContext())
        {
            ctx.Log = Console.Out;
            var qry = from boss in ctx.Employees
                      join grunt in ctx.Employees
                          on boss.EmployeeID equals grunt.ReportsTo into tree
                      from tmp in tree.DefaultIfEmpty()
                      select new
                             {
                                 ID = boss.EmployeeID,
                                 Name = tmp == null ? "" : tmp.FirstName
                        };
            foreach(var row in qry)
            {
                Console.WriteLine("{0}: {1}", row.ID, row.Name);
            }
        }

And here's the TSQL - pretty much what we want (it isn't ISNULL, but it is close enough):

SELECT [t0].[EmployeeID] AS [ID],
    (CASE
        WHEN [t2].[test] IS NULL THEN CONVERT(NVarChar(10),@p0)
        ELSE [t2].[FirstName]
     END) AS [Name]
FROM [dbo].[Employees] AS [t0]
LEFT OUTER JOIN (
    SELECT 1 AS [test], [t1].[FirstName], [t1].[ReportsTo]
    FROM [dbo].[Employees] AS [t1]
    ) AS [t2] ON ([t0].[EmployeeID]) = [t2].[ReportsTo]
-- @p0: Input NVarChar (Size = 0; Prec = 0; Scale = 0) []
-- Context: SqlProvider(Sql2008) Model: AttributedMetaModel Build: 3.5.30729.1

QED?

How do I avoid the specification of the username and password at every git push?

1. Generate an SSH key

Linux/Mac

Open terminal to create ssh keys:

cd ~                 #Your home directory
ssh-keygen -t rsa    #Press enter for all values

For Windows

(Only works if the commit program is capable of using certificates/private & public ssh keys)

  1. Use Putty Gen to generate a key
  2. Export the key as an open SSH key

Here is a walkthrough on putty gen for the above steps

2. Associate the SSH key with the remote repository

This step varies, depending on how your remote is set up.

  • If it is a GitHub repository and you have administrative privileges, go to settings and click 'add SSH key'. Copy the contents of your ~/.ssh/id_rsa.pub into the field labeled 'Key'.

  • If your repository is administered by somebody else, give the administrator your id_rsa.pub.

  • If your remote repository is administered by your, you can use this command for example:

    scp ~/.ssh/id_rsa.pub YOUR_USER@YOUR_IP:~/.ssh/authorized_keys/id_rsa.pub

3. Set your remote URL to a form that supports SSH 1

If you have done the steps above and are still getting the password prompt, make sure your repo URL is in the form

git+ssh://[email protected]/username/reponame.git

as opposed to

https://github.com/username/reponame.git

To see your repo URL, run:

git remote show origin

You can change the URL with:

git remote set-url origin git+ssh://[email protected]/username/reponame.git

[1] This section incorporates the answer from Eric P

Converting JSON data to Java object

Easy and working java code to convert JSONObject to Java Object

Employee.java

import java.util.HashMap;
import java.util.Map;

import javax.annotation.Generated;

import com.fasterxml.jackson.annotation.JsonAnyGetter;
import com.fasterxml.jackson.annotation.JsonAnySetter;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;

@JsonInclude(JsonInclude.Include.NON_NULL)
@Generated("org.jsonschema2pojo")
@JsonPropertyOrder({
"id",
"firstName",
"lastName"
})
public class Employee {

@JsonProperty("id")
private Integer id;
@JsonProperty("firstName")
private String firstName;
@JsonProperty("lastName")
private String lastName;
@JsonIgnore
private Map<String, Object> additionalProperties = new HashMap<String, Object>();

/**
*
* @return
* The id
*/
@JsonProperty("id")
public Integer getId() {
return id;
}

/**
*
* @param id
* The id
*/
@JsonProperty("id")
public void setId(Integer id) {
this.id = id;
}

/**
*
* @return
* The firstName
*/
@JsonProperty("firstName")
public String getFirstName() {
return firstName;
}

/**
*
* @param firstName
* The firstName
*/
@JsonProperty("firstName")
public void setFirstName(String firstName) {
this.firstName = firstName;
}

/**
*
* @return
* The lastName
*/
@JsonProperty("lastName")
public String getLastName() {
return lastName;
}

/**
*
* @param lastName
* The lastName
*/
@JsonProperty("lastName")
public void setLastName(String lastName) {
this.lastName = lastName;
}

@JsonAnyGetter
public Map<String, Object> getAdditionalProperties() {
return this.additionalProperties;
}

@JsonAnySetter
public void setAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
}

}

LoadFromJSON.java

import org.codehaus.jettison.json.JSONObject;

import com.fasterxml.jackson.databind.ObjectMapper;

public class LoadFromJSON {

    public static void main(String args[]) throws Exception {
        JSONObject json = new JSONObject();
        json.put("id", 2);
        json.put("firstName", "hello");
        json.put("lastName", "world");

        byte[] jsonData = json.toString().getBytes();

        ObjectMapper mapper = new ObjectMapper();
        Employee employee = mapper.readValue(jsonData, Employee.class);

        System.out.print(employee.getLastName());

    }
}

Node.js - use of module.exports as a constructor

This question doesn't really have anything to do with how require() works. Basically, whatever you set module.exports to in your module will be returned from the require() call for it.

This would be equivalent to:

var square = function(width) {
  return {
    area: function() {
      return width * width;
    }
  };
}

There is no need for the new keyword when calling square. You aren't returning the function instance itself from square, you are returning a new object at the end. Therefore, you can simply call this function directly.

For more intricate arguments around new, check this out: Is JavaScript's "new" keyword considered harmful?

Can I return the 'id' field after a LINQ insert?

After you commit your object into the db the object receives a value in its ID field.

So:

myObject.Field1 = "value";

// Db is the datacontext
db.MyObjects.InsertOnSubmit(myObject);
db.SubmitChanges();

// You can retrieve the id from the object
int id = myObject.ID;

Adding an external directory to Tomcat classpath

What I suggest you do is add a META-INF directory with a MANIFEST.MF file in .war file.

Please note that according to servlet spec, it must be a .war file and not .war directory for the META-INF/MANIFEST.MF to be read by container.

Edit the MANIFEST.MF Class-Path property to C:\app_config\java_app:

See Using JAR Files: The Basics (Understanding the Manifest)

Enjoy.

How can I get the last 7 characters of a PHP string?

last 7 characters of a string:

$rest = substr( "abcdefghijklmnop", -7); // returns "jklmnop"

Swift Error: Editor placeholder in source file

you had this

destination = Node(key: String?, neighbors: [Edge!], visited: Bool, lat: Double, long: Double)

which was place holder text above you need to insert some values

class Edge{

}

public class Node{

  var key: String?
  var neighbors: [Edge]
  var visited: Bool = false
  var lat: Double
  var long: Double

  init(key: String?, neighbors: [Edge], visited: Bool, lat: Double, long: Double) {
    self.neighbors = [Edge]()
    self.key = key
    self.visited = visited
    self.lat = lat
    self.long = long
  }

}

class Path {

  var total: Int!
  var destination: Node
  var previous: Path!

  init(){
    destination = Node(key: "", neighbors: [], visited: true, lat: 12.2, long: 22.2)
  }
}

Python: Find index of minimum item in list of floats

Use of the argmin method for numpy arrays.

import numpy as np
np.argmin(myList)

However, it is not the fastest method: it is 3 times slower than OP's answer on my computer. It may be the most concise one though.

How to insert a new key value pair in array in php?

Try this:

foreach($array as $k => $obj) { 
    $obj->{'newKey'} = "value"; 
}

Execute a large SQL script (with GO commands)

I hit this same issue and eventually just solved it by a simple string replace, replacing the word GO with a semi-colon (;)

All seems to be working fine while executing scripts with in-line comments, block comments, and GO commands

public static bool ExecuteExternalScript(string filePath)
{
    using (StreamReader file = new StreamReader(filePath))
    using (SqlConnection conn = new SqlConnection(dbConnStr))
    {
        StringBuilder sql = new StringBuilder();

        string line;
        while ((line = file.ReadLine()) != null)
        {
            // replace GO with semi-colon
            if (line == "GO")
                sql.Append(";");
            // remove inline comments
            else if (line.IndexOf("--") > -1)
                sql.AppendFormat(" {0} ", line.Split(new string[] { "--" }, StringSplitOptions.None)[0]);
            // just the line as it is
            else
                sql.AppendFormat(" {0} ", line);
        }
        conn.Open();

        SqlCommand cmd = new SqlCommand(sql.ToString(), conn);
        cmd.ExecuteNonQuery();
    }

    return true;
}

html5 <input type="file" accept="image/*" capture="camera"> display as image rather than "choose file" button

I know this is an old question but I came across it while trying to solve this same issue. I thought it'd be worth sharing this solution I hadn't found anywhere else.

Basically the solution is to use CSS to hide the <input> element and style a <label> around it to look like a button. Click the 'Run code snippet' button to see the results.

I had used a JavaScript solution before that worked fine too but it is nice to solve a 'presentation' issue with just CSS.

_x000D_
_x000D_
label.cameraButton {_x000D_
  display: inline-block;_x000D_
  margin: 1em 0;_x000D_
_x000D_
  /* Styles to make it look like a button */_x000D_
  padding: 0.5em;_x000D_
  border: 2px solid #666;_x000D_
  border-color: #EEE #CCC #CCC #EEE;_x000D_
  background-color: #DDD;_x000D_
}_x000D_
_x000D_
/* Look like a clicked/depressed button */_x000D_
label.cameraButton:active {_x000D_
  border-color: #CCC #EEE #EEE #CCC;_x000D_
}_x000D_
_x000D_
/* This is the part that actually hides the 'Choose file' text box for camera inputs */_x000D_
label.cameraButton input[accept*="camera"] {_x000D_
  display: none;_x000D_
}
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
_x000D_
<head>_x000D_
  <title>Nice image capture button</title>_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
  <label class="cameraButton">Take a picture_x000D_
    <input type="file" accept="image/*;capture=camera">_x000D_
  </label>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_