Programs & Examples On #Cache money

Unable to send email using Gmail SMTP server through PHPMailer, getting error: SMTP AUTH is required for message submission on port 587. How to fix?

$mail = new PHPMailer(); // create a new object
$mail->IsSMTP(); // enable SMTP
$mail->SMTPDebug = 1; // debugging: 1 = errors and messages, 2 = messages only
$mail->SMTPAuth = true; // authentication enabled
$mail->SMTPSecure = 'ssl'; // secure transfer enabled REQUIRED for Gmail
$mail->Host = "smtp.gmail.com";
$mail->Port = 465; // or 587
$mail->IsHTML(true);
$mail->Username = "[email protected]";
$mail->Password = "password";
$mail->SetFrom("[email protected]");
$mail->Subject = "Test";
$mail->Body = "hello";
$mail->AddAddress("[email protected]");

 if(!$mail->Send()) {
    echo "Mailer Error: " . $mail->ErrorInfo;
 } else {
    echo "Message has been sent";
 }

This code above has been tested and worked for me.

It could be that you needed $mail->SMTPSecure = 'ssl';

Also make sure you don't have two step verification switched on for that account as that can cause problems also.

UPDATED

You could try changing $mail->SMTP to:

$mail->SMTPSecure = 'tls';

It's worth noting that some SMTP servers block connections. Some SMTP servers don't support SSL (or TLS) connections.

SSH to Elastic Beanstalk instance

There is a handy 'Connect' option in the 'Instance Actions' menu for the EC2 instance. It will give you the exact SSH command to execute with the correct url for the instance. Jabley's overall instructions are correct.

How can I create a dynamic button click event on a dynamic button?

You can create button in a simple way, such as:

Button button = new Button();
button.Click += new EventHandler(button_Click);

protected void button_Click (object sender, EventArgs e)
{
    Button button = sender as Button;
    // identify which button was clicked and perform necessary actions
}

But event probably will not fire, because the element/elements must be recreated at every postback or you will lose the event handler.

I tried this solution that verify that ViewState is already Generated and recreate elements at every postback,

for example, imagine you create your button on an event click:

    protected void Button_Click(object sender, EventArgs e)
    {
       if (Convert.ToString(ViewState["Generated"]) != "true")
        {
            CreateDynamicElements();
        }
    
    }

on postback, for example on page load, you should do this:

    protected void Page_Load(object sender, EventArgs e)
    {
        if (Convert.ToString(ViewState["Generated"]) == "true") {
            CreateDynamicElements();
        }
    }

In CreateDynamicElements() you can put all the elements you need, such as your button.

This worked very well for me.

public void CreateDynamicElements(){

    Button button = new Button();
    button.Click += new EventHandler(button_Click);

}

How to select rows for a specific date, ignoring time in SQL Server

select * from sales where salesDate between '11/11/2010' and '12/11/2010' --if using dd/mm/yyyy

The more correct way to do it:

DECLARE @myDate datetime
SET @myDate = '11/11/2010'
select * from sales where salesDate>=@myDate and salesDate<dateadd(dd,1,@myDate)

If only the date is specified, it means total midnight. If you want to make sure intervals don't overlap, switch the between with a pair of >= and <

you can do it within one single statement, but it's just that the value is used twice.

Navigate to another page with a button in angular 2

You can use routerLink in the following manner,

<input type="button" value="Add Bulk Enquiry" [routerLink]="['../addBulkEnquiry']" class="btn">

or use <button [routerLink]="['./url']"> in your case, for more info you could read the entire stacktrace on github https://github.com/angular/angular/issues/9471

the other methods are also correct but they create a dependency on the component file.

Hope your concern is resolved.

How to set Default Controller in asp.net MVC 4 & MVC 5

In case you have only one controller and you want to access every action on root you can skip controller name like this

routes.MapRoute(
        "Default", 
        "{action}/{id}", 
        new { controller = "Home", action = "Index", 
        id = UrlParameter.Optional }
);

SQL Server 2008 Connection Error "No process is on the other end of the pipe"

perhaps this comes too late, but still it could be nice to "document it" for others out there.

I received the same error after experimenting and testing with Remote Desktop Services on a MS Server 2012 with MS SQL Server 2012.

During the Remote Desktop Services install one is asked to create a (local) certificate, and so I did. After finishing the test/experiments I removed the Remote Desktop Services. That's when this error appeared (I cannot say whether the error occured during the test with RDS, I don't remember if I used/tried the SQL Connection during the RDS test).

I am not sure how to solve this since the default certificate does not work for me, but the "RDS" certificate does.

BTW, the certificates are found in App: "SQL Server Configuration Manager" -> "SQL Server Network Configuration" -> Right click: "Protocols for " -> Select "Properties" -> Tab "Certificate"

My default SQL Certificate is named: ConfigMgr SQL Server Identification Certificate, has expiration date: 2114-06-09.

Hope this can give a hint to others.

/Kim

Git: How to squash all commits on branch

Another way to squash all your commits is to reset the index to master:

 git checkout yourBranch
 git reset $(git merge-base master yourBranch)
 git add -A
 git commit -m "one commit on yourBranch"

This isn't perfect as it implies you know from which branch "yourBranch" is coming from.
Note: finding that origin branch isn't easy/possible with Git (the visual way is often the easiest, as seen here).


EDIT: you will need to use git push --force


Karlotcha Hoa adds in the comments:

For the reset, you can do

git reset $(git merge-base master $(git rev-parse --abbrev-ref HEAD)) 

[That] automatically uses the branch you are currently on.
And if you use that, you can also use an alias, as the command doesn't rely on the branch name.

JAVA_HOME should point to a JDK not a JRE

In IntelliJ IDEA go to File>Project Structure>SDK>JDK home path. Copy it and then go to My Computer>Advanced Settings>Environment Variables Change the JAVA_HOME path to what you have copied. Then open new cmd, and try mvn -v

It worked for me !!!

How to determine if a string is a number with C++?

C/C++ style for unsigned integers, using range based for C++11:

int isdigits(const std::string & s)
{
    for (char c : s) if (!isdigit(c)) return (0);
    return (1);
}

Seaborn plots not showing up

To avoid confusion (as there seems to be some in the comments). Assuming you are on Jupyter:

%matplotlib inline > displays the plots INSIDE the notebook

sns.plt.show() > displays the plots OUTSIDE of the notebook

%matplotlib inline will OVERRIDE sns.plt.show() in the sense that plots will be shown IN the notebook even when sns.plt.show() is called.

And yes, it is easy to include the line in to your config:

Automatically run %matplotlib inline in IPython Notebook

But it seems a better convention to keep it together with imports in the actual code.

ImportError: No module named sqlalchemy

Probably a stupid mistake; but, I experienced this problem and the issue turned out to be that "pip3 install sqlalchemy" installs libraries in user specific directories.

On my Linux machine, I was logged in as user1 executing a python script in user2's directory. I installed sqlalchemy as user1 and it by default placed the files in user1's directory. After installing sqlalchemy in user2's directory the problem went away.

Executing periodic actions in Python

You can execute your task in a different thread. threading.Timer will let you execute a given callback once after some time has elapsed, if you want to execute your task, for example, as long as the callback returns True (this is actually what glib.timeout_add provides, but you might not have it installed in windows) or until you cancel it, you can use this code:

import logging, threading, functools
import time

logging.basicConfig(level=logging.NOTSET,
                    format='%(threadName)s %(message)s')

class PeriodicTimer(object):
    def __init__(self, interval, callback):
        self.interval = interval

        @functools.wraps(callback)
        def wrapper(*args, **kwargs):
            result = callback(*args, **kwargs)
            if result:
                self.thread = threading.Timer(self.interval,
                                              self.callback)
                self.thread.start()

        self.callback = wrapper

    def start(self):
        self.thread = threading.Timer(self.interval, self.callback)
        self.thread.start()

    def cancel(self):
        self.thread.cancel()


def foo():
    logging.info('Doing some work...')
    return True

timer = PeriodicTimer(1, foo)
timer.start()

for i in range(2):
    time.sleep(2)
    logging.info('Doing some other work...')

timer.cancel()

Example output:

Thread-1 Doing some work...
Thread-2 Doing some work...
MainThread Doing some other work...
Thread-3 Doing some work...
Thread-4 Doing some work...
MainThread Doing some other work...

Note: The callback isn't executed every interval execution. Interval is the time the thread waits between the callback finished the last time and the next time is called.

How can change width of dropdown list?

Try this code:

<select name="wgtmsr" id="wgtmsr">
<option value="kg">Kg</option>
<option value="gm">Gm</option>
<option value="pound">Pound</option>
<option value="MetricTon">Metric ton</option>
<option value="litre">Litre</option>
<option value="ounce">Ounce</option>
</select>

CSS:

#wgtmsr{
 width:150px;   
}

If you want to change the width of the option you can do this in your css:

#wgtmsr option{
  width:150px;   
}

Maybe you have a conflict in your css rules that override the width of your select

DEMO

How can I get a list of users from active directory?

If you want to filter y active accounts add this to Harvey's code:

 UserPrincipal userPrin = new UserPrincipal(context);
 userPrin.Enabled = true;

after the first using. Then add

  searcher.QueryFilter = userPrin;

before the find all. And that should get you the active ones.

git: diff between file in local repo and origin

If [remote-path] and [local-path] are the same, you can do

$ git fetch origin master
$ git diff origin/master -- [local-path]

Note 1: The second command above will compare against the locally stored remote tracking branch. The fetch command is required to update the remote tracking branch to be in sync with the contents of the remote server. Alternatively, you can just do

$ git diff master:<path-or-file-name>

Note 2: master can be replaced in the above examples with any branch name

Passing environment-dependent variables in webpack

You can pass any command-line argument without additional plugins using --env since webpack 2:

webpack --config webpack.config.js --env.foo=bar

Using the variable in webpack.config.js:

module.exports = function(env) {
    if (env.foo === 'bar') {
        // do something
    }
}

Source

Passing variables to the next middleware using next() in Express.js

That's because req and res are two different objects.

You need to look for the property on the same object you added it to.

How to uninstall mini conda? python

In order to uninstall miniconda, simply remove the miniconda folder,

rm -r ~/miniconda/

As for avoiding conflicts between different Python environments, you can use virtual environments. In particular, with Miniconda, the following workflow could be used,

$ wget https://repo.continuum.io/miniconda/Miniconda3-3.7.0-Linux-x86_64.sh -O ~/miniconda.sh
$ bash miniconda
$ conda env remove --yes -n new_env    # remove the environement new_env if it exists (optional)
$ conda create --yes -n new_env pip numpy pandas scipy matplotlib scikit-learn nltk ipython-notebook seaborn python=2
$ activate new_env
$ # pip install modules if needed, run python scripts, etc
  # everything will be installed in the new_env
  # located in ~/miniconda/envs/new_env
$ deactivate

How do I implement a progress bar in C#?

Some people may not like it, but this is what I do:

private void StartBackgroundWork() {
    if (Application.RenderWithVisualStyles)
        progressBar.Style = ProgressBarStyle.Marquee;
    else {
        progressBar.Style = ProgressBarStyle.Continuous;
        progressBar.Maximum = 100;
        progressBar.Value = 0;
        timer.Enabled = true;
    }
    backgroundWorker.RunWorkerAsync();
}

private void timer_Tick(object sender, EventArgs e) {
    if (progressBar.Value < progressBar.Maximum)
        progressBar.Increment(5);
    else
        progressBar.Value = progressBar.Minimum;
}

The Marquee style requires VisualStyles to be enabled, but it continuously scrolls on its own without needing to be updated. I use that for database operations that don't report their progress.

SQL SERVER: Get total days between two dates

This is working for me -

SELECT DATEDIFF(DAY, startdate, enddate) AS DayCount

Example : SELECT DATEDIFF(DAY, '11/30/2019', GETDATE()) AS DayCount

Check if a string contains an element from a list (of strings)

Based on your patterns one improvement would be to change to using StartsWith instead of Contains. StartsWith need only iterate through each string until it finds the first mismatch instead of having to restart the search at every character position when it finds one.

Also, based on your patterns, it looks like you may be able to extract the first part of the path for myString, then reverse the comparison -- looking for the starting path of myString in the list of strings rather than the other way around.

string[] pathComponents = myString.Split( Path.DirectorySeparatorChar );
string startPath = pathComponents[0] + Path.DirectorySeparatorChar;

return listOfStrings.Contains( startPath );

EDIT: This would be even faster using the HashSet idea @Marc Gravell mentions since you could change Contains to ContainsKey and the lookup would be O(1) instead of O(N). You would have to make sure that the paths match exactly. Note that this is not a general solution as is @Marc Gravell's but is tailored to your examples.

Sorry for the C# example. I haven't had enough coffee to translate to VB.

How to send an email with Python?

There is indentation problem. The code below will work:

import textwrap

def sendMail(FROM,TO,SUBJECT,TEXT,SERVER):
    import smtplib
    """this is some test documentation in the function"""
    message = textwrap.dedent("""\
        From: %s
        To: %s
        Subject: %s
        %s
        """ % (FROM, ", ".join(TO), SUBJECT, TEXT))
    # Send the mail
    server = smtplib.SMTP(SERVER)
    server.sendmail(FROM, TO, message)
    server.quit()

How to Detect cause of 503 Service Temporarily Unavailable error and handle it?

There is of course some apache log files. Search in your apache configuration files for 'Log' keyword, you'll certainly find plenty of them. Depending on your OS and installation places may vary (in a Typical Linux server it would be /var/log/apache2/[access|error].log).

Having a 503 error in Apache usually means the proxied page/service is not available. I assume you're using tomcat and that means tomcat is either not responding to apache (timeout?) or not even available (down? crashed?). So chances are that it's a configuration error in the way to connect apache and tomcat or an application inside tomcat that is not even sending a response for apache.

Sometimes, in production servers, it can as well be that you get too much traffic for the tomcat server, apache handle more request than the proxyied service (tomcat) can accept so the backend became unavailable.

PHPmailer sending HTML CODE

or if you have still problems you can use this

$mail->Body =  html_entity_decode($Body);

Xcode 10: A valid provisioning profile for this executable was not found

Check if you're using an Ad Hoc Distribution provisioning profile and not an App Store Distribution provisioning profile instead, I was getting this error because of that.

nginx error "conflicting server name" ignored

You have another server_name ec2-xx-xx-xxx-xxx.us-west-1.compute.amazonaws.com somewhere in the config.

How can I check if a string contains ANY letters from the alphabet?

How about:

>>> string_1 = "(555).555-5555"
>>> string_2 = "(555) 555 - 5555 ext. 5555"
>>> any(c.isalpha() for c in string_1)
False
>>> any(c.isalpha() for c in string_2)
True

How do I make my string comparison case insensitive?

Note that you may want to do null checks on them as well prior to doing your .equals or .equalsIgnoreCase.

A null String object can not call an equals method.

ie:

public boolean areStringsSame(String str1, String str2)
{
    if (str1 == null && str2 == null)
        return true;
    if (str1 == null || str2 == null)
        return false;

    return str1.equalsIgnoreCase(str2);
}

'namespace' but is used like a 'type'

All the answers indicate the cause, but sometimes the bigger problem is identifying all the places that define an improper namespace. With tools like Resharper that automatically adjust the namespace using the folder structure, it is rather easy to encounter this issue.

You can get all the lines that create the issue by searching in project / solution using the following regex:

namespace .+\.TheNameUsedAsBothNamespaceAndType

How to clone an InputStream?

If the data read from the stream is large, I would recommend using a TeeInputStream from Apache Commons IO. That way you can essentially replicate the input and pass a t'd pipe as your clone.

How do you close/hide the Android soft keyboard using Java?

You only need to write one line inside your manifest activity tag

 android:windowSoftInputMode="stateAlwaysHidden|adjustPan"

and it will work.

How to find the minimum value of a column in R?

Since it is a numeric operation, we should be converting it to numeric form first. This operation cannot take place if the data is in factor data type.
Check the data type of the columns using str().

min(as.numeric(data[,2]))

Generate random 5 characters string

It seems like str_shuffle would be a good use for this. Seed the shuffle with whichever characters you want.

$my_rand_strng = substr(str_shuffle("ABCDEFGHIJKLMNOPQRSTUVWXYZ"), -5);

How to write multiple line string using Bash with variables?

I'm using Mac OS and to write multiple lines in a SH Script following code worked for me

#! /bin/bash
FILE_NAME="SomeRandomFile"

touch $FILE_NAME

echo """I wrote all
the  
stuff
here.
And to access a variable we can use
$FILE_NAME  

""" >> $FILE_NAME

cat $FILE_NAME

Please don't forget to assign chmod as required to the script file. I have used

chmod u+x myScriptFile.sh

Send a ping to each IP on a subnet

I came late but here is a little script I made for this purpose that I run in Windows PowerShell. You should be able to copy and paste it into the ISE. This will then run the arp command and save the results into a .txt file and open it in notepad.

# Declare Variables
$MyIpAddress
$MyIpAddressLast

# Declare Variable And Get User Inputs
$IpFirstThree=Read-Host 'What is the first three octects of you IP addresses please include the last period?'
$IpStart=Read-Host 'Which IP Address do you want to start with? Include NO periods.'
$IpEnd=Read-Host 'Which IP Address do you want to end with? Include NO periods.'
$SaveMyFilePath=Read-Host 'Enter the file path and name you want for the text file results.'
$PingTries=Read-Host 'Enter the number of times you want to try pinging each address.'

#Run from start ip and ping
#Run the arp -a and output the results to a text file
#Then launch notepad and open the results file
Foreach($MyIpAddressLast in $IpStart..$IpEnd)
{$MyIpAddress=$IpFirstThree+$MyIpAddressLast
    Test-Connection -computername $MyIpAddress -Count $PingTries}
arp -a | Out-File $SaveMyFilePath
notepad.exe $SaveMyFilePath

How to get parameter value for date/time column from empty MaskedTextBox

You're storing the .Text properties of the textboxes directly into the database, this doesn't work. The .Text properties are Strings (i.e. simple text) and not typed as DateTime instances. Do the conversion first, then it will work.

Do this for each date parameter:

Dim bookIssueDate As DateTime = DateTime.ParseExact( txtBookDateIssue.Text, "dd/MM/yyyy", CultureInfo.InvariantCulture ) cmd.Parameters.Add( New OleDbParameter("@Date_Issue", bookIssueDate ) ) 

Note that this code will crash/fail if a user enters an invalid date, e.g. "64/48/9999", I suggest using DateTime.TryParse or DateTime.TryParseExact, but implementing that is an exercise for the reader.

Using NULL in C++?

I never use NULL in my C or C++ code. 0 works just fine, as does if (ptrname). Any competent C or C++ programmer should know what those do.

dlib installation on Windows 10

None of the answers worked for me. This is what worked Assuming you have anaconda python 3.7 installed

1) Dowload and install cmake(make sure to check the option to add cmake to system path during installation to avoid manually doing later) Download from this link cmake download

2) conda install -c conda-forge dlib

'Best' practice for restful POST response

Returning the whole object on an update would not seem very relevant, but I can hardly see why returning the whole object when it is created would be a bad practice in a normal use case. This would be useful at least to get the ID easily and to get the timestamps when relevant. This is actually the default behavior got when scaffolding with Rails.

I really do not see any advantage to returning only the ID and doing a GET request after, to get the data you could have got with your initial POST.

Anyway as long as your API is consistent I think that you should choose the pattern that fits your needs the best. There is not any correct way of how to build a REST API, imo.

SimpleXml to string

Actually asXML() converts the string into xml as it name says:

<id>5</id>

This will display normally on a web page but it will cause problems when you matching values with something else.

You may use strip_tags function to get real value of the field like:

$newString = strip_tags($xml->asXML());

PS: if you are working with integers or floating numbers, you need to convert it into integer with intval() or floatval().

$newNumber = intval(strip_tags($xml->asXML()));

Binary Data Posting with curl

You don't need --header "Content-Length: $LENGTH".

curl --request POST --data-binary "@template_entry.xml" $URL

Note that GET request does not support content body widely.

Also remember that POST request have 2 different coding schema. This is first form:

  $ nc -l -p 6666 &
  $ curl  --request POST --data-binary "@README" http://localhost:6666

POST / HTTP/1.1
User-Agent: curl/7.21.0 (x86_64-pc-linux-gnu) libcurl/7.21.0 OpenSSL/0.9.8o zlib/1.2.3.4 libidn/1.15 libssh2/1.2.6
Host: localhost:6666
Accept: */*
Content-Length: 9309
Content-Type: application/x-www-form-urlencoded
Expect: 100-continue

.. -*- mode: rst; coding: cp1251; fill-column: 80 -*-
.. rst2html.py README README.html
.. contents::

You probably request this:

-F/--form name=content
           (HTTP) This lets curl emulate a filled-in form in
              which a user has pressed the submit button. This
              causes curl to POST data using the Content- Type
              multipart/form-data according to RFC2388. This
              enables uploading of binary files etc. To force the
              'content' part to be a file, prefix the file name
              with an @ sign. To just get the content part from a
              file, prefix the file name with the symbol <. The
              difference between @ and < is then that @ makes a
              file get attached in the post as a file upload,
              while the < makes a text field and just get the
              contents for that text field from a file.

Saving data to a file in C#

Starting with the System.IO namespace (particularly the File or FileInfo objects) should get you started.

http://msdn.microsoft.com/en-us/library/system.io.file.aspx

http://msdn.microsoft.com/en-us/library/system.io.fileinfo.aspx

How do I run a file on localhost?

I'm not really sure what you mean, so I'll start simply:

If the file you're trying to "run" is static content, like HTML or even Javascript, you don't need to run it on "localhost"... you should just be able to open it from wherever it is on your machine in your browser.

If it is a piece of server-side code (ASP[.NET], php, whatever else, uou need to be running either a web server, or if you're using Visual Studio, start the development server for your application (F5 to debug, or CTRL+F5 to start without debugging).

If you're using a web server, you'll need to have a web site configured with the home directory set to the directory the file is in (or, just put the file in whatever home directory is configured).

If you're using Visual Studio, the file just needs to be in your project.

Select 50 items from list at random to write to file

One easy way to select random items is to shuffle then slice.

import random
a = [1,2,3,4,5,6,7,8,9]
random.shuffle(a)
print a[:4] # prints 4 random variables

Remove all values within one list from another list?

Others have suggested ways to make newlist after filtering e.g.

newl = [x for x in l if x not in [2,3,7]]

or

newl = filter(lambda x: x not in [2,3,7], l) 

but from your question it looks you want in-place modification for that you can do this, this will also be much much faster if original list is long and items to be removed less

l = range(1,10)
for o in set([2,3,7,11]):
    try:
        l.remove(o)
    except ValueError:
        pass

print l

output: [1, 4, 5, 6, 8, 9]

I am checking for ValueError exception so it works even if items are not in orginal list.

Also if you do not need in-place modification solution by S.Mark is simpler.

How to handle authentication popup with Selenium WebDriver using Java

Popular solution is to append username and password in URL, like, http://username:[email protected]. However, if your username or password contains special character, then it may fail. So when you create the URL, make sure you encode those special characters.

String username = URLEncoder.encode(user, StandardCharsets.UTF_8.toString());
String password = URLEncoder.encode(pass, StandardCharsets.UTF_8.toString());
String url = “http://“ + username + “:” + password + “@website.com”;
driver.get(url);

How to create multiple page app using react

This is a broad question and there are multiple ways you can achieve this. In my experience, I've seen a lot of single page applications having an entry point file such as index.js. This file would be responsible for 'bootstrapping' the application and will be your entry point for webpack.

index.js

import React from 'react';
import ReactDOM from 'react-dom';
import Application from './components/Application';

const root = document.getElementById('someElementIdHere');

ReactDOM.render(
  <Application />,
  root,
);

Your <Application /> component would contain the next pieces of your app. You've stated you want different pages and that leads me to believe you're using some sort of routing. That could be included into this component along with any libraries that need to be invoked on application start. react-router, redux, redux-saga, react-devtools come to mind. This way, you'll only need to add a single entry point into your webpack configuration and everything will trickle down in a sense.

When you've setup a router, you'll have options to set a component to a specific matched route. If you had a URL of /about, you should create the route in whatever routing package you're using and create a component of About.js with whatever information you need.

PHP call Class method / function

This way:

 $instance = new Functions(); // create an instance (object) of functions class
 $instance->filter($data); // now call it

array filter in python?

>>> A           = [6, 7, 8, 9, 10, 11, 12]
>>> subset_of_A  = [6, 9, 12];
>>> set(A) - set(subset_of_A)
set([8, 10, 11, 7])
>>> 

How to test if a file is a directory in a batch script?

I would like to post my own function script about this subject hope to be useful for someone one day.

@pushd %~dp1
@if not exist "%~nx1" (
        popd
        exit /b 0
) else (
        if exist "%~nx1\*" (
                popd
                exit /b 1
        ) else (
                popd
                exit /b 3
        )
)

This batch script checks if file/folder is exist and if it is a file or a folder.

Usage:

script.bat "PATH"

Exit code(s):

0: file/folder doesn't exist.

1: exists, and it is a folder.

3: exists, and it is a file.

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

Well a cast from myObject to byte[] is never going to work unless you've got an explicit conversion or if myObject is a byte[]. You need a serialization framework of some kind. There are plenty out there, including Protocol Buffers which is near and dear to me. It's pretty "lean and mean" in terms of both space and time.

You'll find that almost all serialization frameworks have significant restrictions on what you can serialize, however - Protocol Buffers more than some, due to being cross-platform.

If you can give more requirements, we can help you out more - but it's never going to be as simple as casting...

EDIT: Just to respond to this:

I need my binary file to contain the object's bytes. Only the bytes, no metadata whatsoever. Packed object-to-object. So I'll be implementing custom serialization.

Please bear in mind that the bytes in your objects are quite often references... so you'll need to work out what to do with them.

I suspect you'll find that designing and implementing your own custom serialization framework is harder than you imagine.

I would personally recommend that if you only need to do this for a few specific types, you don't bother trying to come up with a general serialization framework. Just implement an instance method and a static method in all the types you need:

public void WriteTo(Stream stream)
public static WhateverType ReadFrom(Stream stream)

One thing to bear in mind: everything becomes more tricky if you've got inheritance involved. Without inheritance, if you know what type you're starting with, you don't need to include any type information. Of course, there's also the matter of versioning - do you need to worry about backward and forward compatibility with different versions of your types?

Set selected option of select box

I have found using the jQuery .val() method to have a significant drawback.

<select id="gate"></select>
$("#gate").val("Gateway 2");

If this select box (or any other input object) is in a form and there is a reset button used in the form, when the reset button is clicked the set value will get cleared and not reset to the beginning value as you would expect.

This seems to work the best for me.

For Select boxes

<select id="gate"></select>
$("#gate option[value='Gateway 2']").attr("selected", true);

For text inputs

<input type="text" id="gate" />
$("#gate").attr("value", "your desired value")

For textarea inputs

<textarea id="gate"></textarea>
$("#gate").html("your desired value")

For checkbox boxes

<input type="checkbox" id="gate" />
$("#gate option[value='Gateway 2']").attr("checked", true);

For radio buttons

<input type="radio" id="gate" value="this"/> or <input type="radio" id="gate" value="that"/>
$("#gate[value='this']").attr("checked", true);

How do I load external fonts into an HTML document?

Regarding Jay Stevens answer: "The fonts available to use in an HTML file have to be present on the user's machine and accessible from the web browser, so unless you want to distribute the fonts to the user's machine via a separate external process, it can't be done." That's true.

But there is another way using javascript / canvas / flash - very good solution gives cufon: http://cufon.shoqolate.com/generate/ library that generates a very easy to use external fonts methods.

How to make rounded percentages add up to 100%

There are many ways to do just this, provided you are not concerned about reliance on the original decimal data.

The first and perhaps most popular method would be the Largest Remainder Method

Which is basically:

  1. Rounding everything down
  2. Getting the difference in sum and 100
  3. Distributing the difference by adding 1 to items in decreasing order of their decimal parts

In your case, it would go like this:

13.626332%
47.989636%
 9.596008%
28.788024%

If you take the integer parts, you get

13
47
 9
28

which adds up to 97, and you want to add three more. Now, you look at the decimal parts, which are

.626332%
.989636%
.596008%
.788024%

and take the largest ones until the total reaches 100. So you would get:

14
48
 9
29

Alternatively, you can simply choose to show one decimal place instead of integer values. So the numbers would be 48.3 and 23.9 etc. This would drop the variance from 100 by a lot.

Angular 2 router.navigate

_x000D_
_x000D_
import { ActivatedRoute } from '@angular/router';_x000D_
_x000D_
export class ClassName {_x000D_
  _x000D_
  private router = ActivatedRoute;_x000D_
_x000D_
    constructor(r: ActivatedRoute) {_x000D_
        this.router =r;_x000D_
    }_x000D_
_x000D_
onSuccess() {_x000D_
     this.router.navigate(['/user_invitation'],_x000D_
         {queryParams: {email: loginEmail, code: userCode}});_x000D_
}_x000D_
_x000D_
}_x000D_
_x000D_
_x000D_
Get this values:_x000D_
---------------_x000D_
_x000D_
ngOnInit() {_x000D_
    this.route_x000D_
        .queryParams_x000D_
        .subscribe(params => {_x000D_
            let code = params['code'];_x000D_
            let userEmail = params['email'];_x000D_
        });_x000D_
}
_x000D_
_x000D_
_x000D_

Ref: https://angular.io/docs/ts/latest/api/router/index/NavigationExtras-interface.html

SQL NVARCHAR and VARCHAR Limits

Okay, so if later on down the line the issue is that you have a query that's greater than the allowable size (which may happen if it keeps growing) you're going to have to break it into chunks and execute the string values. So, let's say you have a stored procedure like the following:

CREATE PROCEDURE ExecuteMyHugeQuery
    @SQL VARCHAR(MAX) -- 2GB size limit as stated by Martin Smith
AS
BEGIN
    -- Now, if the length is greater than some arbitrary value
    -- Let's say 2000 for this example
    -- Let's chunk it
    -- Let's also assume we won't allow anything larger than 8000 total
    DECLARE @len INT
    SELECT @len = LEN(@SQL)

    IF (@len > 8000)
    BEGIN
        RAISERROR ('The query cannot be larger than 8000 characters total.',
                   16,
                   1);
    END

    -- Let's declare our possible chunks
    DECLARE @Chunk1 VARCHAR(2000),
            @Chunk2 VARCHAR(2000),
            @Chunk3 VARCHAR(2000),
            @Chunk4 VARCHAR(2000)

    SELECT @Chunk1 = '',
           @Chunk2 = '',
           @Chunk3 = '',
           @Chunk4 = ''

    IF (@len > 2000)
    BEGIN
        -- Let's set the right chunks
        -- We already know we need two chunks so let's set the first
        SELECT @Chunk1 = SUBSTRING(@SQL, 1, 2000)

        -- Let's see if we need three chunks
        IF (@len > 4000)
        BEGIN
            SELECT @Chunk2 = SUBSTRING(@SQL, 2001, 2000)

            -- Let's see if we need four chunks
            IF (@len > 6000)
            BEGIN
                SELECT @Chunk3 = SUBSTRING(@SQL, 4001, 2000)
                SELECT @Chunk4 = SUBSTRING(@SQL, 6001, (@len - 6001))
            END
              ELSE
            BEGIN
                SELECT @Chunk3 = SUBSTRING(@SQL, 4001, (@len - 4001))
            END
        END
          ELSE
        BEGIN
            SELECT @Chunk2 = SUBSTRING(@SQL, 2001, (@len - 2001))
        END
    END

    -- Alright, now that we've broken it down, let's execute it
    EXEC (@Chunk1 + @Chunk2 + @Chunk3 + @Chunk4)
END

Prevent line-break of span element

If you only need to prevent line-breaks on space characters, you can use &nbsp; entities between words:

No&nbsp;line&nbsp;break

instead of

<span style="white-space:nowrap">No line break</span>

Output data from all columns in a dataframe in pandas

I'm coming to python from R, and R's head() function wraps lines in a really convenient way for looking at data:

> head(cbind(mtcars, mtcars, mtcars))
                   mpg cyl disp  hp drat    wt  qsec vs am gear carb  mpg cyl
Mazda RX4         21.0   6  160 110 3.90 2.620 16.46  0  1    4    4 21.0   6
Mazda RX4 Wag     21.0   6  160 110 3.90 2.875 17.02  0  1    4    4 21.0   6
Datsun 710        22.8   4  108  93 3.85 2.320 18.61  1  1    4    1 22.8   4
Hornet 4 Drive    21.4   6  258 110 3.08 3.215 19.44  1  0    3    1 21.4   6
Hornet Sportabout 18.7   8  360 175 3.15 3.440 17.02  0  0    3    2 18.7   8
Valiant           18.1   6  225 105 2.76 3.460 20.22  1  0    3    1 18.1   6
                  disp  hp drat    wt  qsec vs am gear carb  mpg cyl disp  hp
Mazda RX4          160 110 3.90 2.620 16.46  0  1    4    4 21.0   6  160 110
Mazda RX4 Wag      160 110 3.90 2.875 17.02  0  1    4    4 21.0   6  160 110
Datsun 710         108  93 3.85 2.320 18.61  1  1    4    1 22.8   4  108  93
Hornet 4 Drive     258 110 3.08 3.215 19.44  1  0    3    1 21.4   6  258 110
Hornet Sportabout  360 175 3.15 3.440 17.02  0  0    3    2 18.7   8  360 175
Valiant            225 105 2.76 3.460 20.22  1  0    3    1 18.1   6  225 105
                  drat    wt  qsec vs am gear carb
Mazda RX4         3.90 2.620 16.46  0  1    4    4
Mazda RX4 Wag     3.90 2.875 17.02  0  1    4    4
Datsun 710        3.85 2.320 18.61  1  1    4    1
Hornet 4 Drive    3.08 3.215 19.44  1  0    3    1
Hornet Sportabout 3.15 3.440 17.02  0  0    3    2
Valiant           2.76 3.460 20.22  1  0    3    1

I developed the following little python function to mimic this functionality:

def rhead(x, nrow = 6, ncol = 4):
    pd.set_option('display.expand_frame_repr', False)
    seq = np.arange(0, len(x.columns), ncol)
    for i in seq:
        print(x.loc[range(0, nrow), x.columns[range(i, min(i+ncol, len(x.columns)))]])
    pd.set_option('display.expand_frame_repr', True)

(it depends on pandas and numpy, obviously)

What is the list of supported languages/locales on Android?

Update for 4.0

Android 4.0.3 Platform

Arabic, Egypt (ar_EG)
Arabic, Israel (ar_IL)
Bulgarian, Bulgaria (bg_BG)
Catalan, Spain (ca_ES)
Chinese, PRC (zh_CN)
Chinese, Taiwan (zh_TW)
Croatian, Croatia (hr_HR)
Czech, Czech Republic (cs_CZ)
Danish, Denmark(da_DK)
Dutch, Belgium (nl_BE)
Dutch, Netherlands (nl_NL)
English, Australia (en_AU)
English, Britain (en_GB)
English, Canada (en_CA)
English, India (en_IN)
English, Ireland (en_IE)
English, New Zealand (en_NZ)
English, Singapore(en_SG)
English, South Africa (en_ZA)
English, US (en_US)
Finnish, Finland (fi_FI)
French, Belgium (fr_BE)
French, Canada (fr_CA)
French, France (fr_FR)
French, Switzerland (fr_CH)
German, Austria (de_AT)
German, Germany (de_DE)
German, Liechtenstein (de_LI)
German, Switzerland (de_CH)
Greek, Greece (el_GR)
Hebrew, Israel (he_IL)
Hindi, India (hi_IN)
Hungarian, Hungary (hu_HU)
Indonesian, Indonesia (id_ID)
Italian, Italy (it_IT)
Italian, Switzerland (it_CH)
Japanese (ja_JP)
Korean (ko_KR)
Latvian, Latvia (lv_LV)
Lithuanian, Lithuania (lt_LT)
Norwegian bokmål, Norway (nb_NO)
Polish (pl_PL)
Portuguese, Brazil (pt_BR)
Portuguese, Portugal (pt_PT)
Romanian, Romania (ro_RO)
Russian (ru_RU)
Serbian (sr_RS)
Slovak, Slovakia (sk_SK)
Slovenian, Slovenia (sl_SI)
Spanish (es_ES)
Spanish, US (es_US)
Swedish, Sweden (sv_SE)
Tagalog, Philippines (tl_PH)
Thai, Thailand (th_TH)
Turkish, Turkey (tr_TR)
Ukrainian, Ukraine (uk_UA)
Vietnamese, Vietnam (vi_VN)

SOURCE: http://us.dinodirect.com/Forum/Latest-Posts-5/Android-Versions-and-their-Locales-1-86587/

Input text dialog Android

@LukeTaylor: I currently have the same task at hand (creating a popup/dialog that contains an EditText)..
Personally, I find the fully-dynamic route to be somewhat limiting in terms of creativity.

FULLY CUSTOM DIALOG LAYOUT :

Rather than relying entirely upon Code to create the Dialog, you can fully customize it like so :

1) - Create a new Layout Resource file.. This will act as your Dialog, allowing for full creative freedom!
NOTE: Refer to the Material Design guidelines to help keep things clean and on point.

2) - Give ID's to all of your View elements.. In my example code below, I have 1 EditText, and 2 Buttons.

3) - Create an Activity with a Button, for testing purposes.. We'll have it inflate and launch your Dialog!

public void buttonClick_DialogTest(View view) {

    AlertDialog.Builder mBuilder = new AlertDialog.Builder(MainActivity.this);

    //  Inflate the Layout Resource file you created in Step 1
    View mView = getLayoutInflater().inflate(R.layout.timer_dialog_layout, null);

    //  Get View elements from Layout file. Be sure to include inflated view name (mView)
    final EditText mTimerMinutes = (EditText) mView.findViewById(R.id.etTimerValue);
    Button mTimerOk = (Button) mView.findViewById(R.id.btnTimerOk);
    Button mTimerCancel = (Button) mView.findViewById(R.id.btnTimerCancel);

    //  Create the AlertDialog using everything we needed from above
    mBuilder.setView(mView);
    final AlertDialog timerDialog = mBuilder.create();

    //  Set Listener for the OK Button
    mTimerOk.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick (View view) {
            if (!mTimerMinutes.getText().toString().isEmpty()) {
                Toast.makeText(MainActivity.this, "You entered a Value!,", Toast.LENGTH_LONG).show();
            } else {
                Toast.makeText(MainActivity.this, "Please enter a Value!", Toast.LENGTH_LONG).show();
            }
        }
    });

    //  Set Listener for the CANCEL Button
    mTimerCancel.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick (View view) {
            timerDialog.dismiss();
        }
    });

    //  Finally, SHOW your Dialog!
    timerDialog.show();


    //  END OF buttonClick_DialogTest
}


Piece of cake! Full creative freedom! Just be sure to follow Material Guidelines ;)

I hope this helps someone! Let me know what you guys think!

Node.js request CERT_HAS_EXPIRED

The best way to fix this:

Renew the certificate. This can be done for free using Greenlock which issues certificates via Let's Encrypt™ v2

A less insecure way to fix this:

'use strict';

var request = require('request');
var agentOptions;
var agent;

agentOptions = {
  host: 'www.example.com'
, port: '443'
, path: '/'
, rejectUnauthorized: false
};

agent = new https.Agent(agentOptions);

request({
  url: "https://www.example.com/api/endpoint"
, method: 'GET'
, agent: agent
}, function (err, resp, body) {
  // ...
});

By using an agent with rejectUnauthorized you at least limit the security vulnerability to the requests that deal with that one site instead of making your entire node process completely, utterly insecure.

Other Options

If you were using a self-signed cert you would add this option:

agentOptions.ca = [ selfSignedRootCaPemCrtBuffer ];

For trusted-peer connections you would also add these 2 options:

agentOptions.key = clientPemKeyBuffer;
agentOptions.cert = clientPemCrtSignedBySelfSignedRootCaBuffer;

Bad Idea

It's unfortunate that process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0'; is even documented. It should only be used for debugging and should never make it into in sort of code that runs in the wild. Almost every library that runs atop https has a way of passing agent options through. Those that don't should be fixed.

How to return a string value from a Bash function

To illustrate my comment on Andy's answer, with additional file descriptor manipulation to avoid use of /dev/tty:

#!/bin/bash

exec 3>&1

returnString() {
    exec 4>&1 >&3
    local s=$1
    s=${s:="some default string"}
    echo "writing to stdout"
    echo "writing to stderr" >&2
    exec >&4-
    echo "$s"
}

my_string=$(returnString "$*")
echo "my_string:  [$my_string]"

Still nasty, though.

Java to Jackson JSON serialization: Money fields

I'm one of the maintainers of jackson-datatype-money, so take this answer with a grain of salt since I'm certainly biased. The module should cover your needs and it's pretty light-weight (no additional runtime dependencies). In addition it's mentioned in the Jackson docs, Spring docs and there were even some discussions already about how to integrate it into the official ecosystem of Jackson.

How to iterate over arguments in a Bash script

Amplifying on baz's answer, if you need to enumerate the argument list with an index (such as to search for a specific word), you can do this without copying the list or mutating it.

Say you want to split an argument list at a double-dash ("--") and pass the arguments before the dashes to one command, and the arguments after the dashes to another:

 toolwrapper() {
   for i in $(seq 1 $#); do
     [[ "${!i}" == "--" ]] && break
   done || return $? # returns error status if we don't "break"

   echo "dashes at $i"
   echo "Before dashes: ${@:1:i-1}"
   echo "After dashes: ${@:i+1:$#}"
 }

Results should look like this:

 $ toolwrapper args for first tool -- and these are for the second
 dashes at 5
 Before dashes: args for first tool
 After dashes: and these are for the second

JavaScript require() on client side

The clientside-require library provides an asynchronous load() function that can be used to load any JS file or NPM module (which uses module.exports), any .css file, any .json, any .html, any any other file as text.

e.g., npm install clientside-require --save

<script src = '/node_modules/clientside-require/dist/bundle.js'></script>
<script>
load('color-name') // an npm module
   .then(color_name=>{
        console.log(color_name.blue); // outputs  [0, 0, 255]
   })
</script>

A really cool part of this project is that inside of any load()ed script, you can use the synchronous require() function the same way you would expect in node.js!

e.g.,

load('/path/to/functionality.js')

and inside /path/to/functionality.js:

var query_string = require("qs") // an npm module
module.exports = function(name){
    return qs.stringify({
         name:name,
         time:new Date()
    }
}

That last part, implementing the synchronous require() method, is what enables it to utilize NPM packages built to run on the server.


This module was designed to implement the require functionality as closely as possible in the browser. Disclaimer: I have written this module.

Unique Key constraints for multiple columns in Entity Framework

I found three ways to solve the problem.

Unique indexes in EntityFramework Core:

First approach:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
   modelBuilder.Entity<Entity>()
   .HasIndex(p => new {p.FirstColumn , p.SecondColumn}).IsUnique();
}

The second approach to create Unique Constraints with EF Core by using Alternate Keys.

Examples

One column:

modelBuilder.Entity<Blog>().HasAlternateKey(c => c.SecondColumn).HasName("IX_SingeColumn");

Multiple columns:

modelBuilder.Entity<Entity>().HasAlternateKey(c => new [] {c.FirstColumn, c.SecondColumn}).HasName("IX_MultipleColumns");

EF 6 and below:


First approach:

dbContext.Database.ExecuteSqlCommand(string.Format(
                        @"CREATE UNIQUE INDEX LX_{0} ON {0} ({1})", 
                                 "Entitys", "FirstColumn, SecondColumn"));

This approach is very fast and useful but the main problem is that Entity Framework doesn't know anything about those changes!


Second approach:
I found it in this post but I did not tried by myself.

CreateIndex("Entitys", new string[2] { "FirstColumn", "SecondColumn" },
              true, "IX_Entitys");

The problem of this approach is the following: It needs DbMigration so what do you do if you don't have it?


Third approach:
I think this is the best one but it requires some time to do it. I will just show you the idea behind it: In this link http://code.msdn.microsoft.com/CSASPNETUniqueConstraintInE-d357224a you can find the code for unique key data annotation:

[UniqueKey] // Unique Key 
public int FirstColumn  { get; set;}
[UniqueKey] // Unique Key 
public int SecondColumn  { get; set;}

// The problem hier
1, 1  = OK 
1 ,2  = NO OK 1 IS UNIQUE

The problem for this approach; How can I combine them? I have an idea to extend this Microsoft implementation for example:

[UniqueKey, 1] // Unique Key 
public int FirstColumn  { get; set;}
[UniqueKey ,1] // Unique Key 
public int SecondColumn  { get; set;}

Later in the IDatabaseInitializer as described in the Microsoft example you can combine the keys according to the given integer. One thing has to be noted though: If the unique property is of type string then you have to set the MaxLength.

JPA Criteria API - How to add JOIN clause (as general sentence as possible)

Warning! There's a numbers of errors on the Sun JPA 2 example and the resulting pasted content in Pascal's answer. Please consult this post.

This post and the Sun Java EE 6 JPA 2 example really held back my comprehension of JPA 2. After plowing through the Hibernate and OpenJPA manuals and thinking that I had a good understanding of JPA 2, I still got confused afterwards when returning to this post.

Why doesn't margin:auto center an image?

You need to render it as block level;

img {
   display: block;
   width: auto;
   margin: auto;
}

Hibernate: failed to lazily initialize a collection of role, no session or session was closed

for me it worked the approach that I used in eclipselink as well. Just call the size() of the collection that should be loaded before using it as parameter to pages.

for (Entity e : entityListKeeper.getEntityList()) {
    e.getListLazyLoadedEntity().size();
}

Here entityListKeeper has List of Entity that has list of LazyLoadedEntity. If you have just therelation Entity has list of LazyLoadedEntity then the solution is:

getListLazyLoadedEntity().size();

How to load a jar file at runtime

I was asked to build a java system that will have the ability to load new code while running

You might want to base your system on OSGi (or at least take a lot at it), which was made for exactly this situation.

Messing with classloaders is really tricky business, mostly because of how class visibility works, and you do not want to run into hard-to-debug problems later on. For example, Class.forName(), which is widely used in many libraries does not work too well on a fragmented classloader space.

How do you deploy Angular apps?

You are actually here touching two questions in one.

The first one is How to host your application?.
And as @toskv mentioned its really too broad question to be answered and depends on numerous different things.

The second one is How do you prepare the deployment version of the application?.
You have several options here:

  1. Deploy as it is. Just that - no minification, concatenation, name mangling, etc. Transpile all your ts project copy all your resulting js/css/... sources + dependencies to the hosting server and you are good to go.
  2. Deploy using special bundling tools, like webpack or systemjs builder.
    They come with all the possibilities that are lacking in #1.
    You can pack all your app code into just a couple of js/css/... files that you reference in your HTML. systemjs builder even allows you to get rid of the need to include systemjs as part of your deployment package.

  3. You can use ng deploy as of Angular 8 to deploy your app from your CLI. ng deploy will need to be used in conjunction with your platform of choice (such as @angular/fire). You can check the official docs to see what works best for you here

Yes you will most likely need to deploy systemjs and bunch of other external libraries as part of your package. And yes you will be able to bundle them into just couple of js files you reference from your HTML page.

You do not have to reference all your compiled js files from the page though - systemjs as a module loader will take care of that.

I know it sounds muddy - to help get you started with the #2 here are two really good sample applications:

SystemJS builder: angular2 seed

WebPack: angular2 webpack starter

How to retrieve the dimensions of a view?

I believe the OP is long gone, but in case this answer is able to help future searchers, I thought I'd post a solution that I have found. I have added this code into my onCreate() method:

EDITED: 07/05/11 to include code from comments:

final TextView tv = (TextView)findViewById(R.id.image_test);
ViewTreeObserver vto = tv.getViewTreeObserver();
vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {

    @Override
    public void onGlobalLayout() {
        LayerDrawable ld = (LayerDrawable)tv.getBackground();
        ld.setLayerInset(1, 0, tv.getHeight() / 2, 0, 0);
        ViewTreeObserver obs = tv.getViewTreeObserver();

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
            obs.removeOnGlobalLayoutListener(this);
        } else {
            obs.removeGlobalOnLayoutListener(this);
        }
    }

});

First I get a final reference to my TextView (to access in the onGlobalLayout() method). Next, I get the ViewTreeObserver from my TextView, and add an OnGlobalLayoutListener, overriding onGLobalLayout (there does not seem to be a superclass method to invoke here...) and adding my code which requires knowing the measurements of the view into this listener. All works as expected for me, so I hope that this is able to help.

How to initialise a string from NSData in Swift

import Foundation
var string = NSString(data: NSData?, encoding: UInt)

How can one use multi threading in PHP applications

You could simulate threading. PHP can run background processes via popen (or proc_open). Those processes can be communicated with via stdin and stdout. Of course those processes can themselves be a php program. That is probably as close as you'll get.

How to convert integer into date object python?

I would suggest the following simple approach for conversion:

from datetime import datetime, timedelta
s = "20120213"
# you could also import date instead of datetime and use that.
date = datetime(year=int(s[0:4]), month=int(s[4:6]), day=int(s[6:8]))

For adding/subtracting an arbitary amount of days (seconds work too btw.), you could do the following:

date += timedelta(days=10)
date -= timedelta(days=5)

And convert back using:

s = date.strftime("%Y%m%d")

To convert the integer to a string safely, use:

s = "{0:-08d}".format(i)

This ensures that your string is eight charecters long and left-padded with zeroes, even if the year is smaller than 1000 (negative years could become funny though).

Further reference: datetime objects, timedelta objects

The ScriptManager must appear before any controls that need it

If you are using microsoft ajax on your page you need the script manager control added to your master page or the page that needs it. It Manages ASP.NET Ajax script libraries and script files, partial-page rendering, and client proxy class generation for Web and application services

<asp:ScriptManager ID="ScriptManger1" runat="Server">
</asp:ScriptManager>

The full usage

<asp:ScriptManager
    AllowCustomErrorsRedirect="True|False"
    AsyncPostBackErrorMessage="string"
    AsyncPostBackTimeout="integer"
    AuthenticationService-Path="uri"
    EnablePageMethods="True|False"
    EnablePartialRendering="True|False"
    EnableScriptGlobalization="True|False"
    EnableScriptLocalization="True|False"
    EnableTheming="True|False"
    EnableViewState="True|False"
    ID="string"
    LoadScriptsBeforeUI="True|False"
    OnAsyncPostBackError="AsyncPostBackError event handler"
    OnDataBinding="DataBinding event handler"
    OnDisposed="Disposed event handler"
    OnInit="Init event handler"
    OnLoad="Load event handler"
    OnPreRender="PreRender event handler"
    OnResolveScriptReference="ResolveScriptReference event handler"
    OnUnload="Unload event handler"
    ProfileService-LoadProperties="string"
    ProfileService-Path="uri"
    RoleService-LoadRoles="True|False"
    RoleService-Path="uri"
    runat="server"
    ScriptMode="Auto|Inherit|Debug|Release"
    ScriptPath="string"
    SkinID="string"
    SupportsPartialRendering="True|False"
    Visible="True|False">
        <AuthenticationService
            Path="uri" />
        <ProfileService
            LoadProperties="string"
            Path="uri" />
        <RoleService
            LoadRoles="True|False"
            Path="uri" />
        <Scripts>
            <asp:ScriptReference
                Assembly="string"
                IgnoreScriptPath="True|False"
                Name="string"
                NotifyScriptLoaded="True|False"
                Path="string"
                ResourceUICultures="string"
                ScriptMode="Auto|Debug|Inherit|Release" />
        </Scripts>
        <Services>
            <asp:ServiceReference
                InlineScript="True|False"
                Path="string" />
        </Services>
</asp:ScriptManager>

Jinja2 template not rendering if-elif-else statement properly

You are testing if the values of the variables error and Already are present in RepoOutput[RepoName.index(repo)]. If these variables don't exist then an undefined object is used.

Both of your if and elif tests therefore are false; there is no undefined object in the value of RepoOutput[RepoName.index(repo)].

I think you wanted to test if certain strings are in the value instead:

{% if "error" in RepoOutput[RepoName.index(repo)] %}
    <td id="error"> {{ RepoOutput[RepoName.index(repo)] }} </td>
{% elif "Already" in RepoOutput[RepoName.index(repo) %}
    <td id="good"> {{ RepoOutput[RepoName.index(repo)] }} </td>
{% else %}
    <td id="error"> {{ RepoOutput[RepoName.index(repo)] }} </td>
{% endif %}
</tr>

Other corrections I made:

  • Used {% elif ... %} instead of {$ elif ... %}.
  • moved the </tr> tag out of the if conditional structure, it needs to be there always.
  • put quotes around the id attribute

Note that most likely you want to use a class attribute instead here, not an id, the latter must have a value that must be unique across your HTML document.

Personally, I'd set the class value here and reduce the duplication a little:

{% if "Already" in RepoOutput[RepoName.index(repo)] %}
    {% set row_class = "good" %}
{% else %}
    {% set row_class = "error" %}
{% endif %}
<td class="{{ row_class }}"> {{ RepoOutput[RepoName.index(repo)] }} </td>

Setting max width for body using Bootstrap

You don't have to modify bootstrap-responsive by removing @media (max-width:1200px) ...

My application has a max-width of 1600px. Here's how it worked for me:

  1. Create bootstrap-custom.css - As much as possible, I don't want to override my original bootstrap css.

  2. Inside bootstrap-custom.css, override the container-fluid by including this code:

Like this:

/* set a max-width for horizontal fluid layout and make it centered */
.container-fluid {
  margin-right: auto;
  margin-left: auto;
  max-width: 1600px; /* or 950px */
}

How to work offline with TFS

There are couple of little visual studio extensions for this purpose:

  1. For VS2010 & TFS 2010, try this
  2. For VS2012 & TFS 2010, use this

In case of TFS 2012, looks like there is no need for 'Go offline' extensions. I read something about a new feature called local workspace for the similar purpose.

Alternatively I had good success with Git-TF. All the goodness of git and when you are ready, you can push it to TFS.

What is javax.inject.Named annotation supposed to be used for?

Use @Named to differentiate between different objects of the same type bound in the same scope.

@Named("maxWaitTime")
public long maxWaitTimeMs;

@Named("minWaitTime")
public long minWaitTimeMs;

Without the @Named qualifier, the injector would not know which long to bind to which variable.

  • If you want to create annotations that act like @Named, use the @Qualifier annotation when creating them.

  • If you look at @Named, it is itself annotated with @Qualifier.

How to use z-index in svg elements?

We have already 2019 and z-index is still not supported in SVG.

You can see on the site SVG2 support in Mozilla that the state for z-indexNot implemented.

You can also see on the site Bug 360148 "Support the 'z-index' property on SVG elements" (Reported: 12 years ago).

But you have 3 possibilities in SVG to set it:

  1. With element.appendChild(aChild);
  2. With parentNode.insertBefore(newNode, referenceNode);
  3. With targetElement.insertAdjacentElement(positionStr, newElement); (No support in IE for SVG)

Interactive demo example

With all this 3 functions.

_x000D_
_x000D_
var state = 0,_x000D_
    index = 100;_x000D_
_x000D_
document.onclick = function(e)_x000D_
{_x000D_
    if(e.target.getAttribute('class') == 'clickable')_x000D_
    {_x000D_
        var parent = e.target.parentNode;_x000D_
_x000D_
        if(state == 0)_x000D_
            parent.appendChild(e.target);_x000D_
        else if(state == 1)_x000D_
            parent.insertBefore(e.target, null); //null - adds it on the end_x000D_
        else if(state == 2)_x000D_
            parent.insertAdjacentElement('beforeend', e.target);_x000D_
        else_x000D_
            e.target.style.zIndex = index++;_x000D_
    }_x000D_
};_x000D_
_x000D_
if(!document.querySelector('svg').insertAdjacentElement)_x000D_
{_x000D_
    var label = document.querySelectorAll('label')[2];_x000D_
    label.setAttribute('disabled','disabled');_x000D_
    label.style.color = '#aaa';_x000D_
    label.style.background = '#eee';_x000D_
    label.style.cursor = 'not-allowed';_x000D_
    label.title = 'This function is not supported in SVG for your browser.';_x000D_
}
_x000D_
label{background:#cef;padding:5px;cursor:pointer}_x000D_
.clickable{cursor:pointer}
_x000D_
With: _x000D_
<label><input type="radio" name="check" onclick="state=0" checked/>appendChild()</label>_x000D_
<label><input type="radio" name="check" onclick="state=1"/>insertBefore()</label><br><br>_x000D_
<label><input type="radio" name="check" onclick="state=2"/>insertAdjacentElement()</label>_x000D_
<label><input type="radio" name="check" onclick="state=3"/>Try it with z-index</label>_x000D_
<br>_x000D_
<svg width="150" height="150" viewBox="0 0 150 150">_x000D_
    <g stroke="none">_x000D_
        <rect id="i1" class="clickable" x="10" y="10" width="50" height="50" fill="#80f"/>_x000D_
        <rect id="i2" class="clickable" x="40" y="40" width="50" height="50" fill="#8f0"/>_x000D_
        <rect id="i3" class="clickable" x="70" y="70" width="50" height="50" fill="#08f"/>_x000D_
    </g>_x000D_
</svg>
_x000D_
_x000D_
_x000D_

How to prevent a double-click using jQuery?

I have the similar issue. You can use setTimeout() to avoid the double-click.

//some codes here above after the click then disable it

// also check here if there's an attribute disabled

// if there's an attribute disabled in the btn tag then // return. Convert that into js.

$('#btn1').prop("disabled", true);

setTimeout(function(){
    $('#btn1').prop("disabled", false);
}, 300);

Function names in C++: Capitalize or not?

Since C++11, you may want to use either snake_case or camelCase for function names.

This is because to make a class work as the range-expression in a range-based for-loop, you have to define functions called begin and end (case-sensitive) for that class.

Consequently, using e.g. PascalCase for function names means you have to break the naming consistency in your project if you ever need to make a class work with the range-based for.

How to encrypt and decrypt String with my passphrase in Java (Pc not mobile platform)?

Both Encrypt and Decrypt with AES and DES Algoritham ,This worked for me perfectly GithubLink: Java Code For Encryption and Decryption

package decrypt;

import java.security.Key;
import java.security.NoSuchAlgorithmException;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
/* Decrypt encrypted string into plain string with aes and Des algoritham*/ 

public class Decrypt {

public String decrypt(String str,String k) throws Exception {
// Decode base64 to get bytes

 Cipher  dcipher = Cipher.getInstance("AES");
 Key aesKey = new SecretKeySpec(k.getBytes(), "AES");
 dcipher.init(dcipher.DECRYPT_MODE, aesKey);
//System.out.println(aesKey);
byte[] dec = new sun.misc.BASE64Decoder().decodeBuffer(str);
byte[] utf8 = dcipher.doFinal(dec);
//System.out.println(utf8);
// Decode using utf-8
 return new String(utf8, "UTF8");
 }


  public String encrypt(String str,String k) throws Exception {
 Cipher ecipher = Cipher.getInstance("AES");
 Key aeskey = new SecretKeySpec(k.getBytes(),"AES");
 byte[] utf8 = str.getBytes("UTF8");
 ecipher.init(ecipher.ENCRYPT_MODE, aeskey );

 byte[] enc = ecipher.doFinal(utf8);

 return new sun.misc.BASE64Encoder().encode(enc);

}
 public String encrypt(String str,String k,String Algo) throws Exception {
 Cipher ecipher = Cipher.getInstance(Algo);
 Key aeskey = new SecretKeySpec(k.getBytes(),Algo);
 byte[] utf8 = str.getBytes("UTF8");
 ecipher.init(ecipher.ENCRYPT_MODE, aeskey );

 byte[] enc = ecipher.doFinal(utf8);

 return new sun.misc.BASE64Encoder().encode(enc);

}
public String decrypt(String str,String k,String Algo) throws Exception {
    // Decode base64 to get bytes

     Cipher  dcipher = Cipher.getInstance(Algo);
     Key aesKey = new SecretKeySpec(k.getBytes(), Algo);
     dcipher.init(dcipher.DECRYPT_MODE, aesKey);
    //System.out.println(aesKey);
    byte[] dec = new sun.misc.BASE64Decoder().decodeBuffer(str);
    byte[] utf8 = dcipher.doFinal(dec);
    //System.out.println(utf8);
 // Decode using utf-8
     return new String(utf8, "UTF8");
  }

public static void main(String args []) throws Exception
{
    String original = "rakesh";
    String data = "CfPcX0G+e7TLKKMyyvrvrQ==";
    String k = "qertyuiopasdfghw"; //AES key length must be 16
    String k1 = "qertyuio";  // DES key length must be 8 
    String data1 = "rakesh";
    String data2 = "nAtvNq7uHKE=";
    String Algo= "DES";
    String Algo1= "AES";
    Decrypt decrypter = new Decrypt();
     System.out.println("Original String: " + original);

     System.out.println("encrypted String in DES: " + decrypter.encrypt(data1, 
      k1,Algo));
     System.out.println("Decrypted String in DES: " + decrypter.decrypt(data2, 
       k1,Algo));
     System.out.println("encrypted String in AES: " + decrypter.encrypt(data1, 
      k,Algo1));
     System.out.println("Decrypted String in AES: " + decrypter.decrypt(data, 
      k,Algo1));
   }
}

Asp.net 4.0 has not been registered

For those getting this error in after installing .NET Framework 4.6 - Read and install one of these hotfixes to resolve the issue.

How to set background color of an Activity to white programmatically?

View randview = new View(getBaseContext());
randview = (View)findViewById(R.id.container);
randview.setBackgroundColor(Color.BLUE);

worked for me. thank you.

bootstrap initially collapsed element

When you expand or collapse accordion it just adds/removes a class "in" and sets the height:auto or 0 to the accordion div.

Demo

So in your accordion when you define it just remove "in" class from the div as below. Whenever you expand an accorion it just adds the "in" class to make it visible.

If you render the page with "in" bootstrap looks for the class and it will make the div's height:auto, if it not present it will be at zero height.

<div id="collapseOne" class="accordion-body collapse">

c# Best Method to create a log file

add this config file


*************************************************************************************
<!--Configuration for file appender-->

<configuration>
  <configSections>
    <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
  </configSections>
  <log4net>
    <appender name="FileAppender" type="log4net.Appender.FileAppender">
      <file value="logfile.txt" />
      <appendToFile value="true" />
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%d [%t] %-5p [%logger] - %m%n" />
      </layout>
    </appender>
    <root>
      <level value="DEBUG" />
      <appender-ref ref="FileAppender" />
    </root>
  </log4net>
</configuration>

*************************************************************************************

<!--Configuration for console appender-->


<configuration>

  <configSections>
    <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,
        log4net" />
  </configSections>

  <log4net>
    <appender name="ConsoleAppender" type="log4net.Appender.ConsoleAppender" >
      <layout type="log4net.Layout.PatternLayout">
        <param name="ConversionPattern" value="%d [%t] %-5p [%logger] - %m%n" />
      </layout>
    </appender>
   <root>
      <level value="ALL" />
      <appender-ref ref="ConsoleAppender" />
    </root>
  </log4net>
</configuration>

How do I return a proper success/error message for JQuery .ajax() using PHP?

Server side:

if (mysql_query($query)) {
    // ...
}
else {
    ajaxError(); 
}

Client side:

error: function() {
    alert("There was an error. Try again please!");
},
success: function(){
    alert("Thank you for subscribing!");
}

lvalue required as left operand of assignment error when using C++

if you use an assignment operator but use it in wrong way or in wrong place, then you'll get this types of errors!

suppose if you type:
p+1=p; you will get the error!!

you will get the same error for this:
if(ch>='a' && ch='z')
as you see can see that I i tried to assign in if() statement!!!
how silly I am!!! right??
ha ha
actually i forgot to give less then(<) sign
if(ch>='a' && ch<='z')
and got the error!!

What is the difference between connection and read timeout for sockets?

These are timeout values enforced by JVM for TCP connection establishment and waiting on reading data from socket.

If the value is set to infinity, you will not wait forever. It simply means JVM doesn't have timeout and OS will be responsible for all the timeouts. However, the timeouts on OS may be really long. On some slow network, I've seen timeouts as long as 6 minutes.

Even if you set the timeout value for socket, it may not work if the timeout happens in the native code. We can reproduce the problem on Linux by connecting to a host blocked by firewall or unplugging the cable on switch.

The only safe approach to handle TCP timeout is to run the connection code in a different thread and interrupt the thread when it takes too long.

build maven project with propriatery libraries included

I think that the "right" solution here is to add your proprietary libraries to your own repository. It should be simple: create pom for your library project and publish the compiled version on your repository. Add this repository to the list of repositories for your mail project and run build. I believe it will work for you.

How do I set the classpath in NetBeans?

Maven

The Answer by Bhesh Gurung is correct… unless your NetBeans project is Maven based.

Dependency

Under Maven, you add a "dependency". A dependency is a description of a library (its name & version number) you want to use from your code.

Or a dependency could be a description of a library which another library needs ("depends on"). Maven automatically handles this chain, libraries that need other libraries that then need other libraries and so on. For the mathematical-minded, perhaps the phrase "Maven resolves the transitive dependencies" makes sense.

Repository

Maven gets this related-ness information, and the libraries themselves from a Maven repository. A repository is basically an online database and collection of download files (the dependency library).

Easy to Use

Adding a dependency to a Maven-based project is really quite easy. That is the whole point to Maven, to make managing dependent libraries easy and to make building them into your project easy. To get started with adding a dependency, see this Question, Adding dependencies in Maven Netbeans and my Answer with screenshot.

enter image description here

How can I concatenate a string within a loop in JSTL/JSP?

Is JSTL's join(), what you searched for?

<c:set var="myVar" value="${fn:join(myParams.items, ' ')}" />

Convert float64 column to int64 in Pandas

Solution for pandas 0.24+ for converting numeric with missing values:

df = pd.DataFrame({'column name':[7500000.0,7500000.0, np.nan]})
print (df['column name'])
0    7500000.0
1    7500000.0
2          NaN
Name: column name, dtype: float64

df['column name'] = df['column name'].astype(np.int64)

ValueError: Cannot convert non-finite values (NA or inf) to integer

#http://pandas.pydata.org/pandas-docs/stable/user_guide/integer_na.html
df['column name'] = df['column name'].astype('Int64')
print (df['column name'])
0    7500000
1    7500000
2        NaN
Name: column name, dtype: Int64

I think you need cast to numpy.int64:

df['column name'].astype(np.int64)

Sample:

df = pd.DataFrame({'column name':[7500000.0,7500000.0]})
print (df['column name'])
0    7500000.0
1    7500000.0
Name: column name, dtype: float64

df['column name'] = df['column name'].astype(np.int64)
#same as
#df['column name'] = df['column name'].astype(pd.np.int64)
print (df['column name'])
0    7500000
1    7500000
Name: column name, dtype: int64

If some NaNs in columns need replace them to some int (e.g. 0) by fillna, because type of NaN is float:

df = pd.DataFrame({'column name':[7500000.0,np.nan]})

df['column name'] = df['column name'].fillna(0).astype(np.int64)
print (df['column name'])
0    7500000
1          0
Name: column name, dtype: int64

Also check documentation - missing data casting rules

EDIT:

Convert values with NaNs is buggy:

df = pd.DataFrame({'column name':[7500000.0,np.nan]})

df['column name'] = df['column name'].values.astype(np.int64)
print (df['column name'])
0                7500000
1   -9223372036854775808
Name: column name, dtype: int64

How can I get onclick event on webview in android?

WebViewClient.shouldOverrideUrlLoading might be helpful. We are having a similar requirement in one of our app. Not tried yet.

Is it possible to have a default parameter for a mysql stored procedure?

Unfortunately, MySQL doesn't support DEFAULT parameter values, so:

CREATE PROCEDURE `blah`
(
  myDefaultParam int DEFAULT 0
)
BEGIN
  -- Do something here
END

returns the error:

ERROR 1064 (42000): You have an error in your SQL syntax; check the manual
that corresponds to your MySQL server version for the right syntax to use 
near 'DEFAULT 0) BEGIN END' at line 3

To work around this limitation, simply create additional procedures that assign default values to the original procedure:

DELIMITER //

DROP PROCEDURE IF EXISTS blah//
DROP PROCEDURE IF EXISTS blah2//
DROP PROCEDURE IF EXISTS blah1//
DROP PROCEDURE IF EXISTS blah0//

CREATE PROCEDURE blah(param1 INT UNSIGNED, param2 INT UNSIGNED)
BEGIN
    SELECT param1, param2;
END;
//

CREATE PROCEDURE blah2(param1 INT UNSIGNED, param2 INT UNSIGNED)
BEGIN
    CALL blah(param1, param2);
END;
//

CREATE PROCEDURE blah1(param1 INT UNSIGNED)
BEGIN
    CALL blah2(param1, 3);
END;
//

CREATE PROCEDURE blah0()
BEGIN
    CALL blah1(4);
END;
//

Then, running this:

CALL blah(1, 1);
CALL blah2(2, 2);
CALL blah1(3);
CALL blah0();

will return:

+--------+--------+
| param1 | param2 |
+--------+--------+
|      1 |      1 |
+--------+--------+
1 row in set (0.00 sec)

Query OK, 0 rows affected (0.00 sec)

+--------+--------+
| param1 | param2 |
+--------+--------+
|      2 |      2 |
+--------+--------+
1 row in set (0.00 sec)

Query OK, 0 rows affected (0.00 sec)

+--------+--------+
| param1 | param2 |
+--------+--------+
|      3 |      3 |
+--------+--------+
1 row in set (0.00 sec)

Query OK, 0 rows affected (0.00 sec)

+--------+--------+
| param1 | param2 |
+--------+--------+
|      4 |      3 |
+--------+--------+
1 row in set (0.00 sec)

Query OK, 0 rows affected (0.00 sec)

Then, if you make sure to only use the blah2(), blah1() and blah0() procedures, your code will not need to be immediately updated, when you add a third parameter to the blah() procedure.

Is it possible to decrypt MD5 hashes?

No, you can not decrypt/reverse the md5 as it is a one-way hash function till you can not found a extensive vulnerabilities in the MD5. Another way is there are some website has a large amount of set of password database, so you can try online to decode your MD5 or SHA1 hash string. I tried a website like http://www.mycodemyway.com/encrypt-and-decrypt/md5 and its working fine for me but this totally depends on your hash if that hash is stored in that database then you can get the actual string.

@Html.DropDownListFor how to set default value

I hope this is helpful to you.

Please try this code,

 @Html.DropDownListFor(model => model.Items, new List<SelectListItem>
   { new SelectListItem{Text="Deactive", Value="False"},
     new SelectListItem{Text="Active", Value="True",  Selected = true},
     })

iOS - Calling App Delegate method from ViewController

Just Follow these steps

1.import your app delegate in your class where you want app delegate object.

#import "YourAppDelegate.h"

2.inside your class create an instance of your app delegate object(Its basically a singleton).

YourAppDelegate *appDelegate=( YourAppDelegate* )[UIApplication sharedApplication].delegate;

3.Now invoke method using selector

if([appDelegate respondsToSelector:@selector(yourMethod)]){

        [appDelegate yourMethod];
    }

or directly by

[appDelegate yourMethod];

for swift

let appdel : AppDelegate = UIApplication.shared.delegate as! AppDelegate

i will recommend the first one. Run and Go.

How to get CPU temperature?

I extracted the CPU part from Open Hardware Monitor into a separated library, exposing sensors and members normally hidden into OHM. It also includes many updates (like the support for Ryzen and Xeon) because on OHM they don't accept pull requests since 2015.

https://www.nuget.org/packages/HardwareProviders.CPU.Standard/

Let know your opinion :)

What is the proper way to re-attach detached objects in Hibernate?

In the original post, there are two methods, update(obj) and merge(obj) that are mentioned to work, but in opposite circumstances. If this is really true, then why not test to see if the object is already in the session first, and then call update(obj) if it is, otherwise call merge(obj).

The test for existence in the session is session.contains(obj). Therefore, I would think the following pseudo-code would work:

if (session.contains(obj))
{
    session.update(obj);
}
else 
{
    session.merge(obj);
}

What does string::npos mean in this code?

npos is just a token value that tells you that find() did not find anything (probably -1 or something like that). find() checks for the first occurence of the parameter, and returns the index at which the parameter begins. For Example,

  string name = "asad.txt";
  int i = name.find(".txt");
  //i holds the value 4 now, that's the index at which ".txt" starts
  if (i==string::npos) //if ".txt" was NOT found - in this case it was, so  this condition is false
    name.append(".txt");

How do you do relative time in Rails?

I've written this, but have to check the existing methods mentioned to see if they are better.

module PrettyDate
  def to_pretty
    a = (Time.now-self).to_i

    case a
      when 0 then 'just now'
      when 1 then 'a second ago'
      when 2..59 then a.to_s+' seconds ago' 
      when 60..119 then 'a minute ago' #120 = 2 minutes
      when 120..3540 then (a/60).to_i.to_s+' minutes ago'
      when 3541..7100 then 'an hour ago' # 3600 = 1 hour
      when 7101..82800 then ((a+99)/3600).to_i.to_s+' hours ago' 
      when 82801..172000 then 'a day ago' # 86400 = 1 day
      when 172001..518400 then ((a+800)/(60*60*24)).to_i.to_s+' days ago'
      when 518400..1036800 then 'a week ago'
      else ((a+180000)/(60*60*24*7)).to_i.to_s+' weeks ago'
    end
  end
end

Time.send :include, PrettyDate

Convert String to java.util.Date

You should set a TimeZone in your DateFormat, otherwise it will use the default one (depending on the settings of the computer).

What would be the best method to code heading/title for <ul> or <ol>, Like we have <caption> in <table>?

how about making the heading a list-element with different styles like so

<ul>
 <li class="heading">heading</li>
 <li>list item</li>
 <li>list item</li>
 <li>list item</li>
 <li>list item</li>
</ul>

and the CSS

ul .heading {font-weight: normal; list-style: none;}

additionally, use a reset CSS to set margins and paddings right on the ul and li. here's a good reset CSS. once you've reset the margins and paddings, you can apply some margin on the list-elements other than the one's with the heading class, to indent them.

mysql datetime comparison

But this is obviously performing a 'string' comparison

No. The string will be automatically cast into a DATETIME value.

See 11.2. Type Conversion in Expression Evaluation.

When an operator is used with operands of different types, type conversion occurs to make the operands compatible. Some conversions occur implicitly. For example, MySQL automatically converts numbers to strings as necessary, and vice versa.

Check if page gets reloaded or refreshed in JavaScript

if

event.currentTarget.performance.navigation.type

returns

0 => user just typed in an Url
1 => page reloaded
2 => back button clicked.

Automatically capture output of last command into a variable using Bash?

I find remembering to pipe the output of my commands into a specific file to be a bit annoying, my solution is a function in my .bash_profile that catches the output in a file and returns the result when you need it.

The advantage with this one is that you don't have to rerun the whole command (when using find or other long-running commands that can be critical)

Simple enough, paste this in your .bash_profile:

Script

# catch stdin, pipe it to stdout and save to a file
catch () { cat - | tee /tmp/catch.out}
# print whatever output was saved to a file
res () { cat /tmp/catch.out }

Usage

$ find . -name 'filename' | catch
/path/to/filename

$ res
/path/to/filename

At this point, I tend to just add | catch to the end of all of my commands, because there's no cost to doing it and it saves me having to rerun commands that take a long time to finish.

Also, if you want to open the file output in a text editor you can do this:

# vim or whatever your favorite text editor is
$ vim <(res)

How do I set up Visual Studio Code to compile C++ code?

A makefile task example for new 2.0.0 tasks.json version.

In the snippet below some comments I hope they will be useful.

{
    "version": "2.0.0",
    "tasks": [
        {
            "label": "<TASK_NAME>",
            "type": "shell",
            "command": "make",
            // use options.cwd property if the Makefile is not in the project root ${workspaceRoot} dir
            "options": {
                "cwd": "${workspaceRoot}/<DIR_WITH_MAKEFILE>"
            },
            // start the build without prompting for task selection, use "group": "build" otherwise
            "group": {
                "kind": "build",
                "isDefault": true
            },
            "presentation": {
                "echo": true,
                "reveal": "always",
                "focus": false,
                "panel": "shared"
            },
            // arg passing example: in this case is executed make QUIET=0
            "args": ["QUIET=0"],
            // Use the standard less compilation problem matcher.
            "problemMatcher": {
                "owner": "cpp",
                "fileLocation": ["absolute"],
                "pattern": {
                    "regexp": "^(.*):(\\d+):(\\d+):\\s+(warning|error):\\s+(.*)$",
                    "file": 1,
                    "line": 2,
                    "column": 3,
                    "severity": 4,
                    "message": 5
                }
            }
        }
    ]
}

libstdc++-6.dll not found

This error also occurred when I compiled with MinGW using gcc with the following options: -lstdc++ -lm, rather than g++

I did not notice these options, and added: -static-libgcc -static-libstdc++

I still got the error, and finally realized I was using gcc, and changed the compiler to g++ and removed -stdc++ and -lm, and everything linked fine.

(I was using LINK.c rather than LINK.cpp... use make -pn | less to see what everything does!)

I don't know why the previous author was using gcc with -stdc++. I don't see any reason not to use g++ which will link with stdc++ automatically... and as far as I know, provide other benefits (it is the c++ compiler after all).

Converting ArrayList to HashMap

Using a supposed name property as the map key:

for (Product p: productList) { s.put(p.getName(), p); }

Linking to an external URL in Javadoc?

Hard to find a clear answer from the Oracle site. The following is from javax.ws.rs.core.HttpHeaders.java:

/**
 * See {@link <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.1">HTTP/1.1 documentation</a>}.
 */
public static final String ACCEPT = "Accept";

/**
 * See {@link <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.2">HTTP/1.1 documentation</a>}.
 */
public static final String ACCEPT_CHARSET = "Accept-Charset";

Get today date in google appScript

Utilities.formatDate(new Date(), "GMT+1", "dd/MM/yyyy")

You can change the format by doing swapping the values.

  • dd = day(31)
  • MM = Month(12) - Case sensitive
  • yyyy = Year(2017)
function changeDate() {
    var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(GA_CONFIG);
    // You could use now Date(); on its own but it will not look nice.
    var date = Utilities.formatDate(new Date(), "GMT+1", "dd/MM/yyyy")
    var endDate = date
}

Trim Whitespaces (New Line and Tab space) in a String in Oracle

Below code can be used to Remove New Line and Table Space in text column

Select replace(replace(TEXT,char(10),''),char(13),'')

How to concatenate two layers in keras?

You're getting the error because result defined as Sequential() is just a container for the model and you have not defined an input for it.

Given what you're trying to build set result to take the third input x3.

first = Sequential()
first.add(Dense(1, input_shape=(2,), activation='sigmoid'))

second = Sequential()
second.add(Dense(1, input_shape=(1,), activation='sigmoid'))

third = Sequential()
# of course you must provide the input to result which will be your x3
third.add(Dense(1, input_shape=(1,), activation='sigmoid'))

# lets say you add a few more layers to first and second.
# concatenate them
merged = Concatenate([first, second])

# then concatenate the two outputs

result = Concatenate([merged,  third])

ada_grad = Adagrad(lr=0.1, epsilon=1e-08, decay=0.0)

result.compile(optimizer=ada_grad, loss='binary_crossentropy',
               metrics=['accuracy'])

However, my preferred way of building a model that has this type of input structure would be to use the functional api.

Here is an implementation of your requirements to get you started:

from keras.models import Model
from keras.layers import Concatenate, Dense, LSTM, Input, concatenate
from keras.optimizers import Adagrad

first_input = Input(shape=(2, ))
first_dense = Dense(1, )(first_input)

second_input = Input(shape=(2, ))
second_dense = Dense(1, )(second_input)

merge_one = concatenate([first_dense, second_dense])

third_input = Input(shape=(1, ))
merge_two = concatenate([merge_one, third_input])

model = Model(inputs=[first_input, second_input, third_input], outputs=merge_two)
ada_grad = Adagrad(lr=0.1, epsilon=1e-08, decay=0.0)
model.compile(optimizer=ada_grad, loss='binary_crossentropy',
               metrics=['accuracy'])

To answer the question in the comments:

  1. How are result and merged connected? Assuming you mean how are they concatenated.

Concatenation works like this:

  a        b         c
a b c   g h i    a b c g h i
d e f   j k l    d e f j k l

i.e rows are just joined.

  1. Now, x1 is input to first, x2 is input into second and x3 input into third.

Regex for Comma delimited list

I had a slightly different requirement, to parse an encoded dictionary/hashtable with escaped commas, like this:

"1=This is something, 2=This is something,,with an escaped comma, 3=This is something else"

I think this is an elegant solution, with a trick that avoids a lot of regex complexity:

if (string.IsNullOrEmpty(encodedValues))
{
    return null;
}
else
{
    var retVal = new Dictionary<int, string>();
    var reFields = new Regex(@"([0-9]+)\=(([A-Za-z0-9\s]|(,,))+),");
    foreach (Match match in reFields.Matches(encodedValues + ","))
    {
        var id = match.Groups[1].Value;
        var value = match.Groups[2].Value;
        retVal[int.Parse(id)] = value.Replace(",,", ",");
    }
    return retVal;
}

I think it can be adapted to the original question with an expression like @"([0-9]+),\s?" and parse on Groups[0].

I hope it's helpful to somebody and thanks for the tips on getting it close to there, especially Asaph!

Failed to create provisioning profile

After some time with the same disturbing error and after I write a unique Bundle Identifier and it didn't help, I searched the web and found here that my error was that I selected a virtual device and not an real device. The solution was:

1.I plugged my iPhone

2.I clicked on the button - set the active scheme. and there it was on the top - device iPhone. the error has gone.

enter image description here

What is the theoretical maximum number of open TCP connections that a modern Linux box can have

If you used a raw socket (SOCK_RAW) and re-implemented TCP in userland, I think the answer is limited in this case only by the number of (local address, source port, destination address, destination port) tuples (~2^64 per local address).

It would of course take a lot of memory to keep the state of all those connections, and I think you would have to set up some iptables rules to keep the kernel TCP stack from getting upset &/or responding on your behalf.

How can I get a precise time, for example in milliseconds in Objective-C?

NSDate and the timeIntervalSince* methods will return a NSTimeInterval which is a double with sub-millisecond accuracy. NSTimeInterval is in seconds, but it uses the double to give you greater precision.

In order to calculate millisecond time accuracy, you can do:

// Get a current time for where you want to start measuring from
NSDate *date = [NSDate date];

// do work...

// Find elapsed time and convert to milliseconds
// Use (-) modifier to conversion since receiver is earlier than now
double timePassed_ms = [date timeIntervalSinceNow] * -1000.0;

Documentation on timeIntervalSinceNow.

There are many other ways to calculate this interval using NSDate, and I would recommend looking at the class documentation for NSDate which is found in NSDate Class Reference.

How to fill in proxy information in cntlm config file?

For me just using cntlm -H wasn't generating the right hash, but it does with the command below providing the user name.

If you need to generate a new password hash for cntlm, because you have change it or you've been forced to update it, you can just type the below command and update your cntlm.conf configuration file with the output:

$ cntlm -u test -H
Password: 
PassLM          D2AABAF8828482D5552C4BCA4AEBFB11
PassNT          83AC305A1582F064C469755F04AE5C0A
PassNTLMv2      4B80D9370D353EE006D714E39715A5CB    # Only for user 'test', domain ''

Multiple ping script in Python

To ping several hosts at once you could use subprocess.Popen():

#!/usr/bin/env python3
import os
import time
from subprocess import Popen, DEVNULL

p = {} # ip -> process
for n in range(1, 100): # start ping processes
    ip = "127.0.0.%d" % n
    p[ip] = Popen(['ping', '-n', '-w5', '-c3', ip], stdout=DEVNULL)
    #NOTE: you could set stderr=subprocess.STDOUT to ignore stderr also

while p:
    for ip, proc in p.items():
        if proc.poll() is not None: # ping finished
            del p[ip] # remove from the process list
            if proc.returncode == 0:
                print('%s active' % ip)
            elif proc.returncode == 1:
                print('%s no response' % ip)
            else:
                print('%s error' % ip)
            break

If you can run as a root you could use a pure Python ping script or scapy:

from scapy.all import sr, ICMP, IP, L3RawSocket, conf

conf.L3socket = L3RawSocket # for loopback interface
ans, unans = sr(IP(dst="127.0.0.1-99")/ICMP(), verbose=0) # make requests
ans.summary(lambda (s,r): r.sprintf("%IP.src% is alive"))

Angular 2 'component' is not a known element

I was facing the same issue. In my case I have forgotten to declare Parent component in the app.module.ts

As a example if you are using <app-datapicker> selector in ToDayComponent template, you should declare both ToDayComponent and DatepickerComponent in the app.module.ts

Make selected block of text uppercase

Without defining keyboard shortcuts

  1. Select the text you want capitalized

  2. Open View->Command Palette (or Shift+Command+P)

  3. Start typing "Transform to uppercase" and select that option

  4. Voila!

How to use WHERE IN with Doctrine 2

I found that, despite what the docs indicate, the only way to get this to work is like this:

$ids = array(...); // Array of your values
$qb->add('where', $qb->expr()->in('r.winner', $ids));

http://groups.google.com/group/doctrine-dev/browse_thread/thread/fbf70837293676fb

Laravel - display a PDF file in storage without forcing download?

Retrieving Files
$contents = Storage::get('file.jpg');

Downloading Files
return Storage::download('file.jpg');

File URLs
$url = Storage::url('file.jpg');

How to unbind a listener that is calling event.preventDefault() (using jQuery)?

If the element only has one handler, then simply use jQuery unbind.

$("#element").unbind();

How to check if a scope variable is undefined in AngularJS template?

If foo is not a boolean variable then this would work (i.e. you want to show this when that variable has some data):

<p ng-show="!foo">Show this if $scope.foo is undefined</p>

And vise-versa:

<p ng-show="foo">Show this if $scope.foo is defined</p>

When should null values of Boolean be used?

There are many uses for the **null** value in the Boolean wrapper! :)

For example, you may have in a form a field named "newsletter" that indicate if the user want or doesn't want a newsletter from your site. If the user doesn't select a value in this field, you may want to implement a default behaviour to that situation (send? don't send?, question again?, etc) . Clearly, not set (or not selected or **null**), is not the same that true or false.

But, if "not set" doesn't apply to your model, don't change the boolean primitive ;)

Why does Java have transient fields?

As per google transient meaning == lasting only for a short time; impermanent.

Now if you want to make anything transient in java use transient keyword.

Q: where to use transient?

A: Generally in java we can save data to files by acquiring them in variables and writing those variables to files, this process is known as Serialization. Now if we want to avoid variable data to be written to file, we would make that variable as transient.

transient int result=10;

Note: transient variables cannot be local.

Get the time of a datetime using T-SQL?

In case of SQL Server, this should work

SELECT CONVERT(VARCHAR(8),GETDATE(),108) AS HourMinuteSecond

How to run Pip commands from CMD

Little side note for anyone new to Python who didn't figure it out by theirself: this should be automatic when installing Python, but just in case, note that to run Python using the python command in Windows' CMD you must first add it to the PATH environment variable, as explained here.


To execute Pip, first of all make sure you have it installed, so type in your CMD:

> python
>>> import pip
>>>

And it should proceed with no error. Otherwise, if this fails, you can look here to see how to install it. Now that you are sure you've got Pip, you can run it from CMD with Python using the -m (module) parameter, like this:

> python -m pip <command> <args>

Where <command> is any Pip command you want to run, and <args> are its relative arguments, separated by spaces.

For example, to install a package:

> python -m pip install <package-name>

How do I get which JRadioButton is selected from a ButtonGroup

You could use getSelectedObjects() of ItemSelectable (superinterface of ButtonModel) which returns the list of selected items. In case of a radio button group it can only be one or none at all.

Finding index of character in Swift String

Swift 5

Find index of substring

let str = "abcdecd"
if let range: Range<String.Index> = str.range(of: "cd") {
    let index: Int = str.distance(from: str.startIndex, to: range.lowerBound)
    print("index: ", index) //index: 2
}
else {
    print("substring not found")
}

Find index of Character

let str = "abcdecd"
if let firstIndex = str.firstIndex(of: "c") {
    let index: Int = str.distance(from: str.startIndex, to: firstIndex)
    print("index: ", index)   //index: 2
}
else {
    print("symbol not found")
}

How to find the logs on android studio?

Hope this helps someone: on Mac OS X, the logs are within /Users/<user>/Library/Logs/AndroidStudio<version>/

How to convert color code into media.brush?

For simplicity you could create an extension:-

    public static SolidColorBrush ToSolidColorBrush(this string hex_code)
    {
        return (SolidColorBrush)new BrushConverter().ConvertFromString(hex_code);
    }

And then to use:-

 SolidColorBrush accentBlue = "#3CACDC".ToSolidColorBrush();

Comments in Markdown

Also see Critic Markup, supported by an increasing number of Markdown tools.

http://criticmarkup.com/

Comment {>> <<}

Lorem ipsum dolor sit amet.{>>This is a comment<<}

Highlight+Comment {== ==}{>> <<}

Lorem ipsum dolor sit amet, consectetur adipiscing elit. {==Vestibulum at orci magna. Phasellus augue justo, sodales eu pulvinar ac, vulputate eget nulla.==}{>>confusing<<} Mauris massa sem, tempor sed cursus et, semper tincidunt lacus.

Python NLTK: SyntaxError: Non-ASCII character '\xc3' in file (Sentiment Analysis -NLP)

Add the following to the top of your file # coding=utf-8

If you go to the link in the error you can seen the reason why:

Defining the Encoding

Python will default to ASCII as standard encoding if no other encoding hints are given. To define a source code encoding, a magic comment must be placed into the source files either as first or second line in the file, such as: # coding=

Where to download visual studio express 2005?

Small tip for you. Microsoft frequently has 'launch parties' or 'launch events' in which they frequently distribute licensed, not for resale copies, of that product. I've gotten the last two versions of VS (2005 and 2008) by attending my local .NET user group chapter during those days.

Truncate with condition

As a response to your question: "i want to reset all the data and keep last 30 days inside the table."

you can create an event. Check https://dev.mysql.com/doc/refman/5.7/en/event-scheduler.html

For example:

CREATE EVENT DeleteExpiredLog
ON SCHEDULE EVERY 1 DAY
DO
DELETE FROM log WHERE date < DATE_SUB(NOW(), INTERVAL 30 DAY);

Will run a daily cleanup in your table, keeping the last 30 days data available

Display a angular variable in my html page

In your template, you have access to all the variables that are members of the current $scope. So, tobedone should be $scope.tobedone, and then you can display it with {{tobedone}}, or [[tobedone]] in your case.

Best way to convert an ArrayList to a string

An elegant way to deal with trailing separation characters is to use Class Separator

StringBuilder buf = new StringBuilder();
Separator sep = new Separator("\t");
for (String each: list) buf.append(sep).append(each);
String s = buf.toString();

The toString method of Class Separator returns the separater, except for the first call. Thus we print the list without trailing (or in this case) leading separators.

Auto populate columns in one sheet from another sheet

Below code will look for last used row in sheet1 and copy the entire range from A1 upto last used row in column A to Sheet2 at exact same location.

Sub test()

    Dim lastRow As Long
    lastRow = Sheets("Sheet1").Range("A" & Rows.Count).End(xlUp).Row
    Sheets("Sheet2").Range("A1:A" & lastRow).Value = Sheets("Sheet1").Range("A1:A" & lastRow).Value

End Sub

Place cursor at the end of text in EditText

This works

Editable etext = edittext.getText();
Selection.setSelection(etext,edittext.getText().toString().length());

Why does AngularJS include an empty option in select?

Maybe useful for someone:

If you want to use plain options instead of ng-options, you could do like below:

<select ng-model="sortorder" ng-init="sortorder='publish_date'">
  <option value="publish_date">Ascending</option>
  <option value="-publish_date">Descending</option>
</select>

Set the model inline. Use ng-init to get rid of empty option

Use of "this" keyword in C++

It's programmer preference. Personally, I love using this since it explicitly marks the object members. Of course the _ does the same thing (only when you follow the convention)

How do I mock a service that returns promise in AngularJS Jasmine unit test?

The code snippet:

spyOn(myOtherService, "makeRemoteCallReturningPromise").and.callFake(function() {
    var deferred = $q.defer();
    deferred.resolve('Remote call result');
    return deferred.promise;
});

Can be written in a more concise form:

spyOn(myOtherService, "makeRemoteCallReturningPromise").and.returnValue(function() {
    return $q.resolve('Remote call result');
});

Start service in Android

Intent serviceIntent = new Intent(this,YourActivity.class);

startService(serviceIntent);

add service in manifist

<service android:enabled="true" android:name="YourActivity.class" />

for running service on oreo and greater devices use for ground service and show notification to user

or use geofencing service for location update in background reference http://stackoverflow.com/questions/tagged/google-play-services

Autocompletion of @author in Intellij

For Intellij IDEA Community 2019.1 you will need to follow these steps :

File -> New -> Edit File Templates.. -> Class -> /* Created by ${USER} on ${DATE} */

How to SUM two fields within an SQL query

The sum function only gets the total of a column. In order to sum two values from different columns, convert the values to int and add them up using the +-Operator

Select (convert(int, col1)+convert(int, col2)) as summed from tbl1

Hope that helps.

C#: calling a button event handler method without actually clicking the button

Inside first button event call second button(imagebutton) event:

imagebutton_Click((ImageButton)this.divXXX.FindControl("imagbutton"), EventArgs.Empty);

you can use the button state such as the imagebutton's commandArgument if you save something into it.

Plotting multiple lines, in different colors, with pandas dataframe

Another simple way is to use the pivot function to format the data as you need first.

df.plot() does the rest

df = pd.DataFrame([
    ['red', 0, 0],
    ['red', 1, 1],
    ['red', 2, 2],
    ['red', 3, 3],
    ['red', 4, 4],
    ['red', 5, 5],
    ['red', 6, 6],
    ['red', 7, 7],
    ['red', 8, 8],
    ['red', 9, 9],
    ['blue', 0, 0],
    ['blue', 1, 1],
    ['blue', 2, 4],
    ['blue', 3, 9],
    ['blue', 4, 16],
    ['blue', 5, 25],
    ['blue', 6, 36],
    ['blue', 7, 49],
    ['blue', 8, 64],
    ['blue', 9, 81],
], columns=['color', 'x', 'y'])

df = df.pivot(index='x', columns='color', values='y')

df.plot()

result

pivot effectively turns the data into:

enter image description here

Scrolling an iframe with JavaScript?

Based on Chris's comment

CSS
.amazon-rating {
  width: 55px;
  height: 12px;
  overflow: hidden;
}

.rating-stars {
  left: -18px;
  top: -102px;
  position: relative;
}
HAML
.amazon-rating
  %iframe.rating-stars{src: $item->ratingURL, seamless: 'seamless', frameborder: 0, scrolling: 'no'}

get current url in twig template?

{{ path(app.request.attributes.get('_route'),
     app.request.attributes.get('_route_params')) }}

If you want to read it into a view variable:

{% set currentPath = path(app.request.attributes.get('_route'),
                       app.request.attributes.get('_route_params')) %}

The app global view variable contains all sorts of useful shortcuts, such as app.session and app.security.token.user, that reference the services you might use in a controller.

Best way to create enum of strings?

You can use that for string Enum

public enum EnumTest {
    NAME_ONE("Name 1"),
    NAME_TWO("Name 2");

    private final String name;

    /**
     * @param name
     */
    private EnumTest(final String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }
}

And call from main method

public class Test {
    public static void main (String args[]){
        System.out.println(EnumTest.NAME_ONE.getName());
        System.out.println(EnumTest.NAME_TWO.getName());
    }
}

What is difference between mutable and immutable String in java

I modified the code of william with a output comments for better understandable

   static void changeStr(String in) { 
      in = in+" changed";
      System.out.println("fun:"+in); //value changed 
    }
    static void changeStrBuf(StringBuffer in) {
      in.append(" changed");   //value changed
    }

    public static void main(String[] args) {
       StringBuffer sb = new StringBuffer("value");
       String str = "value";
       changeStrBuf(sb);
       changeStr(str);
       System.out.println("StringBuffer: "+sb); //value changed
       System.out.println("String: "+str);       // value 
    }

In above code , look at the value of str in both main() and changeStr() , even though u r changing the value of str in changeStr() it is affecting only to that function but in the main function the value is not changed , but it not in the case of StringBuffer..

In StringBuffer changed value is affected as a global..

hence String is immutable and StringBuffer is mutable...

In Simple , whatever u changed to String Object will affecting only to that function By going to String Pool. but not Changed...

AttributeError: 'list' object has no attribute 'encode'

You need to unicode each element of the list individually

[x.encode('utf-8') for x in tmp]

How to grep, excluding some patterns?

Question: search for 'loom' excluding 'gloom'.
Answer:

grep -w 'loom' ~/projects/**/trunk/src/**/*.@(h|cpp)

Twitter bootstrap scrollable table

Table elements don't appear to support this directly. Place the table in a div and set the height of the div and set overflow: auto.

How do I format date value as yyyy-mm-dd using SSIS expression builder?

Correct expression is

"source " + (DT_STR,4,1252)DATEPART( "yyyy" , getdate() ) + "-" +
RIGHT("0" + (DT_STR,4,1252)DATEPART( "mm" , getdate() ), 2) + "-" +
RIGHT("0" + (DT_STR,4,1252)DATEPART( "dd" , getdate() ), 2) +".CSV"

Select <a> which href ends with some string

Just in case you don't want to import a big library like jQuery to accomplish something this trivial, you can use the built-in method querySelectorAll instead. Almost all selector strings used for jQuery work with DOM methods as well:

const anchors = document.querySelectorAll('a[href$="ABC"]');

Or, if you know that there's only one matching element:

const anchor = document.querySelector('a[href$="ABC"]');

You may generally omit the quotes around the attribute value if the value you're searching for is alphanumeric, eg, here, you could also use

a[href$=ABC]

but quotes are more flexible and generally more reliable.

When to use throws in a Java method declaration?

The code that you looked at is not ideal. You should either:

  1. Catch the exception and handle it; in which case the throws is unnecesary.

  2. Remove the try/catch; in which case the Exception will be handled by a calling method.

  3. Catch the exception, possibly perform some action and then rethrow the exception (not just the message)

Setting timezone in Python

Be aware that running

import os
os.system("tzutil /s \"Central Standard Time\"");

will alter Windows system time, NOT just the local python environment time (so is definitley NOT the same as:

>>> os.environ['TZ'] = 'Europe/London'
>>> time.tzset()

which will only set in the current environment time (in Unix only)

Get Time from Getdate()

To get the format you want:

SELECT (substring(CONVERT(VARCHAR,GETDATE(),22),10,8) + ' ' + SUBSTRING(CONVERT(VARCHAR,getdate(),22), 19,2))

Why are you pulling this from sql?

DBNull if statement

The idiomatic way is to say:

if(rsData["usr.ursrdaystime"] != DBNull.Value) {
    strLevel = rsData["usr.ursrdaystime"].ToString();
}

This:

rsData = objCmd.ExecuteReader();
rsData.Read();

Makes it look like you're reading exactly one value. Use IDbCommand.ExecuteScalar instead.

Alter MySQL table to add comments on columns

Script for all fields on database:

SELECT 
table_name,
column_name,
CONCAT('ALTER TABLE `',
        TABLE_SCHEMA,
        '`.`',
        table_name,
        '` CHANGE `',
        column_name,
        '` `',
        column_name,
        '` ',
        column_type,
        ' ',
        IF(is_nullable = 'YES', '' , 'NOT NULL '),
        IF(column_default IS NOT NULL, concat('DEFAULT ', IF(column_default IN ('CURRENT_TIMESTAMP', 'CURRENT_TIMESTAMP()', 'NULL', 'b\'0\'', 'b\'1\''), column_default, CONCAT('\'',column_default,'\'') ), ' '), ''),
        IF(column_default IS NULL AND is_nullable = 'YES' AND column_key = '' AND column_type = 'timestamp','NULL ', ''),
        IF(column_default IS NULL AND is_nullable = 'YES' AND column_key = '','DEFAULT NULL ', ''),
        extra,
        ' COMMENT \'',
        column_comment,
        '\' ;') as script
FROM
    information_schema.columns
WHERE
    table_schema = 'my_database_name'
ORDER BY table_name , column_name
  1. Export all to a CSV
  2. Open it on your favorite csv editor

Note: You can improve to only one table if you prefer

The solution given by @Rufinus is great but if you have auto increments it will break it.

Delete all lines beginning with a # from a file

This answer builds upon the earlier answer by Keith.

egrep -v "^[[:blank:]]*#" should filter out comment lines.

egrep -v "^[[:blank:]]*(#|$)" should filter out both comments and empty lines, as is frequently useful.

For information about [:blank:] and other character classes, refer to https://en.wikipedia.org/wiki/Regular_expression#Character_classes.

How to query the permissions on an Oracle directory?

With Oracle 11g R2 (at least with 11.2.02) there is a view named datapump_dir_objs.

SELECT * FROM datapump_dir_objs;

The view shows the NAME of the directory object, the PATH as well as READ and WRITE permissions for the currently connected user. It does not show any directory objects which the current user has no permission to read from or write to, though.

How to add icon to mat-icon-button

The Material icons use the Material icon font, and the font needs to be included with the page.

Here's the CDN from Google Web Fonts:

<link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">

Do subclasses inherit private fields?

No. Private fields are not inherited... and that's why Protected was invented. It is by design. I guess this justified the existence of protected modifier.


Now coming to the contexts. What you mean by inherited -- if it is there in the object created from derived class? yes, it is.

If you mean can it be useful to derived class. Well, no.

Now, when you come to functional programming the private field of super class is not inherited in a meaningful way for the subclass. For the subclass, a private field of super class is same as a private field of any other class.

Functionally, it's not inherited. But ideally, it is.


OK, just looked into Java tutorial they quote this:

Private Members in a Superclass

A subclass does not inherit the private members of its parent class. However, if the superclass has public or protected methods for accessing its private fields, these can also be used by the subclass.

refer: http://download.oracle.com/javase/tutorial/java/IandI/subclasses.html

I agree, that the field is there. But, subclass does not get any privilege on that private field. To a subclass, the private field is same as any private field of any other class.

I believe it's purely matter of point-of-view. You may mould the argument either side. It's better justify both way.

 

Scripting SQL Server permissions

Expanding on the answer provided in https://stackoverflow.com/a/1987215/275388 which fails for database/schema wide rights and database user types you can use:

SELECT
  CASE
      WHEN dp.class_desc = 'OBJECT_OR_COLUMN' THEN
        dp.state_desc + ' ' + dp.permission_name collate latin1_general_cs_as + 
        ' ON ' + '[' + obj_sch.name + ']' + '.' + '[' + o.name + ']' +
        ' TO ' + '[' + dpr.name + ']'
      WHEN dp.class_desc = 'DATABASE' THEN
        dp.state_desc + ' ' + dp.permission_name collate latin1_general_cs_as + 
        ' TO ' + '[' + dpr.name + ']'
      WHEN dp.class_desc = 'SCHEMA' THEN
        dp.state_desc + ' ' + dp.permission_name collate latin1_general_cs_as + 
        ' ON SCHEMA :: ' + '[' + SCHEMA_NAME(dp.major_id) + ']' +
        ' TO ' + '[' + dpr.name + ']'
      WHEN dp.class_desc = 'TYPE' THEN
        dp.state_desc + ' ' + dp.permission_name collate Latin1_General_CS_AS + 
        ' ON TYPE :: [' + s_types.name + '].[' + t.name + ']'
            + ' TO [' + dpr.name + ']'
      WHEN dp.class_desc = 'CERTIFICATE' THEN 
        dp.state_desc + ' ' + dp.permission_name collate latin1_general_cs_as + 
        ' TO ' + '[' + dpr.name + ']' 
      WHEN dp.class_desc = 'SYMMETRIC_KEYS' THEN 
        dp.state_desc + ' ' + dp.permission_name collate latin1_general_cs_as + 
      ' TO ' + '[' + dpr.name + ']' 
      ELSE 
        'ERROR: Unhandled class_desc: ' + dp.class_desc
  END
 AS GRANT_STMT
FROM sys.database_permissions AS dp 
  JOIN sys.database_principals AS dpr ON dp.grantee_principal_id=dpr.principal_id
  LEFT JOIN sys.objects AS o ON dp.major_id=o.object_id
  LEFT JOIN sys.schemas AS obj_sch ON o.schema_id = obj_sch.schema_id
  LEFT JOIN sys.types AS t ON dp.major_id = t.user_type_id
  LEFT JOIN sys.schemas AS s_types ON t.schema_id = s_types.schema_id
WHERE 
dpr.name NOT IN ('public','guest') 
--  AND o.name IN ('My_Procedure')      -- Uncomment to filter to specific object(s)
--  AND (o.name NOT IN ('My_Procedure') or o.name is null)  -- Uncomment to filter out specific object(s), but include rows with no o.name (VIEW DEFINITION etc.)
--  AND dp.permission_name='EXECUTE'    -- Uncomment to filter to just the EXECUTEs
--  AND dpr.name LIKE '%user_name%'     -- Uncomment to filter to just matching users
ORDER BY dpr.name, dp.class_desc, dp.permission_name

link button property to open in new tab?

 <asp:LinkButton ID="LinkButton1" runat="server" target="_blank">LinkButton</asp:LinkButton>

Use target="_blank" because It creates anchor markup. the following HTML is generated for above code

<a id="ctl00_ContentPlaceHolder1_LinkButton1" target="_blank" href="javascript:__doPostBack('ctl00$ContentPlaceHolder1$LinkButton1','')">LinkButton</a>

What does \d+ mean in regular expression terms?

\d is a digit (a character in the range 0-9), and + means 1 or more times. So, \d+ is 1 or more digits.

This is about as simple as regular expressions get. You should try reading up on regular expressions a little bit more. Google has a lot of results for regular expression tutorial, for instance. Or you could try using a tool like the free Regex Coach that will let you enter a regular expression and sample text, then indicate what (if anything) matches the regex.

OS X cp command in Terminal - No such file or directory

Summary of solution:

directory is neither an existing file nor directory. As it turns out, the real name is directory.1 as revealed by ls -la $HOME/Desktop/.

The complete working command is

cp -R $HOME/directory.1/file.bundle /library/application\ support/directory/

with the -R parameter for recursive copy (compulsory for copying directories).

Python equivalent to 'hold on' in Matlab

Just call plt.show() at the end:

import numpy as np
import matplotlib.pyplot as plt

plt.axis([0,50,60,80])
for i in np.arange(1,5):
    z = 68 + 4 * np.random.randn(50)
    zm = np.cumsum(z) / range(1,len(z)+1)
    plt.plot(zm)    

n = np.arange(1,51)
su = 68 + 4 / np.sqrt(n)
sl = 68 - 4 / np.sqrt(n)

plt.plot(n,su,n,sl)

plt.show()

How do I compile jrxml to get jasper?

  1. Open your .jrxml file in iReport Designer.
  2. Open the Report Inspector (Window -> Report Inspector).
  3. Right-click your report name on the top of the inspector and then click "Compile Report".

You can also Preview your report so it's automatically compiled.

Read file from line 2 or skip header row

If you want to read multiple CSV files starting from line 2, this works like a charm

for files in csv_file_list:
        with open(files, 'r') as r: 
            next(r)                  #skip headers             
            rr = csv.reader(r)
            for row in rr:
                #do something

(this is part of Parfait's answer to a different question)

How can I count the number of children?

You don't need jQuery for this. You can use JavaScript's .childNodes.length.

Just make sure to subtract 1 if you don't want to include the default text node (which is empty by default). Thus, you'd use the following:

var count = elem.childNodes.length - 1;

How to find index of all occurrences of element in array?

You can use Polyfill

if (!Array.prototype.filterIndex) {
Array.prototype.filterIndex = function (func, thisArg) {

    'use strict';
    if (!((typeof func === 'Function' || typeof func === 'function') && this))
        throw new TypeError();

    let len = this.length >>> 0,
        res = new Array(len), // preallocate array
        t = this, c = 0, i = -1;

    let kValue;
    if (thisArg === undefined) {
        while (++i !== len) {
            // checks to see if the key was set
            if (i in this) {
                kValue = t[i]; // in case t is changed in callback
                if (func(t[i], i, t)) {
                    res[c++] = i;
                }
            }
        }
    }
    else {
        while (++i !== len) {
            // checks to see if the key was set
            if (i in this) {
                kValue = t[i];
                if (func.call(thisArg, t[i], i, t)) {
                    res[c++] = i;
                }
            }
        }
    }

    res.length = c; // shrink down array to proper size
    return res;
};

}

Use it like this:

[2,23,1,2,3,4,52,2].filterIndex(element => element === 2)

result: [0, 3, 7]

Delete specific line number(s) from a text file using sed?

I would like to propose a generalization with awk.

When the file is made by blocks of a fixed size and the lines to delete are repeated for each block, awk can work fine in such a way

awk '{nl=((NR-1)%2000)+1; if ( (nl<714) || ((nl>1025)&&(nl<1029)) ) print  $0}'
 OriginFile.dat > MyOutputCuttedFile.dat

In this example the size for the block is 2000 and I want to print the lines [1..713] and [1026..1029].

  • NR is the variable used by awk to store the current line number.
  • % gives the remainder (or modulus) of the division of two integers;
  • nl=((NR-1)%BLOCKSIZE)+1 Here we write in the variable nl the line number inside the current block. (see below)
  • || and && are the logical operator OR and AND.
  • print $0 writes the full line

Why ((NR-1)%BLOCKSIZE)+1:
(NR-1) We need a shift of one because 1%3=1, 2%3=2, but 3%3=0.
  +1   We add again 1 because we want to restore the desired order.

+-----+------+----------+------------+
| NR  | NR%3 | (NR-1)%3 | (NR-1)%3+1 |
+-----+------+----------+------------+
|  1  |  1   |    0     |     1      |
|  2  |  2   |    1     |     2      |
|  3  |  0   |    2     |     3      |
|  4  |  1   |    0     |     1      |
+-----+------+----------+------------+

Batch Renaming of Files in a Directory

Try: http://www.mattweber.org/2007/03/04/python-script-renamepy/

I like to have my music, movie, and picture files named a certain way. When I download files from the internet, they usually don’t follow my naming convention. I found myself manually renaming each file to fit my style. This got old realy fast, so I decided to write a program to do it for me.

This program can convert the filename to all lowercase, replace strings in the filename with whatever you want, and trim any number of characters from the front or back of the filename.

The program's source code is also available.

Jmeter - Run .jmx file through command line and get the summary report in a excel

To get the results in excel like file, you have one option to get it done with csv file. Use below commands with provided options.

jmeter -n -t /path-to-jmeter-test/file.jmx -l TestResults.csv
-n states Non GUI mode
-t states Test JMX File
-l state Log the results in provided file

Also you can pass any results related parameters dynamically in command line arguments using -Jprop.name=value which are already defined in jmeter.properties in bin folder.

When does Java's Thread.sleep throw InterruptedException?

A solid and easy way to handle it in single threaded code would be to catch it and retrow it in a RuntimeException, to avoid the need to declare it for every method.

Restart container within pod

Both pod and container are ephemeral, try to use the following command to stop the specific container and the k8s cluster will restart a new container.

kubectl exec -it [POD_NAME] -c [CONTAINER_NAME] -- /bin/sh -c "kill 1"

This will send a SIGTERM signal to process 1, which is the main process running in the container. All other processes will be children of process 1, and will be terminated after process 1 exits. See the kill manpage for other signals you can send.

Show hide divs on click in HTML and CSS without jQuery

I like Roko's answer, and added a few lines to it so that you get a triangle that points right when the element is hidden, and down when it is displayed:

.collapse { font-weight: bold; display: inline-block; }
.collapse + input:after { content: " \25b6"; display: inline-block; }
.collapse + input:checked:after { content: " \25bc"; display: inline-block; }
.collapse + input { display: inline-block; -webkit-appearance: none; -o-appearance:none; -moz-appearance:none;  }
.collapse + input + * { display: none; }
.collapse + input:checked + * { display: block; }

How do I set up HttpContent for my HttpClient PostAsync second parameter?

    public async Task<ActionResult> Index()
    {
        apiTable table = new apiTable();
        table.Name = "Asma Nadeem";
        table.Roll = "6655";

        string str = "";
        string str2 = "";

        HttpClient client = new HttpClient();

        string json = JsonConvert.SerializeObject(table);

        StringContent httpContent = new StringContent(json, System.Text.Encoding.UTF8, "application/json");

        var response = await client.PostAsync("http://YourSite.com/api/apiTables", httpContent);

        str = "" + response.Content + " : " + response.StatusCode;

        if (response.IsSuccessStatusCode)
        {       
            str2 = "Data Posted";
        }

        return View();
    }

docker : invalid reference format

Found that using docker-compose config reported what the problem was.

In my case, an override compose file with an entry that was overriding nothing.

How to hide the keyboard when I press return key in a UITextField?

Try this in Swift,

Step 1: Set delegate as self to your textField

textField.delegate = self

Step 2: Add this UITextFieldDelegate below your class declaration,

extension YourClassName: UITextFieldDelegate {
    func textFieldShouldReturn(textField: UITextField) -> Bool {
         textField.resignFirstResponder()
        return true
    }
}

What are the differences and similarities between ffmpeg, libav, and avconv?

Confusing messages

These messages are rather misleading and understandably a source of confusion. Older Ubuntu versions used Libav which is a fork of the FFmpeg project. FFmpeg returned in Ubuntu 15.04 "Vivid Vervet".

The fork was basically a non-amicable result of conflicting personalities and development styles within the FFmpeg community. It is worth noting that the maintainer for Debian/Ubuntu switched from FFmpeg to Libav on his own accord due to being involved with the Libav fork.

The real ffmpeg vs the fake one

For a while both Libav and FFmpeg separately developed their own version of ffmpeg.

Libav then renamed their bizarro ffmpeg to avconv to distance themselves from the FFmpeg project. During the transition period the "not developed anymore" message was displayed to tell users to start using avconv instead of their counterfeit version of ffmpeg. This confused users into thinking that FFmpeg (the project) is dead, which is not true. A bad choice of words, but I can't imagine Libav not expecting such a response by general users.

This message was removed upstream when the fake "ffmpeg" was finally removed from the Libav source, but, depending on your version, it can still show up in Ubuntu because the Libav source Ubuntu uses is from the ffmpeg-to-avconv transition period.

In June 2012, the message was re-worded for the package libav - 4:0.8.3-0ubuntu0.12.04.1. Unfortunately the new "deprecated" message has caused additional user confusion.

Starting with Ubuntu 15.04 "Vivid Vervet", FFmpeg's ffmpeg is back in the repositories again.

libav vs Libav

To further complicate matters, Libav chose a name that was historically used by FFmpeg to refer to its libraries (libavcodec, libavformat, etc). For example the libav-user mailing list, for questions and discussions about using the FFmpeg libraries, is unrelated to the Libav project.

How to tell the difference

If you are using avconv then you are using Libav. If you are using ffmpeg you could be using FFmpeg or Libav. Refer to the first line in the console output to tell the difference: the copyright notice will either mention FFmpeg or Libav.

Secondly, the version numbering schemes differ. Each of the FFmpeg or Libav libraries contains a version.h header which shows a version number. FFmpeg will end in three digits, such as 57.67.100, and Libav will end in one digit such as 57.67.0. You can also view the library version numbers by running ffmpeg or avconv and viewing the console output.

If you want to use the real ffmpeg

Ubuntu 15.04 "Vivid Vervet" or newer

The real ffmpeg is in the repository, so you can install it with:

apt-get install ffmpeg

For older Ubuntu versions

Your options are:

These methods are non-intrusive, reversible, and will not interfere with the system or any repository packages.

Another possible option is to upgrade to Ubuntu 15.04 "Vivid Vervet" or newer and just use ffmpeg from the repository.

Also see

For an interesting blog article on the situation, as well as a discussion about the main technical differences between the projects, see The FFmpeg/Libav situation.

FB OpenGraph og:image not pulling images (possibly https?)

I had similar problems. I removed the property="og:image:secure_url" and now it will scrub with just og:image. Sometimes, less is more

Import a module from a relative path

The quick-and-dirty way for Linux users

If you are just tinkering around and don't care about deployment issues, you can use a symbolic link (assuming your filesystem supports it) to make the module or package directly visible in the folder of the requesting module.

ln -s (path)/module_name.py

or

ln -s (path)/package_name

Note: A "module" is any file with a .py extension and a "package" is any folder that contains the file __init__.py (which can be an empty file). From a usage standpoint, modules and packages are identical -- both expose their contained "definitions and statements" as requested via the import command.

See: http://docs.python.org/2/tutorial/modules.html

Login failed for user 'IIS APPPOOL\ASP.NET v4.0'

I hate the ApplicationPoolIdentity. I always set a Windows User Account as the account on AppPools.

As adrift says, it does sound like a database security issue. So create an NT user account, assign it to the ASP.NET v4.0 AppPool and then grant it permission on the website folder and to the relevant table(s) in SQL.

No notification sound when sending notification from firebase in android

In the notification payload of the notification there is a sound key.

From the official documentation its use is:

Indicates a sound to play when the device receives a notification. Supports default or the filename of a sound resource bundled in the app. Sound files must reside in /res/raw/.

Eg:

{
    "to" : "bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1...",

    "notification" : {
      "body" : "great match!",
      "title" : "Portugal vs. Denmark",
      "icon" : "myicon",
      "sound" : "mySound"
    }
  }

If you want to use default sound of the device, you should use: "sound": "default".

See this link for all possible keys in the payloads: https://firebase.google.com/docs/cloud-messaging/http-server-ref#notification-payload-support

For those who don't know firebase handles notifications differently when the app is in background. In this case the onMessageReceived function is not called.

When your app is in the background, Android directs notification messages to the system tray. A user tap on the notification opens the app launcher by default. This includes messages that contain both notification and data payload. In these cases, the notification is delivered to the device's system tray, and the data payload is delivered in the extras of the intent of your launcher Activity.