Programs & Examples On #User defined literals

User-defined literals are a C++ language feature (new in C++11) that allow the user to define new kinds of literal modifiers that will construct objects based on the string of characters that the literal modifies.

How do I get java logging output to appear on a single line?

Similar to Tervor, But I like to change the property on runtime.

Note that this need to be set before the first SimpleFormatter is created - as was written in the comments.

    System.setProperty("java.util.logging.SimpleFormatter.format", 
            "%1$tF %1$tT %4$s %2$s %5$s%6$s%n");

How to parse an RSS feed using JavaScript?

If you are looking for a simple and free alternative to Google Feed API for your rss widget then rss2json.com could be a suitable solution for that.

You may try to see how it works on a sample code from the api documentation below:

_x000D_
_x000D_
google.load("feeds", "1");_x000D_
_x000D_
    function initialize() {_x000D_
      var feed = new google.feeds.Feed("https://news.ycombinator.com/rss");_x000D_
      feed.load(function(result) {_x000D_
        if (!result.error) {_x000D_
          var container = document.getElementById("feed");_x000D_
          for (var i = 0; i < result.feed.entries.length; i++) {_x000D_
            var entry = result.feed.entries[i];_x000D_
            var div = document.createElement("div");_x000D_
            div.appendChild(document.createTextNode(entry.title));_x000D_
            container.appendChild(div);_x000D_
          }_x000D_
        }_x000D_
      });_x000D_
    }_x000D_
    google.setOnLoadCallback(initialize);
_x000D_
<html>_x000D_
  <head>    _x000D_
     <script src="https://rss2json.com/gfapi.js"></script>_x000D_
  </head>_x000D_
  <body>_x000D_
    <p><b>Result from the API:</b></p>_x000D_
    <div id="feed"></div>_x000D_
  </body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

Why am I getting "void value not ignored as it ought to be"?

    int a = srand(time(NULL))
        arr[i] = a;

Should be

        arr[i] = rand();

And put srand(time(NULL)) somewhere at the very beginning of your program.

How to get values of selected items in CheckBoxList with foreach in ASP.NET C#?

I like to use this simple method to get the selected values and join them into a string

private string JoinCBLSelectedValues(CheckBoxList cbl, string separator = "")
{
    return string.Join(separator, cbl.Items.Cast<ListItem>().Where(li => li.Selected).ToList());
}

How to subtract a day from a date?

Subtract datetime.timedelta(days=1)

SpringApplication.run main method

Using:

@ComponentScan
@EnableAutoConfiguration
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);  

        //do your ReconTool stuff
    }
}

will work in all circumstances. Whether you want to launch the application from the IDE, or the build tool.

Using maven just use mvn spring-boot:run

while in gradle it would be gradle bootRun

An alternative to adding code under the run method, is to have a Spring Bean that implements CommandLineRunner. That would look like:

@Component
public class ReconTool implements CommandLineRunner {

    @Override
    public void run(String... args) throws Exception {
       //implement your business logic here
    }
}

Check out this guide from Spring's official guide repository.

The full Spring Boot documentation can be found here

What is the difference between char array and char pointer in C?

char p[3] = "hello" ? should be char p[6] = "hello" remember there is a '\0' char in the end of a "string" in C.

anyway, array in C is just a pointer to the first object of an adjust objects in the memory. the only different s are in semantics. while you can change the value of a pointer to point to a different location in the memory an array, after created, will always point to the same location.
also when using array the "new" and "delete" is automatically done for you.

font-family is inherit. How to find out the font-family in chrome developer pane?

Your browser's default font-family will be inherited for that case.

You can check the browser default font in chrome: Settings > Web content > Customize fonts...

enter image description here enter image description here

Regex match digits, comma and semicolon?

You are 90% of the way there.

^[0-9,;]+$

Starting with the carat ^ indicates a beginning of line.

The [ indicates a character set

The 0-9 indicates characters 0 through 9, the comma , indicates comma, and the semicolon indicates a ;.

The closing ] indicates the end of the character set.

The plus + indicates that one or more of the "previous item" must be present. In this case it means that you must have one or more of the characters in the previously declared character set.

The dollar $ indicates the end of the line.

Why is processing a sorted array faster than processing an unsorted array?

Besides the fact that the branch prediction may slow you down, a sorted array has another advantage:

You can have a stop condition instead of just checking the value, this way you only loop over the relevant data, and ignore the rest.
The branch prediction will miss only once.

 // sort backwards (higher values first), may be in some other part of the code
 std::sort(data, data + arraySize, std::greater<int>());

 for (unsigned c = 0; c < arraySize; ++c) {
       if (data[c] < 128) {
              break;
       }
       sum += data[c];               
 }

Find the index of a dict within a list, by matching the dict's value

def search(itemID,list):
     return[i for i in list if i.itemID==itemID]

How to append a char to a std::string?

int main()
{
  char d = 'd';
  std::string y("Hello worl");

  y += d;
  y.push_back(d);
  y.append(1, d); //appending the character 1 time
  y.insert(y.end(), 1, d); //appending the character 1 time
  y.resize(y.size()+1, d); //appending the character 1 time
  y += std::string(1, d); //appending the character 1 time
}

Note that in all of these examples you could have used a character literal directly: y += 'd';.

Your second example almost would have worked, for unrelated reasons. char d[1] = { 'd'}; didn't work, but char d[2] = { 'd'}; (note the array is size two) would have been worked roughly the same as const char* d = "d";, and a string literal can be appended: y.append(d);.

Best way to detect Mac OS X or Windows computers with JavaScript or jQuery

Let me know if this works. Way to detect an Apple device (Mac computers, iPhones, etc.) with help from StackOverflow.com:
What is the list of possible values for navigator.platform as of today?

var deviceDetect = navigator.platform;
var appleDevicesArr = ['MacIntel', 'MacPPC', 'Mac68K', 'Macintosh', 'iPhone', 
'iPod', 'iPad', 'iPhone Simulator', 'iPod Simulator', 'iPad Simulator', 'Pike 
v7.6 release 92', 'Pike v7.8 release 517'];

// If on Apple device
if(appleDevicesArr.includes(deviceDetect)) {
    // Execute code
}
// If NOT on Apple device
else {
    // Execute code
}

How to use the "required" attribute with a "radio" input field

You can use this code snippet ...

<html>
  <body>
     <form>
          <input type="radio" name="color" value="black" required />
          <input type="radio" name="color" value="white" />
          <input type="submit" value="Submit" />
    </form>
  </body>
</html>

Specify "required" keyword in one of the select statements. If you want to change the default way of its appearance. You can follow these steps. This is just for extra info if you have any intention to modify the default behavior.

Add the following into you .css file.

/* style all elements with a required attribute */
:required {
  background: red;
}

For more information you can refer following URL.

https://css-tricks.com/almanac/selectors/r/required/

Add URL link in CSS Background Image?

You can not add links from CSS, you will have to do so from the HTML code explicitly. For example, something like this:

<a href="whatever.html"><li id="header"></li></a>

How to Load RSA Private Key From File

You need to convert your private key to PKCS8 format using following command:

openssl pkcs8 -topk8 -inform PEM -outform DER -in private_key_file  -nocrypt > pkcs8_key

After this your java program can read it.

Thin Black Border for a Table

Style the td and th instead

td, th {
    border: 1px solid black;
}

And also to make it so there is no spacing between cells use:

table {
    border-collapse: collapse;
}

(also note, you have border-style: none; which should be border-style: solid;)

See an example here: http://jsfiddle.net/KbjNr/

Use ffmpeg to add text subtitles

I will provide a simple and general answer that works with any number of audios and srt subtitles and respects the metadata that may include the mkv container. So it will even add the images the matroska may include as attachments (though not another types AFAIK) and convert them to tracks; you will not be able to watch but they will be there (you can demux them). Ah, and if the mkv has chapters the mp4 too.

ffmpeg -i <mkv-input> -c copy -map 0 -c:s mov_text <mp4-output>

As you can see, it's all about the -map 0, that tells FFmpeg to add all the tracks, which includes metadata, chapters, attachments, etc. If there is an unrecognized "track" (mkv allows to attach any type of file), it will end with an error.

You can create a simple batch mkv2mp4.bat, if you usually do this, to create an mp4 with the same name as the mkv. It would be better with error control, a different output name, etc., but you get the point.

@ffmpeg -i %1 -c copy -map 0 -c:s mov_text "%~n1.mp4"

Now you can simply run

mkv2mp4 "Video with subtitles etc.mkv"

And it will create "Video with subtitles etc.mp4" with the maximum of information included.

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

You have more than one form tags with runat="server" on your template, most probably you have one in your master page, remove one on your aspx page, it is not needed if already have form in master page file which is surrounding your content place holders.

Try to remove that tag:

<form id="formID" runat="server">

and of course closing tag:

</form>

How can I use a batch file to write to a text file?

echo "blahblah"> txt.txt will erase the txt and put blahblah in it's place

echo "blahblah">> txt.txt will write blahblah on a new line in the txt

I think that both will create a new txt if none exists (I know that the first one does)

Where "txt.txt" is written above, a file path can be inserted if wanted. e.g. C:\Users\<username>\desktop, which will put it on their desktop.

Git - How to use .netrc file on Windows to save user and password

I am posting a way to use _netrc to download materials from the site www.course.com.

If someone is going to use the coursera-dl to download the open-class materials on www.coursera.com, and on the Windows OS someone wants to use a file like ".netrc" which is in like-Unix OS to add the option -n instead of -U <username> -P <password> for convenience. He/she can do it like this:

  1. Check the home path on Windows OS: setx HOME %USERPROFILE%(refer to VonC's answer). It will save the HOME environment variable as C:\Users\"username".

  2. Locate into the directory C:\Users\"username" and create a file name _netrc.NOTE: there is NOT any suffix. the content is like: machine coursera-dl login <user> password <pass>

  3. Use a command like coursera-dl -n --path PATH <course name> to download the class materials. More coursera-dl options details for this page.

When creating a service with sc.exe how to pass in context parameters?

I had issues getting this to work on Windows 7. It seemed to ignore the first argument I passed in so I used binPath= "C:\path\to\service.exe -bogusarg -realarg1 -realarg2" and it worked.

how to create inline style with :before and :after

If you really need it inline, for example because you are loading some user-defined colors dynamically, you can always add a <style> element right before your content.

<style>#project-slide-1:before { color: #ff0000; }</style>
<div id="project-slide-1" class="project-slide"> ... </div>

Example use case with PHP and some (wordpress inspired) dummy functions:

<style>#project-slide-<?php the_ID() ?>:before { color: <?php the_field('color') ?>; }</style>
<div id="project-slide-<?php the_ID() ?>" class="project-slide"> ... </div>

Since HTML 5.2 it is valid to place style elements inside the body, although it is still recommend to place style elements in the head.

Reference: https://www.w3.org/TR/html52/document-metadata.html#the-style-element

Storing integer values as constants in Enum manner in java

Well, you can't quite do it that way. PAGE.SIGN_CREATE will never return 1; it will return PAGE.SIGN_CREATE. That's the point of enumerated types.

However, if you're willing to add a few keystrokes, you can add fields to your enums, like this:


    public enum PAGE{
        SIGN_CREATE(0),
        SIGN_CREATE_BONUS(1),
        HOME_SCREEN(2),
        REGISTER_SCREEN(3);

        private final int value;

        PAGE(final int newValue) {
            value = newValue;
        }

        public int getValue() { return value; }
    }

And then you call PAGE.SIGN_CREATE.getValue() to get 0.

onclick event function in JavaScript

Two observations:

  1. You should write

    <input type="button" value="button text" />
    

    instead of

    <input type="button">button text</input>
    
  2. You should rename your function. The function click() is already defined on a button (it simulates a click), and gets a higher priority then your method.

Note that there are a couple of suggestions here that are plain wrong, and you shouldn't spend to much time on them:

  • Do not use onclick="javascript:myfunc()". Only use the javascript: prefix inside the href attribute of a hyperlink: <a href="javascript:myfunc()">.
  • You don't have to end with a semicolon. onclick="foo()" and onclick="foo();" both work just fine.
  • Event attributes in HTML are not case sensitive, so onclick, onClick and ONCLICK all work. It is common practice to write attributes in lowercase: onclick. note that javascript itself is case sensitive, so if you write document.getElementById("...").onclick = ..., then it must be all lowercase.

How can I check for NaN values?

for strings in panda take pd.isnull:

if not pd.isnull(atext):
  for word in nltk.word_tokenize(atext):

the function as feature extraction for NLTK

def act_features(atext):
features = {}
if not pd.isnull(atext):
  for word in nltk.word_tokenize(atext):
    if word not in default_stopwords:
      features['cont({})'.format(word.lower())]=True
return features

How can I execute PHP code from the command line?

If you're going to do PHP in the command line, I recommend you install phpsh, a decent PHP shell. It's a lot more fun.

Anyway, the php command offers two switches to execute code from the command line:

-r <code>        Run PHP <code> without using script tags <?..?>
-R <code>        Run PHP <code> for every input line

You can use php's -r switch as such:

php -r 'echo function_exists("foo") ? "yes" : "no";'

The above PHP command above should output no and returns 0 as you can see:

>>> php -r 'echo function_exists("foo") ? "yes" : "no";'
no
>>> echo $? # print the return value of the previous command
0

Another funny switch is php -a:

-a               Run as interactive shell

It's sort of lame compared to phpsh, but if you don't want to install the awesome interactive shell for PHP made by Facebook to get tab completion, history, and so on, then use -a as such:

>>> php -a
Interactive shell

php > echo function_exists("foo") ? "yes" : "no";
no
php >

If it doesn't work on your box like on my boxes (tested on Ubuntu and Arch Linux), then probably your PHP setup is fuzzy or broken. If you run this command:

php -i | grep 'API'

You should see:

Server API => Command Line Interface

If you don't, this means that maybe another command will provides the CLI SAPI. Try php-cli; maybe it's a package or a command available in your OS.

If you do see that your php command uses the CLI (command-line interface) SAPI (Server API), then run php -h | grep code to find out which crazy switch - as this hasn't changed for year- allows to run code in your version/setup.

Another couple of examples, just to make sure it works on my boxes:

>>> php -r 'echo function_exists("sg_load") ? "yes" : "no";'
no
>>> php -r 'echo function_exists("print_r") ? "yes" : "no";'
yes

Also, note that it is possible that an extension is loaded in the CLI and not in the CGI or Apache SAPI. It is likely that several PHP SAPIs use different php.ini files, e.g., /etc/php/cli/php.ini vs. /etc/php/cgi/php.ini vs. /etc/php/apache/php.ini on a Gentoo Linux box. Find out which ini file is used with php -i | grep ini.

How to list files and folder in a dir (PHP)

If you have problems with accessing to the path, maybe you need to put this:

$root = $_SERVER['DOCUMENT_ROOT'];
$path = "/cv/"; 

// Open the folder
 $dir_handle = @opendir($root . $path) or die("Unable to open $path");

Highcharts - how to have a chart with dynamic height?

I had the same problem and I fixed it with:

<div id="container" style="width: 100%; height: 100%; position:absolute"></div>

The chart fits perfect to the browser even if I resize it. You can change the percentage according to your needs.

Nullable type as a generic parameter possible?

Change the return type to Nullable<T>, and call the method with the non nullable parameter

static void Main(string[] args)
{
    int? i = GetValueOrNull<int>(null, string.Empty);
}


public static Nullable<T> GetValueOrNull<T>(DbDataRecord reader, string columnName) where T : struct
{
    object columnValue = reader[columnName];

    if (!(columnValue is DBNull))
        return (T)columnValue;

    return null;
}

How to get an ASP.NET MVC Ajax response to redirect to new page instead of inserting view into UpdateTargetId?

Using JavaScript will definitely do the job.

You can also use Content if this is more your style.

Example:

MVC Controller

[HttpPost]
public ActionResult AjaxMethod()
{
    return Content(@"http://www.google.co.uk");
}

Javascript

$.ajax({
    type: 'POST',
    url: '/AjaxMethod',
    success: function (redirect) {
        window.location = redirect;
    }
});

JavaScript property access: dot notation vs. brackets?

Be careful while using these notations: For eg. if we want to access a function present in the parent of a window. In IE :

window['parent']['func']

is not equivalent to

window.['parent.func']

We may either use:

window['parent']['func'] 

or

window.parent.func 

to access it

C# List<> Sort by x then y

For versions of .Net where you can use LINQ OrderBy and ThenBy (or ThenByDescending if needed):

using System.Linq;
....
List<SomeClass>() a;
List<SomeClass> b = a.OrderBy(x => x.x).ThenBy(x => x.y).ToList();

Note: for .Net 2.0 (or if you can't use LINQ) see Hans Passant answer to this question.

How to set python variables to true or false?

First to answer your question, you set a variable to true or false by assigning True or False to it:

myFirstVar = True
myOtherVar = False

If you have a condition that is basically like this though:

if <condition>:
    var = True
else:
    var = False

then it is much easier to simply assign the result of the condition directly:

var = <condition>

In your case:

match_var = a == b

Plugin is too old, please update to a more recent version, or set ANDROID_DAILY_OVERRIDE environment variable to

I got a way which finally resolve this 1. check your calsspath in the top build.gradle,e.g mine is classpath 'com.android.tools.build:gradle:2.1.0-alpha3' then go to https://jcenter.bintray.com/com/android/tools/build/gradle/ find a release which is newer than yours,here I choose 2.1.0-beta3 change classpath to below, then launch the build. classpath 'com.android.tools.build:gradle:2.1.0-beta3'

Creating files in C++

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

string filename = "/tmp/filename.txt";

int main() {
  std::ofstream o(filename.c_str());

  o << "Hello, World\n" << std::endl;

  return 0;
}

This is what I had to do in order to use a variable for the filename instead of a regular string.

how to make window.open pop up Modal?

You can't make window.open modal and I strongly recommend you not to go that way. Instead you can use something like jQuery UI's dialog widget.

UPDATE:

You can use load() method:

$("#dialog").load("resource.php").dialog({options});

This way it would be faster but the markup will merge into your main document so any submit will be applied on the main window.

And you can use an IFRAME:

$("#dialog").append($("<iframe></iframe>").attr("src", "resource.php")).dialog({options});

This is slower, but will submit independently.

How to put a link on a button with bootstrap?

If you don't really need the button element, just move the classes to a regular link:

<div class="btn-group">
    <a href="/save/1" class="btn btn-primary active">
        <i class="glyphicon glyphicon-floppy-disk" aria-hidden="true"></i> Save
    </a>
    <a href="/cancel/1" class="btn btn-default">Cancel</a>
</div>

Conversely, you can also change a button to appear like a link:

<button type="button" class="btn btn-link">Link</button>

How do format a phone number as a String in Java?

U can format any string containing non numeric characters also to your desired format use my util class to format

usage is very simple

public static void main(String[] args){
    String num = "ab12345*&67890";

    System.out.println(PhoneNumberUtil.formateToPhoneNumber(num,"(XXX)-XXX-XXXX",10));
}

output: (123)-456-7890

u can specify any foramt such as XXX-XXX-XXXX and length of the phone number , if input length is greater than specified length then string will be trimmed.

Get my class from here: https://github.com/gajeralalji/PhoneNumberUtil/blob/master/PhoneNumberUtil.java

CSS: how to position element in lower right?

Lets say your HTML looks something like this:

<div class="box">
    <!-- stuff -->
    <p class="bet_time">Bet 5 days ago</p>
</div>

Then, with CSS, you can make that text appear in the bottom right like so:

.box {
    position:relative;
}
.bet_time {
    position:absolute;
    bottom:0;
    right:0;
}

The way this works is that absolutely positioned elements are always positioned with respect to the first relatively positioned parent element, or the window. Because we set the box's position to relative, .bet_time positions its right edge to the right edge of .box and its bottom edge to the bottom edge of .box

How to store command results in a shell variable?

The syntax to store the command output into a variable is var=$(command).

So you can directly do:

result=$(ls -l | grep -c "rahul.*patle")

And the variable $result will contain the number of matches.

SQL Server JOIN missing NULL values

you can just map like that

select * from tableA a
join tableB b on isnull(a.colID,'') = isnull(b.colId,'')

ggplot with 2 y axes on each side and different scales

The answer by Hadley gives an interesting reference to Stephen Few's report Dual-Scaled Axes in Graphs Are They Ever the Best Solution?.

I do not know what the OP means with "counts" and "rate" but a quick search gives me Counts and Rates, so I get some data about Accidents in North American Mountaineering1:

Years<-c("1998","1999","2000","2001","2002","2003","2004")
Persons.Involved<-c(281,248,301,276,295,231,311)
Fatalities<-c(20,17,24,16,34,18,35)
rate=100*Fatalities/Persons.Involved
df<-data.frame(Years=Years,Persons.Involved=Persons.Involved,Fatalities=Fatalities,rate=rate)
print(df,row.names = FALSE)

 Years Persons.Involved Fatalities      rate
  1998              281         20  7.117438
  1999              248         17  6.854839
  2000              301         24  7.973422
  2001              276         16  5.797101
  2002              295         34 11.525424
  2003              231         18  7.792208
  2004              311         35 11.254019

And then I tried to do the graph as Few suggested at page 7 of the aforementioned report (and following the request of OP to graph the counts as a bar chart and the rates as a line chart) :

The other less obvious solution, which works only for time series, is to convert all sets of values to a common quantitative scale by displaying percentage differences between each value and a reference (or index) value. For instance, select a particular point in time, such as the first interval that appears in the graph, and express each subsequent value as the percentage difference between it and the initial value. This is done by dividing the value at each point in time by the value for the initial point in time and then multiplying it by 100 to convert the rate to a percentage, as illustrated below.

df2<-df
df2$Persons.Involved <- 100*df$Persons.Involved/df$Persons.Involved[1]
df2$rate <- 100*df$rate/df$rate[1]
plot(ggplot(df2)+
  geom_bar(aes(x=Years,weight=Persons.Involved))+
  geom_line(aes(x=Years,y=rate,group=1))+
  theme(text = element_text(size=30))
  )

And this is the result: enter image description here

But I do not like it a lot and I am not able to easily put a legend on it...

1 WILLIAMSON, Jed, et al. Accidents in North American Mountaineering 2005. The Mountaineers Books, 2005.

How to extend a class in python?

Another way to extend (specifically meaning, add new methods, not change existing ones) classes, even built-in ones, is to use a preprocessor that adds the ability to extend out of/above the scope of Python itself, converting the extension to normal Python syntax before Python actually gets to see it.

I've done this to extend Python 2's str() class, for instance. str() is a particularly interesting target because of the implicit linkage to quoted data such as 'this' and 'that'.

Here's some extending code, where the only added non-Python syntax is the extend:testDottedQuad bit:

extend:testDottedQuad
def testDottedQuad(strObject):
    if not isinstance(strObject, basestring): return False
    listStrings = strObject.split('.')
    if len(listStrings) != 4: return False
    for strNum in listStrings:
        try:    val = int(strNum)
        except: return False
        if val < 0: return False
        if val > 255: return False
    return True

After which I can write in the code fed to the preprocessor:

if '192.168.1.100'.testDottedQuad():
    doSomething()

dq = '216.126.621.5'
if not dq.testDottedQuad():
    throwWarning();

dqt = ''.join(['127','.','0','.','0','.','1']).testDottedQuad()
if dqt:
    print 'well, that was fun'

The preprocessor eats that, spits out normal Python without monkeypatching, and Python does what I intended it to do.

Just as a c preprocessor adds functionality to c, so too can a Python preprocessor add functionality to Python.

My preprocessor implementation is too large for a stack overflow answer, but for those who might be interested, it is here on GitHub.

Execute an action when an item on the combobox is selected

this is how you do it with ActionLIstener

import java.awt.FlowLayout;
import java.awt.event.*;

import javax.swing.*;

public class MyWind extends JFrame{

    public MyWind() {
        initialize();
    }

    private void initialize() {
        setSize(300, 300);
        setLayout(new FlowLayout(FlowLayout.LEFT));
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        final JTextField field = new JTextField();
        field.setSize(200, 50);
        field.setText("              ");

        JComboBox comboBox = new JComboBox();
        comboBox.setEditable(true);
        comboBox.addItem("item1");
        comboBox.addItem("item2");

        //
        // Create an ActionListener for the JComboBox component.
        //
        comboBox.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent event) {
                //
                // Get the source of the component, which is our combo
                // box.
                //
                JComboBox comboBox = (JComboBox) event.getSource();

                Object selected = comboBox.getSelectedItem();
                if(selected.toString().equals("item1"))
                field.setText("30");
                else if(selected.toString().equals("item2"))
                    field.setText("40");

            }
        });
        getContentPane().add(comboBox);
        getContentPane().add(field);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                new MyWind().setVisible(true);
            }
        });
    }
}

How to "wait" a Thread in Android

You can try this one it is short :)

SystemClock.sleep(7000);

It will sleep for 7 sec look at documentation

How to automatically update your docker containers, if base-images are updated

Another approach could be to assume that your base image gets behind quite quickly (and that's very likely to happen), and force another image build of your application periodically (e.g. every week) and then re-deploy it if it has changed.

As far as I can tell, popular base images like the official Debian or Java update their tags to cater for security fixes, so tags are not immutable (if you want a stronger guarantee of that you need to use the reference [image:@digest], available in more recent Docker versions). Therefore, if you were to build your image with docker build --pull, then your application should get the latest and greatest of the base image tag you're referencing.

Since mutable tags can be confusing, it's best to increment the version number of your application every time you do this so that at least on your side things are cleaner.

So I'm not sure that the script suggested in one of the previous answers does the job, since it doesn't rebuild you application's image - it just updates the base image tag and then it restarts the container, but the new container still references the old base image hash.

I wouldn't advocate for running cron-type jobs in containers (or any other processes, unless really necessary) as this goes against the mantra of running only one process per container (there are various arguments about why this is better, so I'm not going to go into it here).

dyld: Library not loaded: /usr/local/opt/icu4c/lib/libicui18n.62.dylib error running php after installing node with brew on Mac

Update - As stated in some of the comments, running brew cleanup could possibly fix this error, if that alone doesn't fix it, you might try upgrading individual packages or all your brew packages.

I just had this same problem. Upgrading Homebrew and then cleaning up worked for me. This error likely showed up for me because of a mismatch in package versions. None of the above solutions resolved my error, but running the following homebrew commands did.

Caution - This will upgrade all your brew packages, including, but not limited to PHP. If you only want to upgrade specific packages make sure to be specific.

brew upgrade // for upgrading all packages -- this is the command I used

brew upgrade {package} // for upgrading a specific package

and finally

brew cleanup

How to convert a Java String to an ASCII byte array?

If you are a user there is a handy Charsets class:

String s = "Hello, world!";
byte[] b = s.getBytes(Charsets.US_ASCII);

Apart from not hard-coding arbitrary charset name in your source code it has a much bigger advantage: Charsets.US_ASCII is of Charset type (not String) so you avoid checked UnsupportedEncodingException thrown only from String.getBytes(String), but not from String.getBytes(Charset).

In Java 7 there is equivalent StandardCharsets class.

Hidden Features of Xcode

If you have a multi-touch capable Mac - use MultiClutch to map some of the keystrokes described by mouse gestures.

I use three finger forward and back to go forward and back in file history (cmd-alt-.), and pinch to switch between .h and .m.

Difference between Apache CXF and Axis

One more thing is the activity of the community. Compare the mailing list traffic for axis and cxf (2013).

So if this is any indicator of usage then axis is by far less used than cxf.

Compare CXF and Axis statistics at ohloh. CXF has very high activity while Axis has low activity overall.

This is the chart for the number of commits over time for CXF (red) and Axis1 (green) Axis2 (blue). enter image description here

How to programmatically get iOS status bar height

    var statusHeight: CGFloat!
    if #available(iOS 13.0, *) {
         statusHeight = UIApplication.shared.keyWindow?.windowScene?.statusBarManager?.statusBarFrame.height
    } else {
        // Fallback on earlier versions
        statusHeight = UIApplication.shared.statusBarFrame.height
    }

Is there an ignore command for git like there is for svn?

On Linux/Unix, you can append files to the .gitignore file with the echo command. For example if you want to ignore all .svn folders, run this from the root of the project:

echo .svn/ >> .gitignore

How To Execute SSH Commands Via PHP

Use the ssh2 functions. Anything you'd do via an exec() call can be done directly using these functions, saving you a lot of connections and shell invocations.

What's the difference between import java.util.*; and import java.util.Date; ?

Your program should work exactly the same with either import java.util.*; or import java.util.Date;. There has to be something else you did in between.

How to specify preference of library path?

This is an old question, but no one seems to have mentioned this.

You were getting lucky that the thing was linking at all.

You needed to change

g++ -g -Wall -o my_binary -L/my/dir -lfoo bar.cpp

to this:

g++ -g -Wall -o my_binary -L/my/dir bar.cpp -lfoo

Your linker keeps track of symbols it needs to resolve. If it reads the library first, it doesn't have any needed symbols, so it ignores the symbols in it. Specify the libraries after the things that need to link to them so that your linker has symbols to find in them.

Also, -lfoo makes it search specifically for a file named libfoo.a or libfoo.so as needed. Not libfoo.so.0. So either ln the name or rename the library as appopriate.

To quote the gcc man page:

-l library
   ...
   It makes a difference where in the command you 
   write this option; the linker searches and processes 
   libraries and object files in the order they are 
   specified.  Thus, foo.o -lz bar.o searches library z 
   after file foo.o but before bar.o.  If bar.o refers 
   to functions in z, those functions may not be loaded.

Adding the file directly to g++'s command line should have worked, unless of course, you put it prior to bar.cpp, causing the linker to ignore it for lacking any needed symbols, because no symbols were needed yet.

jQuery select change show/hide div event

Nothing new but caching your jQuery collections will have a small perf boost

$(function() {

    var $typeSelector = $('#type');
    var $toggleArea = $('#row_dim');

    $typeSelector.change(function(){
        if ($typeSelector.val() === 'parcel') {
            $toggleArea.show(); 
        }
        else {
            $toggleArea.hide(); 
        }
    });
});

And in vanilla JS for super speed:

(function() {

    var typeSelector = document.getElementById('type');
    var toggleArea = document.getElementById('row_dim');

    typeSelector.onchange = function() {
        toggleArea.style.display = typeSelector.value === 'parcel'
            ? 'block'
            : 'none';
    };

});

Where can I get Google developer key

It's the API key as listed under 'API Access', the 'Simple API Access' box.

nodemon command is not recognized in terminal for node js server

Since node prefix is not in the PATH ENV variable , any of the globally installed modules are not getting recognized. Please try this. Open cmd prompt npm config get prefix append the resulting path to PATH env variable. Now you should be able to run nodemon from any location. try this link and follow it.fixing npm permissions https://docs.npmjs.com/getting-started/fixing-npm-permissions#option-2-change-npms-default-directory-to-another-directory

Why is the minidlna database not being refreshed?

There is a patch for the sourcecode of minidlna at sourceforge available that does not make a full rescan, but a kind of incremental scan. That worked fine, but with some later version, the patch is broken. See here Link to SF

Regards Gerry

AppSettings get value from .config file

Some of the Answers seems a little bit off IMO Here is my take circa 2016

<add key="ClientsFilePath" value="filepath"/>

Make sure System.Configuration is referenced.

Question is asking for value of an appsettings key

Which most certainly SHOULD be

  string yourKeyValue = ConfigurationManager.AppSettings["ClientsFilePath"]

  //yourKeyValue should hold on the HEAP  "filepath"

Here is a twist in which you can group together values ( not for this question)

var emails = ConfigurationManager.AppSettings[ConfigurationManager.AppSettings["Environment"] + "_Emails"];

emails will be value of Environment Key + "_Emails"

example :   [email protected];[email protected];

How can I set the maximum length of 6 and minimum length of 6 in a textbox?

You can find the answer here: Is there a minlength validation attribute in HTML5?

Therefore this should do the job:

<input pattern=".{6,6}">

Better way of getting time in milliseconds in javascript?

As far that I know you only can get time with Date.

Date.now is the solution but is not available everywhere : https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date/now.

var currentTime = +new Date();

This gives you the current time in milliseconds.

For your jumps. If you compute interpolations correctly according to the delta frame time and you don't have some rounding number error, I bet for the garbage collector (GC).

If there is a lot of created temporary object in your loop, garbage collection has to lock the thread to make some cleanup and memory re-organization.

With Chrome you can see how much time the GC is spending in the Timeline panel.

EDIT: Since my answer, Date.now() should be considered as the best option as it is supported everywhere and on IE >= 9.

How do change the color of the text of an <option> within a <select>?

You just need to add disabled as option attribute

<option disabled>select one option</option>

How to convert date to timestamp?

The below code will convert the current date into the timestamp.

var currentTimeStamp = Date.parse(new Date());
console.log(currentTimeStamp);

How to center a navigation bar with CSS or HTML?

#nav ul {
    display: inline-block;
    list-style-type: none;
}

It should work, I tested it in your site.

enter image description here

CMD: Export all the screen content to a text file

From command prompt Run as Administrator. Example below is to print a list of Services running on your PC run the command below:

net start > c:\netstart.txt

You should see a copy of the text file you just exported with a listing all the PC services running at the root of your C:\ drive.

MVC 3 file upload and model binding

If you won't always have images posting to your action, you can do something like this:

[HttpPost]
public ActionResult Uploadfile(Container container, HttpPostedFileBase file) 
{
    //do container stuff

    if (Request.Files != null)
    {
        foreach (string requestFile in Request.Files)
        {
            HttpPostedFileBase file = Request.Files[requestFile]; 
            if (file.ContentLength > 0)
            {
                string fileName = Path.GetFileName(file.FileName);
                string directory = Server.MapPath("~/App_Data/uploads/");
                if (!Directory.Exists(directory))
                {
                    Directory.CreateDirectory(directory);
                }
                string path = Path.Combine(directory, fileName);
                file.SaveAs(path);
            }
        }
    }

} 

How to know if other threads have finished?

Look at the Java documentation for the Thread class. You can check the thread's state. If you put the three threads in member variables, then all three threads can read each other's states.

You have to be a bit careful, though, because you can cause race conditions between the threads. Just try to avoid complicated logic based on the state of the other threads. Definitely avoid multiple threads writing to the same variables.

How do I change screen orientation in the Android emulator?

With Android Studio:

Windows: Ctrl+Left-Arrow and Ctrl+Right-Arrow

ImportError: numpy.core.multiarray failed to import

Just fixed this issue. import c2 or import numpy was not working. Uninstalled the most current version of numpy. Tried to install numpy==1.15.2 just like specified above, did not work. Tried numpy==1.19.3 IT worked. I guess not all versions work perfectly with all versions of python and dependencies. So keep uninstalling and install one that works.

How to require a controller in an angularjs directive

There is a good stackoverflow answer here by Mark Rajcok:

AngularJS directive controllers requiring parent directive controllers?

with a link to this very clear jsFiddle: http://jsfiddle.net/mrajcok/StXFK/

<div ng-controller="MyCtrl">
    <div screen>
        <div component>
            <div widget>
                <button ng-click="widgetIt()">Woo Hoo</button>
            </div>
        </div>
    </div>
</div>

JavaScript

var myApp = angular.module('myApp',[])

.directive('screen', function() {
    return {
        scope: true,
        controller: function() {
            this.doSomethingScreeny = function() {
                alert("screeny!");
            }
        }
    }
})

.directive('component', function() {
    return {
        scope: true,
        require: '^screen',
        controller: function($scope) {
            this.componentFunction = function() {
                $scope.screenCtrl.doSomethingScreeny();
            }
        },
        link: function(scope, element, attrs, screenCtrl) {
            scope.screenCtrl = screenCtrl
        }
    }
})

.directive('widget', function() {
    return {
        scope: true,
        require: "^component",
        link: function(scope, element, attrs, componentCtrl) {
            scope.widgetIt = function() {
                componentCtrl.componentFunction();
            };
        }
    }
})


//myApp.directive('myDirective', function() {});
//myApp.factory('myService', function() {});

function MyCtrl($scope) {
    $scope.name = 'Superhero';
}

How do I filter an array with AngularJS and use a property of the filtered object as the ng-model attribute?

You can also use functions with $filter('filter'):

var foo = $filter('filter')($scope.results.subjects, function (item) {
  return item.grade !== 'A';
});

do-while loop in R

See ?Control or the R Language Definition:

> y=0
> while(y <5){ print( y<-y+1) }
[1] 1
[1] 2
[1] 3
[1] 4
[1] 5

So do_while does not exist as a separate construct in R, but you can fake it with:

repeat( { expressions}; if (! end_cond_expr ) {break} )

If you want to see the help page you cannot type ?while or ?repeat at the console but rather need to use ?'repeat' or ?'while'. All the "control-constructs" including if are on the same page and all need character quoting after the "?" so the interpreter doesn't see them as incomplete code and give you a continuation "+".

Deleting Elements in an Array if Element is a Certain value VBA

An array is a structure with a certain size. You can use dynamic arrays in vba that you can shrink or grow using ReDim but you can't remove elements in the middle. It's not clear from your sample how your array functionally works or how you determine the index position (eachHdr) but you basically have 3 options

(A) Write a custom 'delete' function for your array like (untested)

Public Sub DeleteElementAt(Byval index As Integer, Byref prLst as Variant)
       Dim i As Integer

        ' Move all element back one position
        For i = index + 1 To UBound(prLst)
            prLst(i - 1) = prLst(i)
        Next

        ' Shrink the array by one, removing the last one
        ReDim Preserve prLst(Len(prLst) - 1)
End Sub

(B) Simply set a 'dummy' value as the value instead of actually deleting the element

If prLst(eachHdr) = "0" Then        
   prLst(eachHdr) = "n/a"
End If

(C) Stop using an array and change it into a VBA.Collection. A collection is a (unique)key/value pair structure where you can freely add or delete elements from

Dim prLst As New Collection

Binning column with python pandas

You can use pandas.cut:

bins = [0, 1, 5, 10, 25, 50, 100]
df['binned'] = pd.cut(df['percentage'], bins)
print (df)
   percentage     binned
0       46.50   (25, 50]
1       44.20   (25, 50]
2      100.00  (50, 100]
3       42.12   (25, 50]

bins = [0, 1, 5, 10, 25, 50, 100]
labels = [1,2,3,4,5,6]
df['binned'] = pd.cut(df['percentage'], bins=bins, labels=labels)
print (df)
   percentage binned
0       46.50      5
1       44.20      5
2      100.00      6
3       42.12      5

Or numpy.searchsorted:

bins = [0, 1, 5, 10, 25, 50, 100]
df['binned'] = np.searchsorted(bins, df['percentage'].values)
print (df)
   percentage  binned
0       46.50       5
1       44.20       5
2      100.00       6
3       42.12       5

...and then value_counts or groupby and aggregate size:

s = pd.cut(df['percentage'], bins=bins).value_counts()
print (s)
(25, 50]     3
(50, 100]    1
(10, 25]     0
(5, 10]      0
(1, 5]       0
(0, 1]       0
Name: percentage, dtype: int64

s = df.groupby(pd.cut(df['percentage'], bins=bins)).size()
print (s)
percentage
(0, 1]       0
(1, 5]       0
(5, 10]      0
(10, 25]     0
(25, 50]     3
(50, 100]    1
dtype: int64

By default cut return categorical.

Series methods like Series.value_counts() will use all categories, even if some categories are not present in the data, operations in categorical.

Using GPU from a docker container?

Ok i finally managed to do it without using the --privileged mode.

I'm running on ubuntu server 14.04 and i'm using the latest cuda (6.0.37 for linux 13.04 64 bits).


Preparation

Install nvidia driver and cuda on your host. (it can be a little tricky so i will suggest you follow this guide https://askubuntu.com/questions/451672/installing-and-testing-cuda-in-ubuntu-14-04)

ATTENTION : It's really important that you keep the files you used for the host cuda installation


Get the Docker Daemon to run using lxc

We need to run docker daemon using lxc driver to be able to modify the configuration and give the container access to the device.

One time utilization :

sudo service docker stop
sudo docker -d -e lxc

Permanent configuration Modify your docker configuration file located in /etc/default/docker Change the line DOCKER_OPTS by adding '-e lxc' Here is my line after modification

DOCKER_OPTS="--dns 8.8.8.8 --dns 8.8.4.4 -e lxc"

Then restart the daemon using

sudo service docker restart

How to check if the daemon effectively use lxc driver ?

docker info

The Execution Driver line should look like that :

Execution Driver: lxc-1.0.5

Build your image with the NVIDIA and CUDA driver.

Here is a basic Dockerfile to build a CUDA compatible image.

FROM ubuntu:14.04
MAINTAINER Regan <http://stackoverflow.com/questions/25185405/using-gpu-from-a-docker-container>

RUN apt-get update && apt-get install -y build-essential
RUN apt-get --purge remove -y nvidia*

ADD ./Downloads/nvidia_installers /tmp/nvidia                             > Get the install files you used to install CUDA and the NVIDIA drivers on your host
RUN /tmp/nvidia/NVIDIA-Linux-x86_64-331.62.run -s -N --no-kernel-module   > Install the driver.
RUN rm -rf /tmp/selfgz7                                                   > For some reason the driver installer left temp files when used during a docker build (i don't have any explanation why) and the CUDA installer will fail if there still there so we delete them.
RUN /tmp/nvidia/cuda-linux64-rel-6.0.37-18176142.run -noprompt            > CUDA driver installer.
RUN /tmp/nvidia/cuda-samples-linux-6.0.37-18176142.run -noprompt -cudaprefix=/usr/local/cuda-6.0   > CUDA samples comment if you don't want them.
RUN export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/usr/local/cuda/lib64         > Add CUDA library into your PATH
RUN touch /etc/ld.so.conf.d/cuda.conf                                     > Update the ld.so.conf.d directory
RUN rm -rf /temp/*  > Delete installer files.

Run your image.

First you need to identify your the major number associated with your device. Easiest way is to do the following command :

ls -la /dev | grep nvidia

If the result is blank, use launching one of the samples on the host should do the trick. The result should look like that enter image description here As you can see there is a set of 2 numbers between the group and the date. These 2 numbers are called major and minor numbers (wrote in that order) and design a device. We will just use the major numbers for convenience.

Why do we activated lxc driver? To use the lxc conf option that allow us to permit our container to access those devices. The option is : (i recommend using * for the minor number cause it reduce the length of the run command)

--lxc-conf='lxc.cgroup.devices.allow = c [major number]:[minor number or *] rwm'

So if i want to launch a container (Supposing your image name is cuda).

docker run -ti --lxc-conf='lxc.cgroup.devices.allow = c 195:* rwm' --lxc-conf='lxc.cgroup.devices.allow = c 243:* rwm' cuda

Remove folder and its contents from git/GitHub's history

The best and most accurate method I found was to download the bfg.jar file: https://rtyley.github.io/bfg-repo-cleaner/

Then run the commands:

git clone --bare https://project/repository project-repository
cd project-repository
java -jar bfg.jar --delete-folders DIRECTORY_NAME
git reflog expire --expire=now --all && git gc --prune=now --aggressive
git push --mirror https://project/new-repository

If you want to delete files then use the delete-files option instead:

java -jar bfg.jar --delete-files *.pyc

Send HTML in email via PHP

The trick is to know the content id of the Image mime part when building the html body part. It boils down to making the img tag

https://github.com/horde/horde/blob/master/kronolith/lib/Kronolith.php

Look at the function buildMimeMessage for a working example.

What are the differences between NP, NP-Complete and NP-Hard?

There are really nice answers for this particular question, so there is no point to write my own explanation. So I will try to contribute with an excellent resource about different classes of computational complexity.

For someone who thinks that computational complexity is only about P and NP, here is the most exhaustive resource about different computational complexity problems. Apart from problems asked by OP, it listed approximately 500 different classes of computational problems with nice descriptions and also the list of fundamental research papers which describe the class.

How to override maven property in command line?

See Introduction to the POM

finalName is created as:

<build>
    <finalName>${project.artifactId}-${project.version}</finalName>
</build>

One of the solutions is to add own property:

<properties>
    <finalName>${project.artifactId}-${project.version}</finalName>
</properties>
<build>
    <finalName>${finalName}</finalName>
 </build>

And now try:

mvn -DfinalName=build clean package

Best way to run scheduled tasks

We use console applications also. If you use logging tools like Log4net you can properly monitor their execution. Also, I'm not sure how they are more difficult to maintain than a web page, given you may be sharing some of the same code libraries between the two if it is designed properly.

If you are against having those tasks run on a timed basis, you could have a web page in your administrative section of your website that acts as a queue. User puts in a request to run the task, it in turn inserts a blank datestamp record on MyProcessQueue table and your scheduled task is checking every X minutes for a new record in MyProcessQueue. That way, it only runs when the customer wants it to run.

Hope those suggestions help.

How to make a countdown timer in Android?

enter image description here

MainActivity.java

package com.zeustechnocrats.countdown;

import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import java.text.SimpleDateFormat;
import java.util.Date;

public class MainActivity extends AppCompatActivity {

    private String EVENT_DATE_TIME = "2020-12-31 10:30:00";
    private String DATE_FORMAT = "yyyy-MM-dd HH:mm:ss";
    private LinearLayout linear_layout_1, linear_layout_2;
    private TextView tv_days, tv_hour, tv_minute, tv_second;
    private Handler handler = new Handler();
    private Runnable runnable;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.count_down);

        initUI();
        countDownStart();
    }

    private void initUI() {
        linear_layout_1 = findViewById(R.id.linear_layout_1);
        linear_layout_2 = findViewById(R.id.linear_layout_2);
        tv_days = findViewById(R.id.tv_days);
        tv_hour = findViewById(R.id.tv_hour);
        tv_minute = findViewById(R.id.tv_minute);
        tv_second = findViewById(R.id.tv_second);
    }

    private void countDownStart() {
        runnable = new Runnable() {
            @Override
            public void run() {
                try {
                    handler.postDelayed(this, 1000);
                    SimpleDateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT);
                    Date event_date = dateFormat.parse(EVENT_DATE_TIME);
                    Date current_date = new Date();
                    if (!current_date.after(event_date)) {
                        long diff = event_date.getTime() - current_date.getTime();
                        long Days = diff / (24 * 60 * 60 * 1000);
                        long Hours = diff / (60 * 60 * 1000) % 24;
                        long Minutes = diff / (60 * 1000) % 60;
                        long Seconds = diff / 1000 % 60;
                        //
                        tv_days.setText(String.format("%02d", Days));
                        tv_hour.setText(String.format("%02d", Hours));
                        tv_minute.setText(String.format("%02d", Minutes));
                        tv_second.setText(String.format("%02d", Seconds));
                    } else {
                        linear_layout_1.setVisibility(View.VISIBLE);
                        linear_layout_2.setVisibility(View.GONE);
                        handler.removeCallbacks(runnable);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        };
        handler.postDelayed(runnable, 0);
    }

    protected void onStop() {
        super.onStop();
        handler.removeCallbacks(runnable);
    }
}

activity_main.xml

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@android:color/white"
    android:orientation="horizontal">

    <LinearLayout
        android:id="@+id/linear_layout_1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@android:color/black"
        android:gravity="center_horizontal"
        android:visibility="gone">

        <TextView
            android:id="@+id/tv_event"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="20dp"
            android:text="Android Event Start"
            android:textColor="@android:color/white"
            android:textSize="20dp"
            android:textStyle="normal" />
    </LinearLayout>

    <LinearLayout
        android:id="@+id/linear_layout_2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@android:color/black"
        android:visibility="visible">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:orientation="vertical">

            <TextView
                android:id="@+id/tv_days"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center"
                android:text="00"
                android:textColor="@android:color/white"
                android:textSize="20dp"
                android:textStyle="bold" />

            <TextView
                android:id="@+id/tv_days_title"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center"
                android:text="Days"
                android:textColor="@android:color/white"
                android:textSize="20dp"
                android:textStyle="normal" />
        </LinearLayout>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:orientation="vertical">

            <TextView
                android:id="@+id/tv_hour"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center"
                android:text="00"
                android:textColor="@android:color/white"
                android:textSize="20dp"
                android:textStyle="bold" />

            <TextView
                android:id="@+id/tv_hour_title"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center"
                android:text="Hour"
                android:textColor="@android:color/white"
                android:textSize="20dp"
                android:textStyle="normal" />
        </LinearLayout>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:orientation="vertical">

            <TextView
                android:id="@+id/tv_minute"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center"
                android:text="00"
                android:textColor="@android:color/white"
                android:textSize="20dp"
                android:textStyle="bold" />

            <TextView
                android:id="@+id/tv_minute_title"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center"
                android:text="Minute"
                android:textColor="@android:color/white"
                android:textSize="20dp"
                android:textStyle="normal" />
        </LinearLayout>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:orientation="vertical">

            <TextView
                android:id="@+id/tv_second"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center"
                android:text="00"
                android:textColor="@android:color/white"
                android:textSize="20dp"
                android:textStyle="bold" />

            <TextView
                android:id="@+id/tv_second_title"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center"
                android:text="Second"
                android:textColor="@android:color/white"
                android:textSize="20dp"
                android:textStyle="normal" />
        </LinearLayout>
    </LinearLayout>
</LinearLayout>

How to create a md5 hash of a string in C?

Here's a complete example:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#if defined(__APPLE__)
#  define COMMON_DIGEST_FOR_OPENSSL
#  include <CommonCrypto/CommonDigest.h>
#  define SHA1 CC_SHA1
#else
#  include <openssl/md5.h>
#endif

char *str2md5(const char *str, int length) {
    int n;
    MD5_CTX c;
    unsigned char digest[16];
    char *out = (char*)malloc(33);

    MD5_Init(&c);

    while (length > 0) {
        if (length > 512) {
            MD5_Update(&c, str, 512);
        } else {
            MD5_Update(&c, str, length);
        }
        length -= 512;
        str += 512;
    }

    MD5_Final(digest, &c);

    for (n = 0; n < 16; ++n) {
        snprintf(&(out[n*2]), 16*2, "%02x", (unsigned int)digest[n]);
    }

    return out;
}

    int main(int argc, char **argv) {
        char *output = str2md5("hello", strlen("hello"));
        printf("%s\n", output);
        free(output);
        return 0;
    }

What is Inversion of Control?

Let to say that we make some meeting in some hotel.

Many people, many carafes of water, many plastic cups.

When somebody want to drink, she fill cup, drink and throw cup on the floor.

After hour or something we have a floor covered of plastic cups and water.

Let invert control.

The same meeting in the same place, but instead of plastic cups we have a waiter with one glass cup (Singleton)

and she all of time offers to guests drinking.

When somebody want to drink, she get from waiter glass, drink and return it back to waiter.

Leaving aside the question of the hygienic, last form of drinking process control is much more effective and economic.

And this is exactly what the Spring (another IoC container, for example: Guice) does. Instead of let to application create what it need using new keyword (taking plastic cup), Spring IoC container all of time offer to application the same instance (singleton) of needed object(glass of water).

Think about yourself as organizer of such meeting. You need the way to message to hotel administration that

meeting members will need glass of water but not piece of cake.

Example:-

public class MeetingMember {

    private GlassOfWater glassOfWater;

    ...

    public void setGlassOfWater(GlassOfWater glassOfWater){
        this.glassOfWater = glassOfWater;
    }
    //your glassOfWater object initialized and ready to use...
    //spring IoC  called setGlassOfWater method itself in order to
    //offer to meetingMember glassOfWater instance

}

Useful links:-

How to join two tables by multiple columns in SQL?

SELECT E.CaseNum, E.FileNum, E.ActivityNum, E.Grade, V.Score
FROM Evaluation E
INNER JOIN Value V
ON E.CaseNum = V.CaseNum AND E.FileNum = V.FileNum AND E.ActivityNum = V.ActivityNum

How to insert data to MySQL having auto incremented primary key?

Check out this post

According to it

No value was specified for the AUTO_INCREMENT column, so MySQL assigned sequence numbers automatically. You can also explicitly assign NULL or 0 to the column to generate sequence numbers.

Angular.js How to change an elements css class on click and to remove all others

have you tried with a condition in ng-class like here : http://jsfiddle.net/DotDotDot/zvLvg/ ?

    <span id='1' ng-class='{"myclass":tog==1}' ng-click='tog=1'>span 1</span>
    <span id='2' ng-class='{"myclass":tog==2}' ng-click='tog=2'>span 2</span>

Javascript change Div style

function abc() {
    var color = document.getElementById("test").style.color;
    color = (color=="red") ? "black" : "red" ;
    document.getElementById("test").style.color= color;
}

Javascript Thousand Separator / string format

// thousand separates a digit-only string using commas
// by element:  onkeyup = "ThousandSeparate(this)"
// by ID:       onkeyup = "ThousandSeparate('txt1','lbl1')"
function ThousandSeparate()
{
    if (arguments.length == 1)
    {
        var V = arguments[0].value;
        V = V.replace(/,/g,'');
        var R = new RegExp('(-?[0-9]+)([0-9]{3})'); 
        while(R.test(V))
        {
            V = V.replace(R, '$1,$2');
        }
        arguments[0].value = V;
    }
    else  if ( arguments.length == 2)
    {
        var V = document.getElementById(arguments[0]).value;
        var R = new RegExp('(-?[0-9]+)([0-9]{3})'); 
        while(R.test(V))
        {
            V = V.replace(R, '$1,$2');
        }
        document.getElementById(arguments[1]).innerHTML = V;
    }
    else return false;
}   

Practical uses of git reset --soft?

Use Case - Combine a series of local commits

"Oops. Those three commits could be just one."

So, undo the last 3 (or whatever) commits (without affecting the index nor working directory). Then commit all the changes as one.

E.g.

> git add -A; git commit -m "Start here."
> git add -A; git commit -m "One"
> git add -A; git commit -m "Two"
> git add -A' git commit -m "Three"
> git log --oneline --graph -4 --decorate

> * da883dc (HEAD, master) Three
> * 92d3eb7 Two
> * c6e82d3 One
> * e1e8042 Start here.

> git reset --soft HEAD~3
> git log --oneline --graph -1 --decorate

> * e1e8042 Start here.

Now all your changes are preserved and ready to be committed as one.

Short answers to your questions

Are these two commands really the same (reset --soft vs commit --amend)?

  • No.

Any reason to use one or the other in practical terms?

  • commit --amend to add/rm files from the very last commit or to change its message.
  • reset --soft <commit> to combine several sequential commits into a new one.

And more importantly, are there any other uses for reset --soft apart from amending a commit?

  • See other answers :)

Using DISTINCT along with GROUP BY in SQL Server

Use DISTINCT to remove duplicate GROUPING SETS from the GROUP BY clause

In a completely silly example using GROUPING SETS() in general (or the special grouping sets ROLLUP() or CUBE() in particular), you could use DISTINCT in order to remove the duplicate values produced by the grouping sets again:

SELECT DISTINCT actors
FROM (VALUES('a'), ('a'), ('b'), ('b')) t(actors)
GROUP BY CUBE(actors, actors)

With DISTINCT:

actors
------
NULL
a
b

Without DISTINCT:

actors
------
a
b
NULL
a
b
a
b

But why, apart from making an academic point, would you do that?

Use DISTINCT to find unique aggregate function values

In a less far-fetched example, you might be interested in the DISTINCT aggregated values, such as, how many different duplicate numbers of actors are there?

SELECT DISTINCT COUNT(*)
FROM (VALUES('a'), ('a'), ('b'), ('b')) t(actors)
GROUP BY actors

Answer:

count
-----
2

Use DISTINCT to remove duplicates with more than one GROUP BY column

Another case, of course, is this one:

SELECT DISTINCT actors, COUNT(*)
FROM (VALUES('a', 1), ('a', 1), ('b', 1), ('b', 2)) t(actors, id)
GROUP BY actors, id

With DISTINCT:

actors  count
-------------
a       2
b       1

Without DISTINCT:

actors  count
-------------
a       2
b       1
b       1

For more details, I've written some blog posts, e.g. about GROUPING SETS and how they influence the GROUP BY operation, or about the logical order of SQL operations (as opposed to the lexical order of operations).

How do I make a semi transparent background?

If you want to make transparent background is gray, pls try:

   .transparent{
       background:rgba(1,1,1,0.5);
   }

Attach (open) mdf file database with SQL Server Management Studio

You may need to repair your mdf file first using some tools. There are lot of tool available in the market. There is tool called SQL Database Recovery Tool Repairs which is very useful to repair the mdf files.

The issue might me because of corrupted transaction logs, you may use tool SQL Database Recovery Tool Repairs to repair your corrupted mdf file.

How can I remove the outline around hyperlinks images?

in order to Removing The Dotted Outline href link you can write in your css file:

a {
   outline: 0;
}

CORS: Cannot use wildcard in Access-Control-Allow-Origin when credentials flag is true

This is a part of security, you cannot do that. If you want to allow credentials then your Access-Control-Allow-Origin must not use *. You will have to specify the exact protocol + domain + port. For reference see these questions :

  1. Access-Control-Allow-Origin wildcard subdomains, ports and protocols
  2. Cross Origin Resource Sharing with Credentials

Besides * is too permissive and would defeat use of credentials. So set http://localhost:3000 or http://localhost:8000 as the allow origin header.

Vertical divider doesn't work in Bootstrap 3

Here is some LESS for you, in case you customize the navbar:

.navbar .divider-vertical {
    height: floor(@navbar-height - @navbar-margin-bottom);
    margin: floor(@navbar-margin-bottom / 2) 9px;
    border-left: 1px solid #f2f2f2;
    border-right: 1px solid #ffffff;
}

How do you get the logical xor of two variables in Python?

The way that Python handles logic operations can be confusing, so my implementation gives the user the option (by default) of a simple True/False answer. The actual Python result can be obtained by setting the optional third arg to None.

def xor(a, b, true=True, false=False): # set true to None to get actual Python result
    ab1 = a and not b
    ab2 = not a and b
    if bool(ab1) != bool(ab2):
        return (ab1 or ab2) if true is None else true
    else:
        return false

private final static attribute vs private final attribute

For final, it can be assigned different values at runtime when initialized. For example

class Test{
  public final int a;
}

Test t1  = new Test();
t1.a = 10;
Test t2  = new Test();
t2.a = 20; //fixed

Thus each instance has different value of field a.

For static final, all instances share the same value, and can't be altered after first initialized.

class TestStatic{
      public static final int a = 0;
}

TestStatic t1  = new TestStatic();
t1.a = 10; // ERROR, CAN'T BE ALTERED AFTER THE FIRST 
TestStatic t2  = new TestStatic();
t1.a = 20;   // ERROR, CAN'T BE ALTERED AFTER THE FIRST INITIALIZATION.

How to format LocalDate to string?

A pretty nice way to do this is to use SimpleDateFormat I'll show you how:

SimpleDateFormat sdf = new SimpleDateFormat("d MMMM YYYY");
Date d = new Date();
sdf.format(d);

I see that you have the date in a variable:

sdf.format(variable_name);

Cheers.

Submit form using a button outside the <form> tag

In HTML5, there is the form attribute. Basically

<form id="myform" method="get" action="something.php">
    <input type="text" name="name" />
</form>

<input type="submit" form="myform" />

How to capture Curl output to a file?

There are several options to make curl output to a file

 # saves it to myfile.txt
curl http://www.example.com/data.txt -o myfile.txt

# The #1 will get substituted with the url, so the filename contains the url
curl http://www.example.com/data.txt -o "file_#1.txt" 

# saves to data.txt, the filename extracted from the URL
curl http://www.example.com/data.txt -O 

# saves to filename determined by the Content-Disposition header sent by the server.
curl http://www.example.com/data.txt -O -J 

Passing by reference in C

You're passing a pointer(address location) by value.

It's like saying "here's the place with the data I want you to update."

How do I rename both a Git local and remote branch name?

I had to do the following task to rename local and remote branch:

# Rename the local branch to the new name
git branch -m <old_name> <new_name>

#  Delete the old remote branch
git push origin --delete <old_name>

# push to new remote branch - creates new remote branch
git push origin <new_name>

# set new remote branch as default remote branch for local branch
git branch --set-upstream-to=origin/<new_name> <new_name>

Retrieving JSON Object Literal from HttpServletRequest

There is another way to do it, using org.apache.commons.io.IOUtils to extract the String from the request

String jsonString = IOUtils.toString(request.getInputStream());

Then you can do whatever you want, convert it to JSON or other object with Gson, etc.

JSONObject json = new JSONObject(jsonString);
MyObject myObject = new Gson().fromJson(jsonString, MyObject.class);

How to apply shell command to each line of a command output?

i like to use gawk for running multiple commands on a list, for instance

ls -l | gawk '{system("/path/to/cmd.sh "$1)}'

however the escaping of the escapable characters can get a little hairy.

How do I clone a github project to run locally?

You clone a repository with git clone [url]. Like so,

$ git clone https://github.com/libgit2/libgit2

Docker error cannot delete docker container, conflict: unable to remove repository reference

There is a difference between docker images and docker containers. Check this SO Question.

In short, a container is a runnable instance of an image. which is why you cannot delete an image if there is a running container from that image. You just need to delete the container first.

docker ps -a                # Lists containers (and tells you which images they are spun from)

docker images               # Lists images 

docker rm <container_id>    # Removes a stopped container

docker rm -f <container_id> # Forces the removal of a running container (uses SIGKILL)

docker rmi <image_id>       # Removes an image 
                            # Will fail if there is a running instance of that image i.e. container

docker rmi -f <image_id>    # Forces removal of image even if it is referenced in multiple repositories, 
                            # i.e. same image id given multiple names/tags 
                            # Will still fail if there is a docker container referencing image

Update for Docker 1.13+ [Since Jan 2017]

In Docker 1.13, we regrouped every command to sit under the logical object it’s interacting with

Basically, above commands could also be rewritten, more clearly, as:

docker container ls -a
docker image ls
docker container rm <container_id>
docker image rm <image_id>

Also, if you want to remove EVERYTHING you could use:

docker system prune -a

WARNING! This will remove:

  • all stopped containers
  • all networks not used by at least one container
  • all unused images
  • all build cache

How do I calculate the date in JavaScript three months prior to today?

var d = new Date();
d.setMonth(d.getMonth() - 3);

This works for January. Run this snippet:

_x000D_
_x000D_
var d = new Date("January 14, 2012");_x000D_
console.log(d.toLocaleDateString());_x000D_
d.setMonth(d.getMonth() - 3);_x000D_
console.log(d.toLocaleDateString());
_x000D_
_x000D_
_x000D_


There are some caveats...

A month is a curious thing. How do you define 1 month? 30 days? Most people will say that one month ago means the same day of the month on the previous month citation needed. But more than half the time, that is 31 days ago, not 30. And if today is the 31st of the month (and it isn't August or Decemeber), that day of the month doesn't exist in the previous month.

Interestingly, Google agrees with JavaScript if you ask it what day is one month before another day:

Google search result for 'one month before March 31st' shows 'March 3rd'

It also says that one month is 30.4167 days long: Google search result for 'one month in days' shows '30.4167'

So, is one month before March 31st the same day as one month before March 28th, 3 days earlier? This all depends on what you mean by "one month before". Go have a conversation with your product owner.

If you want to do like momentjs does, and correct these last day of the month errors by moving to the last day of the month, you can do something like this:

_x000D_
_x000D_
const d = new Date("March 31, 2019");_x000D_
console.log(d.toLocaleDateString());_x000D_
const month = d.getMonth();_x000D_
d.setMonth(d.getMonth() - 1);_x000D_
while (d.getMonth() === month) {_x000D_
    d.setDate(d.getDate() - 1);_x000D_
}_x000D_
console.log(d.toLocaleDateString());
_x000D_
_x000D_
_x000D_

If your requirements are more complicated than that, use some math and write some code. You are a developer! You don't have to install a library! You don't have to copy and paste from stackoverflow! You can develop the code yourself to do precisely what you need!

Generate a sequence of numbers in Python

Write a function that takes a number as an argument and prints the Fibonacci series till that number

def Series(n):  
    a = 0  
    b = 1  
    print(a)  
    print(b)  
    S = 0  
    for i in range(0,n):  
        if S <= n-1:  
            S = a + b  
            print(S)  
            a = b  
            b = S

Laravel PDOException SQLSTATE[HY000] [1049] Unknown database 'forge'

I had this problem for several days, it turns out if I created the db inside phpMyAdmin it wouldn't appear to Laravel, so, I created the db through MySqlWorkbench, and it worked :)

How to tell 'PowerShell' Copy-Item to unconditionally copy files

From the documentation (help copy-item -full):

-force <SwitchParameter>
    Allows cmdlet to override restrictions such as renaming existing files as long as security is not compromised.

    Required?                    false
    Position?                    named
    Default value                False
    Accept pipeline input?       false
    Accept wildcard characters?  false

How to use string.substr() function?

If I am correct, the second parameter of substr() should be the length of the substring. How about

b = a.substr(i,2);

?

Can you have multiple $(document).ready(function(){ ... }); sections?

Yes you can easily have multiple blocks. Just be careful with dependencies between them as the evaluation order might not be what you expect.

Is Spring annotation @Controller same as @Service?

  • Controller will handle the navigation between the different views. Your mappings request mappings are handled with the help of controller.
  • Service interacts directly with the repository where usually the business logic is performed. You can add, delete, remove etc at the service layer

Python, Matplotlib, subplot: How to set the axis range?

Sometimes you really want to set the axes limits before you plot the data. In that case, you can set the "autoscaling" feature of the Axes or AxesSubplot object. The functions of interest are set_autoscale_on, set_autoscalex_on, and set_autoscaley_on.

In your case, you want to freeze the y axis' limits, but allow the x axis to expand to accommodate your data. Therefore, you want to change the autoscaley_on property to False. Here is a modified version of the FFT subplot snippet from your code:

fft_axes = pylab.subplot(h,w,2)
pylab.title("FFT")
fft = scipy.fft(rawsignal)
pylab.ylim([0,1000])
fft_axes.set_autoscaley_on(False)
pylab.plot(abs(fft))

Javascript form validation with password confirming

 if ($("#Password").val() != $("#ConfirmPassword").val()) {
          alert("Passwords do not match.");
      }

A JQuery approach that will eliminate needless code.

Disabling Minimize & Maximize On WinForm?

How to make form minimize when closing was already answered, but how to remove the minimize and maximize buttons wasn't.
FormBorderStyle: FixedDialog
MinimizeBox: false
MaximizeBox: false

Error message: (provider: Shared Memory Provider, error: 0 - No process is on the other end of the pipe.)

Enable Mixed authentication mode while installing MSSQL server. Also provide password for sa user.

Add Class to Object on Page Load

This should work:

window.onload = function() {
  document.getElementById('about').className = 'expand';
};

Or if you're using jQuery:

$(function() {
  $('#about').addClass('expand');
});

In Python how should I test if a variable is None, True or False

Don't fear the Exception! Having your program just log and continue is as easy as:

try:
    result = simulate(open("myfile"))
except SimulationException as sim_exc:
    print "error parsing stream", sim_exc
else:
    if result:
        print "result pass"
    else:
        print "result fail"

# execution continues from here, regardless of exception or not

And now you can have a much richer type of notification from the simulate method as to what exactly went wrong, in case you find error/no-error not to be informative enough.

Excel VBA - Pass a Row of Cell Values to an Array and then Paste that Array to a Relative Reference of Cells

When i Tried your Code i got en Error when i wanted to fill the Array.

you can try to fill the Array like This.

Sub Testing_Data()
Dim k As Long, S2 As Worksheet, VArray

Application.ScreenUpdating = False
Set S2 = ThisWorkbook.Sheets("Sheet1")
With S2
    VArray = .Range("A1:A" & .Cells(Rows.Count, "A").End(xlUp).Row)
End With
For k = 2 To UBound(VArray, 1)
    S2.Cells(k, "B") = VArray(k, 1) / 100
    S2.Cells(k, "C") = VArray(k, 1) * S2.Cells(k, "B")
Next

End Sub

Converting string format to datetime in mm/dd/yyyy

You need an uppercase M for the month part.

string strDate = DateTime.Now.ToString("MM/dd/yyyy");

Lowercase m is for outputting (and parsing) a minute (such as h:mm).

e.g. a full date time string might look like this:

string strDate = DateTime.Now.ToString("MM/dd/yyyy h:mm");

Notice the uppercase/lowercase mM difference.


Also if you will always deal with the same datetime format string, you can make it easier by writing them as C# extension methods.

public static class DateTimeMyFormatExtensions
{
  public static string ToMyFormatString(this DateTime dt)
  {
    return dt.ToString("MM/dd/yyyy");
  }
}

public static class StringMyDateTimeFormatExtension
{
  public static DateTime ParseMyFormatDateTime(this string s)
  {
    var culture = System.Globalization.CultureInfo.CurrentCulture;
    return DateTime.ParseExact(s, "MM/dd/yyyy", culture);
  }
}

EXAMPLE: Translating between DateTime/string

DateTime now = DateTime.Now;

string strNow = now.ToMyFormatString();
DateTime nowAgain = strNow.ParseMyFormatDateTime();

Note that there is NO way to store a custom DateTime format information to use as default as in .NET most string formatting depends on the currently set culture, i.e.

System.Globalization.CultureInfo.CurrentCulture.

The only easy way you can do is to roll a custom extension method.

Also, the other easy way would be to use a different "container" or "wrapper" class for your DateTime, i.e. some special class with explicit operator defined that automatically translates to and from DateTime/string. But that is dangerous territory.

JavaScript single line 'if' statement - best syntax, this alternative?

As has already been stated, you can use:

&& style

lemons && document.write("foo gave me a bar");  

or

bracket-less style

if (lemons) document.write("foo gave me a bar");

short-circuit return

If, however, you wish to use the one line if statement to short-circuit a function though, you'd need to go with the bracket-less version like so:

if (lemons) return "foo gave me a bar";

as

lemons && return "foo gave me a bar"; // does not work!

will give you a SyntaxError: Unexpected keyword 'return'

How to delete a folder with files using Java

You can try this

public static void deleteDir(File dirFile) {
    if (dirFile.isDirectory()) {
        File[] dirs = dirFile.listFiles();
        for (File dir: dirs) {
            deleteDir(dir);
        }
    }
    dirFile.delete();
}

How to install PHP intl extension in Ubuntu 14.04

you could search with aptitude search intl after you can choose the right one, for example sudo aptitude install php-intl and finally sudo service apache2 restart

good Luck!

Inserting a Python datetime.datetime object into MySQL

For a time field, use:

import time    
time.strftime('%Y-%m-%d %H:%M:%S')

I think strftime also applies to datetime.

Add element to a list In Scala

I will try to explain the results of all the commands you tried.

scala> val l = 1.0 :: 5.5 :: Nil
l: List[Double] = List(1.0, 5.5)

First of all, List is a type alias to scala.collection.immutable.List (defined in Predef.scala).

Using the List companion object is more straightforward way to instantiate a List. Ex: List(1.0,5.5)

scala> l
res0: List[Double] = List(1.0, 5.5)

scala> l ::: List(2.2, 3.7)
res1: List[Double] = List(1.0, 5.5, 2.2, 3.7)

::: returns a list resulting from the concatenation of the given list prefix and this list

The original List is NOT modified

scala> List(l) :+ 2.2
res2: List[Any] = List(List(1.0, 5.5), 2.2)

List(l) is a List[List[Double]] Definitely not what you want.

:+ returns a new list consisting of all elements of this list followed by elem.

The type is List[Any] because it is the common superclass between List[Double] and Double

scala> l
res3: List[Double] = List(1.0, 5.5)

l is left unmodified because no method on immutable.List modified the List.

select and echo a single field from mysql db using PHP

And escape your values with mysql_real_escape_string since PHP6 won't do that for you anymore! :)

Java split string to array

This behavior is explicitly documented in String.split(String regex) (emphasis mine):

This method works as if by invoking the two-argument split method with the given expression and a limit argument of zero. Trailing empty strings are therefore not included in the resulting array.

If you want those trailing empty strings included, you need to use String.split(String regex, int limit) with a negative value for the second parameter (limit):

String[] array = values.split("\\|", -1);

Cycles in an Undirected Graph

A simple DFS does the work of checking if the given undirected graph has a cycle or not.

Here's the C++ code to the same.

The idea used in the above code is:

If a node which is already discovered/visited is found again and is not the parent node , then we have a cycle.

This can also be explained as below(mentioned by @Rafal Dowgird

If an unexplored edge leads to a node visited before, then the graph contains a cycle.

How do I sort a list of dictionaries by a value of the dictionary?

It may look cleaner using a key instead a cmp:

newlist = sorted(list_to_be_sorted, key=lambda k: k['name']) 

or as J.F.Sebastian and others suggested,

from operator import itemgetter
newlist = sorted(list_to_be_sorted, key=itemgetter('name')) 

For completeness (as pointed out in comments by fitzgeraldsteele), add reverse=True to sort descending

newlist = sorted(l, key=itemgetter('name'), reverse=True)

How to suppress "unused parameter" warnings in C?

Labelling the attribute is ideal way. MACRO leads to sometime confusion. and by using void(x),we are adding an overhead in processing.

If not using input argument, use

void foo(int __attribute__((unused))key)
{
}

If not using the variable defined inside the function

void foo(int key)
{
   int hash = 0;
   int bkt __attribute__((unused)) = 0;

   api_call(x, hash, bkt);
}

Now later using the hash variable for your logic but doesn’t need bkt. define bkt as unused, otherwise compiler says'bkt set bt not used".

NOTE: This is just to suppress the warning not for optimization.

TextView - setting the text size programmatically doesn't seem to work

Text size 2 will be practically invisible. Try it with 14 at least. BTW, using xml has a lot of advantages and will make your life easier once you need to do anything more complex than 'Hello World'.

How to count occurrences of a column value efficiently in SQL?

select s.id, s.age, c.count
from students s
inner join (
    select age, count(*) as count
    from students
    group by age
) c on s.age = c.age
order by id

How do I get Month and Date of JavaScript in 2 digit format?

Just another example, almost one liner.

_x000D_
_x000D_
var date = new Date();_x000D_
console.log( (date.getMonth() < 9 ? '0': '') + (date.getMonth()+1) );
_x000D_
_x000D_
_x000D_

How to set the size of a column in a Bootstrap responsive table

Bootstrap 4.0

Be aware of all migration changes from Bootstrap 3 to 4. On the table you now need to enable flex box by adding the class d-flex, and drop the xs to allow bootstrap to automatically detect the viewport.

<div class="container-fluid">
    <table id="productSizes" class="table">
        <thead>
            <tr class="d-flex">
                <th class="col-1">Size</th>
                <th class="col-3">Bust</th>
                <th class="col-3">Waist</th>
                <th class="col-5">Hips</th>
            </tr>
        </thead>
        <tbody>
            <tr class="d-flex">
                <td class="col-1">6</td>
                <td class="col-3">79 - 81</td>
                <td class="col-3">61 - 63</td>
                <td class="col-5">89 - 91</td>
            </tr>
            <tr class="d-flex">
                <td class="col-1">8</td>
                <td class="col-3">84 - 86</td>
                <td class="col-3">66 - 68</td>
                <td class="col-5">94 - 96</td>
            </tr>
        </tbody>
    </table>

bootply

Bootstrap 3.2

Table column width use the same layout as grids do; using col-[viewport]-[size]. Remember the column sizes should total 12; 1 + 3 + 3 + 5 = 12 in this example.

        <thead>
            <tr>
                <th class="col-xs-1">Size</th>
                <th class="col-xs-3">Bust</th>
                <th class="col-xs-3">Waist</th>
                <th class="col-xs-5">Hips</th>
            </tr>
        </thead>

Remember to set the <th> elements rather than the <td> elements so it sets the whole column. Here is a working BOOTPLY.

Thanks to @Dan for reminding me to always work mobile view (col-xs-*) first.

How to pass an object from one activity to another on Android

It is impossible to serialize any type of object. For Example you can not serialize delegate methods or interfaces that carry code instead of data. So I have written a 'Box' class you can use to pass any type of data without Serialization.

1- for putting Data to Intent Use:

Intent I = new Intent(this, YourActivity.class);
CustomClass Date = new CustomClass();
Box.Add(I, "Name", Data);

2- for retrieving Data from Intent:

CustomClass Data = Box.Get(getIntent(), "Name");

3- for removing data after use, add this method to your activity:

@Override
protected void onDestroy() {
    Box.Remove(getIntent());
    super.onDestroy();
}

4- and add this code to your project:

package ir.namirasoft.Utility;

import android.content.Intent;

import java.util.HashMap;
import java.util.Vector;

public class Box {
    // Number
    private static int Number = 1;

    public static int NextNumber() {
        return Number++;
    }

    //
    private static String _Intent_Identifier = "_Intent_Identifier";
    private static HashMap<Integer, Vector<Integer>> DeleteList = new HashMap<Integer, Vector<Integer>>();
    private static HashMap<Integer, HashMap<String, Object>> ObjectList = new HashMap<Integer, HashMap<String, Object>>();

    public static int GetIntent_Identifier(Intent I) {
        int Intent_Identifier = I.getIntExtra(_Intent_Identifier, 0);
        if (Intent_Identifier == 0)
            I.putExtra(_Intent_Identifier, Intent_Identifier = NextNumber());
        return Intent_Identifier;
    }

    public static void Add(Intent I, String Name, Object O) {
        int Intent_Identifier = GetIntent_Identifier(I);
        synchronized (ObjectList) {
            if (!ObjectList.containsKey(Intent_Identifier))
                ObjectList.put(Intent_Identifier, new HashMap<String, Object>());
            ObjectList.get(Intent_Identifier).put(Name, O);
        }
    }

    public static <T> T Get(Intent I, String Name) {
        int Intent_Identifier = GetIntent_Identifier(I);
        synchronized (DeleteList) {
            DeleteList.remove(Intent_Identifier);
        }
        return (T) ObjectList.get(Intent_Identifier).get(Name);
    }

    public static void Remove(final Intent I) {
        final int Intent_Identifier = GetIntent_Identifier(I);
        final int ThreadID = NextNumber();
        synchronized (DeleteList) {
            if (!DeleteList.containsKey(Intent_Identifier))
                DeleteList.put(Intent_Identifier, new Vector<Integer>());
            DeleteList.get(Intent_Identifier).add(ThreadID);
        }
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(60 * 1000);
                } catch (InterruptedException e) {
                }
                synchronized (DeleteList) {
                    if (DeleteList.containsKey(Intent_Identifier))
                        if (DeleteList.get(Intent_Identifier).contains(ThreadID))
                            synchronized (ObjectList) {
                                ObjectList.remove(Intent_Identifier);
                            }
                }
            }
        }).start();
    }
}

** Box class is Thread-Safe.

How do I erase an element from std::vector<> by index?

If you work with large vectors (size > 100,000) and want to delete lots of elements, I would recommend to do something like this:

int main(int argc, char** argv) {

    vector <int> vec;
    vector <int> vec2;

    for (int i = 0; i < 20000000; i++){
        vec.push_back(i);}

    for (int i = 0; i < vec.size(); i++)
    {
        if(vec.at(i) %3 != 0)
            vec2.push_back(i);
    }

    vec = vec2;
    cout << vec.size() << endl;
}

The code takes every number in vec that can't be divided by 3 and copies it to vec2. Afterwards it copies vec2 in vec. It is pretty fast. To process 20,000,000 elements this algorithm only takes 0.8 sec!

I did the same thing with the erase-method, and it takes lots and lots of time:

Erase-Version (10k elements)  : 0.04 sec
Erase-Version (100k elements) : 0.6  sec
Erase-Version (1000k elements): 56   sec
Erase-Version (10000k elements): ...still calculating (>30 min)

How to delete duplicate lines in a file without sorting it in Unix?

The first solution is also from http://sed.sourceforge.net/sed1line.txt

$ echo -e '1\n2\n2\n3\n3\n3\n4\n4\n4\n4\n5' |sed -nr '$!N;/^(.*)\n\1$/!P;D'
1
2
3
4
5

the core idea is:

print ONLY once of each duplicate consecutive lines at its LAST appearance and use D command to implement LOOP.

Explains:

  1. $!N;: if current line is NOT the last line, use N command to read the next line into pattern space.
  2. /^(.*)\n\1$/!P: if the contents of current pattern space is two duplicate string separated by \n, which means the next line is the same with current line, we can NOT print it according to our core idea; otherwise, which means current line is the LAST appearance of all of its duplicate consecutive lines, we can now use P command to print the chars in current pattern space util \n (\n also printed).
  3. D: we use D command to delete the chars in current pattern space util \n (\n also deleted), then the content of pattern space is the next line.
  4. and D command will force sed to jump to its FIRST command $!N, but NOT read the next line from file or standard input stream.

The second solution is easy to understood (from myself):

$ echo -e '1\n2\n2\n3\n3\n3\n4\n4\n4\n4\n5' |sed -nr 'p;:loop;$!N;s/^(.*)\n\1$/\1/;tloop;D'
1
2
3
4
5

the core idea is:

print ONLY once of each duplicate consecutive lines at its FIRST appearance and use : command & t command to implement LOOP.

Explains:

  1. read a new line from input stream or file and print it once.
  2. use :loop command set a label named loop.
  3. use N to read next line into the pattern space.
  4. use s/^(.*)\n\1$/\1/ to delete current line if the next line is same with current line, we use s command to do the delete action.
  5. if the s command is executed successfully, then use tloop command force sed to jump to the label named loop, which will do the same loop to the next lines util there are no duplicate consecutive lines of the line which is latest printed; otherwise, use D command to delete the line which is the same with thelatest-printed line, and force sed to jump to first command, which is the p command, the content of current pattern space is the next new line.

How to set image to UIImage

UIImage *img = [UIImage imageNamed@"aImageName"];

PHP: HTTP or HTTPS?

This can get more complicated depending on where PHP sits in your environment, since your question is quite broad. This may depend on whether there's a load-balancer and how it's configured. Here are are a few related questions:

PHP form - on submit stay on same page

Friend. Use this way, There will be no "Undefined variable message" and it will work fine.

<?php
    if(isset($_POST['SubmitButton'])){
        $price = $_POST["price"];
        $qty = $_POST["qty"];
        $message = $price*$qty;
    }

        ?>

    <!DOCTYPE html>
    <html>
    <head>
        <title></title>
    </head>
    <body>
        <form action="#" method="post">
            <input type="number" name="price"> <br>
            <input type="number" name="qty"><br>
            <input type="submit" name="SubmitButton">
        </form>
        <?php echo "The Answer is" .$message; ?>

    </body>
    </html>

Send email with PHPMailer - embed image in body

I found the answer:

$mail->AddEmbeddedImage('img/2u_cs_mini.jpg', 'logo_2u');

and on the <img> tag put src='cid:logo_2u'

How to bind multiple values to a single WPF TextBlock?

If these are just going to be textblocks (and thus one way binding), and you just want to concatenate values, just bind two textblocks and put them in a horizontal stackpanel.

    <StackPanel Orientation="Horizontal">
        <TextBlock Text="{Binding Name}"/>
        <TextBlock Text="{Binding ID}"/>
    </StackPanel>

That will display the text (which is all Textblocks do) without having to do any more coding. You might put a small margin on them to make them look right though.

How to do INSERT into a table records extracted from another table

No "VALUES", no parenthesis:

INSERT INTO Table2(LongIntColumn2, CurrencyColumn2)
SELECT LongIntColumn1, Avg(CurrencyColumn) as CurrencyColumn1 FROM Table1 GROUP BY LongIntColumn1;

Countdown timer using Moment js

The following also requires the moment-duration-format plugin:

$.fn.countdown = function ( options ) {
    var $target = $(this);
    var defaults = {
        seconds: 0,
        format: 'hh:mm:ss',
        stopAtZero: true
    };
    var settings = $.extend(defaults, options);
    var eventTime = Date.now() + ( settings.seconds * 1000 );
    var diffTime = eventTime - Date.now();
    var duration = moment.duration( diffTime, 'milliseconds' );
    var interval = 0;
    $target.text( duration.format( settings.format, { trim: false }) );
    var counter = setInterval(function () {
        $target.text( moment.duration( duration.asSeconds() - ++interval, 'seconds' ).format( settings.format, { trim: false }) );
        if( settings.stopAtZero && interval >= settings.seconds ) clearInterval( counter );
    }, 1000);
};

Usage example:

$('#someDiv').countdown({
    seconds: 30*60,
    format: 'mm:ss'
});

File Upload using AngularJS

Some of the answers here propose using FormData(), but unfortunately that is a browser object not available in Internet Explorer 9 and below. If you need to support those older browsers, you will need a backup strategy such as using <iframe> or Flash.

There are already many Angular.js modules to perform file uploading. These two have explicit support for older browsers:

And some other options:

One of these should fit your project, or may give you some insight into how to code it yourself.

How to force deletion of a python object?

  1. Add an exit handler that closes all the bars.
  2. __del__() gets called when the number of references to an object hits 0 while the VM is still running. This may be caused by the GC.
  3. If __init__() raises an exception then the object is assumed to be incomplete and __del__() won't be invoked.

Difference between return and exit in Bash functions

The OP's question: What is the difference between the return and exit statement in BASH functions with respect to exit codes?

Firstly, some clarification is required:

  • A (return|exit) statement is not required to terminate execution of a (function|shell). A (function|shell) will terminate when it reaches the end of its code list, even with no (return|exit) statement.

  • A (return|exit) statement is not required to pass a value back from a terminated (function|shell). Every process has a built-in variable $? which always has a numeric value. It is a special variable that cannot be set like "?=1", but it is set only in special ways (see below *).

    The value of $? after the last command to be executed in the (called function | sub shell) is the value that is passed back to the (function caller | parent shell). That is true whether the last command executed is ("return [n]"| "exit [n]") or plain ("return" or something else which happens to be the last command in the called function's code.

In the above bullet list, choose from "(x|y)" either always the first item or always the second item to get statements about functions and return, or shells and exit, respectively.

What is clear is that they both share common usage of the special variable $? to pass values upwards after they terminate.

* Now for the special ways that $? can be set:

  • When a called function terminates and returns to its caller then $? in the caller will be equal to the final value of $? in the terminated function.
  • When a parent shell implicitly or explicitly waits on a single sub shell and is released by termination of that sub shell, then $? in the parent shell will be equal to the final value of $? in the terminated sub shell.
  • Some built-in functions can modify $? depending upon their result. But some don't.
  • Built-in functions "return" and "exit", when followed by a numerical argument both $? with argument, and terminate execution.

It is worth noting that $? can be assigned a value by calling exit in a sub shell, like this:

# (exit 259)
# echo $?
3

How do I get the last character of a string?

The other answers contain a lot of needless text and code. Here are two ways to get the last character of a String:

char

char lastChar = myString.charAt(myString.length() - 1);

String

String lastChar = myString.substring(myString.length() - 1);

ld cannot find an existing library

As just formulated by grepsedawk, the answer lies in the -l option of g++, calling ld. If you look at the man page of this command, you can either do:

  • g++ -l:libmagic.so.1 [...]
  • or: g++ -lmagic [...] , if you have a symlink named libmagic.so in your libs path

Parse query string into an array

Use http://us1.php.net/parse_str

Attention, it's usage is:

parse_str($str, &$array);

not

$array = parse_str($str);

Find row where values for column is maximal in a pandas DataFrame

You might also try idxmax:

In [5]: df = pandas.DataFrame(np.random.randn(10,3),columns=['A','B','C'])

In [6]: df
Out[6]: 
          A         B         C
0  2.001289  0.482561  1.579985
1 -0.991646 -0.387835  1.320236
2  0.143826 -1.096889  1.486508
3 -0.193056 -0.499020  1.536540
4 -2.083647 -3.074591  0.175772
5 -0.186138 -1.949731  0.287432
6 -0.480790 -1.771560 -0.930234
7  0.227383 -0.278253  2.102004
8 -0.002592  1.434192 -1.624915
9  0.404911 -2.167599 -0.452900

In [7]: df.idxmax()
Out[7]: 
A    0
B    8
C    7

e.g.

In [8]: df.loc[df['A'].idxmax()]
Out[8]: 
A    2.001289
B    0.482561
C    1.579985

When should I use uuid.uuid1() vs. uuid.uuid4() in python?

uuid1() is guaranteed to not produce any collisions (under the assumption you do not create too many of them at the same time). I wouldn't use it if it's important that there's no connection between the uuid and the computer, as the mac address gets used to make it unique across computers.

You can create duplicates by creating more than 214 uuid1 in less than 100ns, but this is not a problem for most use cases.

uuid4() generates, as you said, a random UUID. The chance of a collision is really, really, really small. Small enough, that you shouldn't worry about it. The problem is, that a bad random-number generator makes it more likely to have collisions.

This excellent answer by Bob Aman sums it up nicely. (I recommend reading the whole answer.)

Frankly, in a single application space without malicious actors, the extinction of all life on earth will occur long before you have a collision, even on a version 4 UUID, even if you're generating quite a few UUIDs per second.

JQuery show/hide when hover

('.cat').hover(
  function () {
    $(this).show();
  }, 
  function () {
    $(this).hide();
  }
);

It's the same for the others.

For the smooth fade in you can use fadeIn and fadeOut

jQuery attr('onclick')

As @Richard pointed out above, the onClick needs to have a capital 'C'.

$('#stop').click(function() {
     $('next').attr('onClick','stopMoving()');
}

Auto-redirect to another HTML page

One of these will work...

_x000D_
_x000D_
<head>_x000D_
  <meta http-equiv='refresh' content='0; URL=http://example.com/'>_x000D_
</head>
_x000D_
_x000D_
_x000D_

...or it can done with JavaScript:

_x000D_
_x000D_
window.location.href = 'https://example.com/';
_x000D_
_x000D_
_x000D_

Could not load file or assembly ... The parameter is incorrect

If you are using SQL Server 2012's Data Tools, which uses the VS2010 shell as at May 1 2013, check your Configuration Manager settings. A server name change from Workflow to xCPWorkflow was enough to produce the exact same The parameter is incorrect (Exception from HRESULT: 0x80070057 (E_INVALIDARG)) message.

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

Even the auto-increment column is not PK ( in this example it is called seq - aka sequence ) you could achieve that with a trigger :

DROP TABLE IF EXISTS devops_guide CASCADE;

SELECT 'create the "devops_guide" table'
;
   CREATE TABLE devops_guide (
      guid           UUID NOT NULL DEFAULT gen_random_uuid()
    , level          integer NULL
    , seq            integer NOT NULL DEFAULT 1
    , name           varchar (200) NOT NULL DEFAULT 'name ...'
    , description    text NULL
    , CONSTRAINT pk_devops_guide_guid PRIMARY KEY (guid)
    ) WITH (
      OIDS=FALSE
    );

-- START trg_devops_guide_set_all_seq
CREATE OR REPLACE FUNCTION fnc_devops_guide_set_all_seq()
    RETURNS TRIGGER
    AS $$
       BEGIN
         UPDATE devops_guide SET seq=col_serial FROM
         (SELECT guid, row_number() OVER ( ORDER BY seq) AS col_serial FROM devops_guide ORDER BY seq) AS tmp_devops_guide
         WHERE devops_guide.guid=tmp_devops_guide.guid;

         RETURN NEW;
       END;
    $$ LANGUAGE plpgsql;

 CREATE TRIGGER trg_devops_guide_set_all_seq
  AFTER UPDATE OR DELETE ON devops_guide
  FOR EACH ROW
  WHEN (pg_trigger_depth() < 1)
  EXECUTE PROCEDURE fnc_devops_guide_set_all_seq();

Anaconda-Navigator - Ubuntu16.04

it works :

export PATH=/home/yourUserName/anaconda3/bin:$PATH

after that run anaconda-navigator command. remember anaconda can't in Sudo mode, so don't use sudo at all.

Anaconda Running screenshot

How to detect when WIFI Connection has been established in Android?

This code does not require permission at all. It is restricted only to Wi-Fi network connectivity state changes (any other network is not taken into account). The receiver is statically published in the AndroidManifest.xml file and does not need to be exported as it will be invoked by the system protected broadcast, NETWORK_STATE_CHANGED_ACTION, at every network connectivity state change.

AndroidManifest:

<receiver
    android:name=".WifiReceiver"
    android:enabled="true"
    android:exported="false">

    <intent-filter>
        <!--protected-broadcast: Special broadcast that only the system can send-->
        <!--Corresponds to: android.net.wifi.WifiManager.NETWORK_STATE_CHANGED_ACTION-->
        <action android:name="android.net.wifi.STATE_CHANGE" />
    </intent-filter>

</receiver>

BroadcastReceiver class:

public class WifiReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
/*
 Tested (I didn't test with the WPS "Wi-Fi Protected Setup" standard):
 In API15 (ICE_CREAM_SANDWICH) this method is called when the new Wi-Fi network state is:
 DISCONNECTED, OBTAINING_IPADDR, CONNECTED or SCANNING

 In API19 (KITKAT) this method is called when the new Wi-Fi network state is:
 DISCONNECTED (twice), OBTAINING_IPADDR, VERIFYING_POOR_LINK, CAPTIVE_PORTAL_CHECK
 or CONNECTED

 (Those states can be obtained as NetworkInfo.DetailedState objects by calling
 the NetworkInfo object method: "networkInfo.getDetailedState()")
*/
    /*
     * NetworkInfo object associated with the Wi-Fi network.
     * It won't be null when "android.net.wifi.STATE_CHANGE" action intent arrives.
     */
    NetworkInfo networkInfo = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);

    if (networkInfo != null && networkInfo.isConnected()) {
        // TODO: Place the work here, like retrieving the access point's SSID

        /*
         * WifiInfo object giving information about the access point we are connected to.
         * It shouldn't be null when the new Wi-Fi network state is CONNECTED, but it got
         * null sometimes when connecting to a "virtualized Wi-Fi router" in API15.
         */
        WifiInfo wifiInfo = intent.getParcelableExtra(WifiManager.EXTRA_WIFI_INFO);
        String ssid = wifiInfo.getSSID();
    }
}
}

Permissions:

None

Core dump file analysis

You just need a binary (with debugging symbols included) that is identical to the one that generated the core dump file. Then you can run gdb path/to/the/binary path/to/the/core/dump/file to debug it.

When it starts up, you can use bt (for backtrace) to get a stack trace from the time of the crash. In the backtrace, each function invocation is given a number. You can use frame number (replacing number with the corresponding number in the stack trace) to select a particular stack frame.

You can then use list to see code around that function, and info locals to see the local variables. You can also use print name_of_variable (replacing "name_of_variable" with a variable name) to see its value.

Typing help within GDB will give you a prompt that will let you see additional commands.

How to find third or n?? maximum salary from salary table?

Optimized way,

;With CTE as
(
select salary 
        ,RANK(order by salary desc) as Rnk
from table
)
select * from CTE where Rnk = @yourVariable

Second Opinion,

Declare @yourVariable int = 2
Select top 1 * from 
(
select distinct top(@yourVariable)  salary 
from Employees
order by salary desc
)as a
order by a.salary asc
select * from Employees
order by salary desc

Push items into mongo array via mongoose

Assuming, var friend = { firstName: 'Harry', lastName: 'Potter' };

There are two options you have:

Update the model in-memory, and save (plain javascript array.push):

person.friends.push(friend);
person.save(done);

or

PersonModel.update(
    { _id: person._id }, 
    { $push: { friends: friend } },
    done
);

I always try and go for the first option when possible, because it'll respect more of the benefits that mongoose gives you (hooks, validation, etc.).

However, if you are doing lots of concurrent writes, you will hit race conditions where you'll end up with nasty version errors to stop you from replacing the entire model each time and losing the previous friend you added. So only go to the former when it's absolutely necessary.

What is NODE_ENV and how to use it in Express?

NODE_ENV is an environmental variable that stands for node environment in express server.

It's how we set and detect which environment we are in.

It's very common using production and development.

Set:

export NODE_ENV=production

Get:

You can get it using app.get('env')

Import pfx file into particular certificate store from command line

Anchoring my findings here for future readers.

Import certificate to Trusted Root Certification Authorities on Local Machine:

CERTUTIL -addstore -enterprise -f -v root "somCertificat.cer"

Import pfx to Personal on local machine

CERTUTIL -f -p somePassword -importpfx "somePfx.pfx"

Import pfx to Trusted People on local machine - Link to importpfx.exe

importpfx.exe -f "somePfx.pfx" -p "somePassword" -t MACHINE -s "TRUSTEDPEOPLE"

Import certificate to Trusted People on local machine

Certutil -addstore -f "TRUSTEDPEOPLE" "someCertificate.cer"

Splitting string with pipe character ("|")

Using Pattern.quote()

String[] value_split = rat_values.split(Pattern.quote("|"));

//System.out.println(Arrays.toString(rat_values.split(Pattern.quote("|")))); //(FOR GETTING OUTPUT)

Using Escape characters(for metacharacters)

String[] value_split = rat_values.split("\\|");
//System.out.println(Arrays.toString(rat_values.split("\\|"))); //(FOR GETTING OUTPUT)

Using StringTokenizer(For avoiding regular expression issues)

public static String[] splitUsingTokenizer(String Subject, String Delimiters) 
{
     StringTokenizer StrTkn = new StringTokenizer(Subject, Delimiters);
     ArrayList<String> ArrLis = new ArrayList<String>(Subject.length());
     while(StrTkn.hasMoreTokens())
     {
       ArrLis.add(StrTkn.nextToken());
     }
     return ArrLis.toArray(new String[0]);
}

Using Pattern class(java.util.regex.Pattern)

Arrays.asList(Pattern.compile("\\|").split(rat_values))
//System.out.println(Arrays.asList(Pattern.compile("\\|").split(rat_values))); //(FOR GETTING OUTPUT)

Output

[Food 1 ,  Service 3 ,  Atmosphere 3 ,  Value for money 1 ]

ASP.NET Web API application gives 404 when deployed at IIS 7

Spend a whole week, after all the following setting worked ! and finally saved. Removing the UrlScan from ISAPI fileters in IIS fixes the problem in our case

Force to open "Save As..." popup open at text link click for PDF in HTML

A very easy way to do this, if you need to force download for a single link on your page, is to use the HTML5 download-attribute in the href-link.

See: http://davidwalsh.name/download-attribute

with this you can rename the file that the user will download and at the same time it forces the download.

There has been a debate whether this is good practice or not, but in my case I have an embedded viewer for a PDF file and the viewer does not offer a download link, so i have to provide one separately. Here I want to make sure the user does not get the PDF opened in the web browser, which would be confusing.

This won't necessary open the save as-dialog, but will download the link straight to the preset download destination. And of course if you are doing a site for someone else, and need them to write in manually attributes to their links is probably a bad idea, but if there is way to get the attribute into the links, this can be a light solution.

How do I run Python script using arguments in windows command line

  • import sys out of hello function.
  • arguments should be converted to int.
  • String literal that contain ' should be escaped or should be surrouned by ".
  • Did you invoke the program with python hello.py <some-number> <some-number> in command line?

import sys

def hello(a,b):
    print "hello and that's your sum:", a + b

if __name__ == "__main__":
    a = int(sys.argv[1])
    b = int(sys.argv[2])
    hello(a, b)

Jquery get form field value

You can get any input field value by $('input[fieldAttribute=value]').val()

here is an example

_x000D_
_x000D_
displayValue = () => {_x000D_
_x000D_
  // you can get the value by name attribute like this_x000D_
  _x000D_
  console.log('value of firstname : ' + $('input[name=firstName]').val());_x000D_
  _x000D_
  // if there is the id as lastname_x000D_
  _x000D_
  console.log('value of lastname by id : ' + $('#lastName').val());_x000D_
  _x000D_
  // get value of carType from placeholder  _x000D_
  console.log('value of carType from placeholder ' + $('input[placeholder=carType]').val());_x000D_
_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<div class="formdiv">_x000D_
    <form name="inpForm">_x000D_
        <input type="text" name="firstName" placeholder='first name'/>_x000D_
        <input type="text" name="lastName" id='lastName' placeholder='last name'/>_x000D_
        _x000D_
        <input type="text" placeholder="carType" />_x000D_
        <input type="button" value="display value" onclick='displayValue()'/>_x000D_
        _x000D_
    </form>_x000D_
</div>
_x000D_
_x000D_
_x000D_

What is the "right" JSON date format?

The prefered way is using 2018-04-23T18:25:43.511Z...

The picture below shows why this is the prefered way:

JSON Date

So as you see Date has a native Method toJSON, which return in this format and can be easily converted to Date again...

Copy a file list as text from Windows Explorer

If you paste the listing into your word processor instead of Notepad, (since each file name is in quotation marks with the full path name), you can highlight all the stuff you don't want on the first file, then use Find and Replace to replace every occurrence of that with nothing. Same with the ending quote (").

It makes a nice clean list of file names.

Maven artifact and groupId naming

However, I disagree the official definition of Guide to naming conventions on groupId, artifactId, and version which proposes the groupId must start with a reversed domain name you control.

com means this project belongs to a company, and org means this project belongs to a social organization. These are alright, but for those strange domain like xxx.tv, xxx.uk, xxx.cn, it does not make sense to name the groupId started with "tv.","cn.", the groupId should deliver the basic information of the project rather than the domain.

Find and copy files

If your intent is to copy the found files into /home/shantanu/tosend, you have the order of the arguments to cp reversed:

find /home/shantanu/processed/ -name '*2011*.xml' -exec cp "{}" /home/shantanu/tosend  \;

Please, note: the find command use {} as placeholder for matched file.

How to change an Android app's name?

change the app string resource to your new activity

Forcing to download a file using PHP

If you are doing it with your application itself... I hope this code helps.

HTML

In href -- you have to add download_file.php along with your URL:

<a class="download" href="'/download_file.php?fileSource='+http://www.google.com/logo_small.png" target="_blank" title="YourTitle">

PHP

/* Here is the Download.php file to force download stuff */

<?php
    $fullPath = $_GET['fileSource'];
    if($fullPath) {
        $fsize = filesize($fullPath);
        $path_parts = pathinfo($fullPath);
        $ext = strtolower($path_parts["extension"]);

        switch ($ext) {
            case "pdf":
                header("Content-Disposition: attachment; filename=\"" . $path_parts["basename"]."\""); // Use 'attachment' to force a download
                header("Content-type: application/pdf"); // Add here more headers for diff. extensions
                break;

            default;
                header("Content-type: application/octet-stream");
                header("Content-Disposition: filename=\"" . $path_parts["basename"]."\"");
        }

        if($fsize) { // Checking if file size exist
            header("Content-length: $fsize");
        }
        readfile($fullPath);
        exit;
    }
?>

How do I get a TextBox to only accept numeric input in WPF?

e.Handled = (int)e.Key >= 43 || (int)e.Key <= 34;

in preview keydown event of textbox.

Where can I get a list of Ansible pre-defined variables?

Some variables are not available on every host, e.g. ansible_domain and domain. If the situation needs to be debugged, I login to the server and issue:

user@server:~$ ansible -m setup localhost | grep domain
 [WARNING]: provided hosts list is empty, only localhost is available
    "ansible_domain": "prd.example.com",

how to convert an RGB image to numpy array?

I also adopted imageio, but I found the following machinery useful for pre- and post-processing:

import imageio
import numpy as np

def imload(*a, **k):
    i = imageio.imread(*a, **k)
    i = i.transpose((1, 0, 2))  # x and y are mixed up for some reason...
    i = np.flip(i, 1)  # make coordinate system right-handed!!!!!!
    return i/255


def imsave(i, url, *a, **k):
    # Original order of arguments was counterintuitive. It should
    # read verbally "Save the image to the URL" — not "Save to the
    # URL the image."

    i = np.flip(i, 1)
    i = i.transpose((1, 0, 2))
    i *= 255

    i = i.round()
    i = np.maximum(i, 0)
    i = np.minimum(i, 255)

    i = np.asarray(i, dtype=np.uint8)

    imageio.imwrite(url, i, *a, **k)

The rationale is that I am using numpy for image processing, not just image displaying. For this purpose, uint8s are awkward, so I convert to floating point values ranging from 0 to 1.

When saving images, I noticed I had to cut the out-of-range values myself, or else I ended up with a really gray output. (The gray output was the result of imageio compressing the full range, which was outside of [0, 256), to values that were inside the range.)

There were a couple other oddities, too, which I mentioned in the comments.

Function to Calculate Median in SQL Server

DECLARE @Obs int
DECLARE @RowAsc table
(
ID      INT IDENTITY,
Observation  FLOAT
)
INSERT INTO @RowAsc
SELECT Observations FROM MyTable
ORDER BY 1 
SELECT @Obs=COUNT(*)/2 FROM @RowAsc
SELECT Observation AS Median FROM @RowAsc WHERE ID=@Obs

stringstream, string, and char* conversion confusion

In this line:

const char* cstr2 = ss.str().c_str();

ss.str() will make a copy of the contents of the stringstream. When you call c_str() on the same line, you'll be referencing legitimate data, but after that line the string will be destroyed, leaving your char* to point to unowned memory.

sqlplus how to find details of the currently connected database session

select * from v$session
where sid = to_number(substr(dbms_session.unique_session_id,1,4),'XXXX')

How a thread should close itself in Java?

If you're at the top level - or able to cleanly get to the top level - of the thread, then just returning is nice. Throwing an exception isn't as clean, as you need to be able to check that nothing's going to catch the exception and ignore it.

The reason you need to use Thread.currentThread() in order to call interrupt() is that interrupt() is an instance method - you need to call it on the thread you want to interrupt, which in your case happens to be the current thread. Note that the interruption will only be noticed the next time the thread would block (e.g. for IO or for a monitor) anyway - it doesn't mean the exception is thrown immediately.

Laravel use same form for create and edit

Instead of creating two methods - one for creating new row and one for updating, you should use findOrNew() method. So:

public function edit(Request $request, $id = 0)
{
    $user = User::findOrNew($id);
    $user->fill($request->all());
    $user->save();
}

Find the max of two or more columns with pandas

@DSM's answer is perfectly fine in almost any normal scenario. But if you're the type of programmer who wants to go a little deeper than the surface level, you might be interested to know that it is a little faster to call numpy functions on the underlying .to_numpy() (or .values for <0.24) array instead of directly calling the (cythonized) functions defined on the DataFrame/Series objects.

For example, you can use ndarray.max() along the first axis.

# Data borrowed from @DSM's post.
df = pd.DataFrame({"A": [1,2,3], "B": [-2, 8, 1]})
df
   A  B
0  1 -2
1  2  8
2  3  1

df['C'] = df[['A', 'B']].values.max(1)
# Or, assuming "A" and "B" are the only columns, 
# df['C'] = df.values.max(1) 
df

   A  B  C
0  1 -2  1
1  2  8  8
2  3  1  3 

If your data has NaNs, you will need numpy.nanmax:

df['C'] = np.nanmax(df.values, axis=1)
df

   A  B  C
0  1 -2  1
1  2  8  8
2  3  1  3 

You can also use numpy.maximum.reduce. numpy.maximum is a ufunc (Universal Function), and every ufunc has a reduce:

df['C'] = np.maximum.reduce(df['A', 'B']].values, axis=1)
# df['C'] = np.maximum.reduce(df[['A', 'B']], axis=1)
# df['C'] = np.maximum.reduce(df, axis=1)
df

   A  B  C
0  1 -2  1
1  2  8  8
2  3  1  3

enter image description here

np.maximum.reduce and np.max appear to be more or less the same (for most normal sized DataFrames)—and happen to be a shade faster than DataFrame.max. I imagine this difference roughly remains constant, and is due to internal overhead (indexing alignment, handling NaNs, etc).

The graph was generated using perfplot. Benchmarking code, for reference:

import pandas as pd
import perfplot

np.random.seed(0)
df_ = pd.DataFrame(np.random.randn(5, 1000))

perfplot.show(
    setup=lambda n: pd.concat([df_] * n, ignore_index=True),
    kernels=[
        lambda df: df.assign(new=df.max(axis=1)),
        lambda df: df.assign(new=df.values.max(1)),
        lambda df: df.assign(new=np.nanmax(df.values, axis=1)),
        lambda df: df.assign(new=np.maximum.reduce(df.values, axis=1)),
    ],
    labels=['df.max', 'np.max', 'np.maximum.reduce', 'np.nanmax'],
    n_range=[2**k for k in range(0, 15)],
    xlabel='N (* len(df))',
    logx=True,
    logy=True)

How to create a simple http proxy in node.js?

Here's a more optimized version of Mike's answer above that gets the websites Content-Type properly, supports POST and GET request, and uses your browsers User-Agent so websites can identify your proxy as a browser. You can just simply set the URL by changing url = and it will automatically set HTTP and HTTPS stuff without manually doing it.

var express = require('express')
var app = express()
var https = require('https');
var http = require('http');
const { response } = require('express');


app.use('/', function(clientRequest, clientResponse) {
    var url;
    url = 'https://www.google.com'
    var parsedHost = url.split('/').splice(2).splice(0, 1).join('/')
    var parsedPort;
    var parsedSSL;
    if (url.startsWith('https://')) {
        parsedPort = 443
        parsedSSL = https
    } else if (url.startsWith('http://')) {
        parsedPort = 80
        parsedSSL = http
    }
    var options = { 
      hostname: parsedHost,
      port: parsedPort,
      path: clientRequest.url,
      method: clientRequest.method,
      headers: {
        'User-Agent': clientRequest.headers['user-agent']
      }
    };  
  
    var serverRequest = parsedSSL.request(options, function(serverResponse) { 
      var body = '';   
      if (String(serverResponse.headers['content-type']).indexOf('text/html') !== -1) {
        serverResponse.on('data', function(chunk) {
          body += chunk;
        }); 
  
        serverResponse.on('end', function() {
          // Make changes to HTML files when they're done being read.
          body = body.replace(`example`, `Cat!` );
  
          clientResponse.writeHead(serverResponse.statusCode, serverResponse.headers);
          clientResponse.end(body);
        }); 
      }   
      else {
        serverResponse.pipe(clientResponse, {
          end: true
        }); 
        clientResponse.contentType(serverResponse.headers['content-type'])
      }   
    }); 
  
    serverRequest.end();
  });    


  app.listen(3000)
  console.log('Running on 0.0.0.0:3000')

enter image description here

enter image description here

How do I get the SQLSRV extension to work with PHP, since MSSQL is deprecated?

Quoting http://php.net/manual/en/intro.mssql.php:

The MSSQL extension is not available anymore on Windows with PHP 5.3 or later. SQLSRV, an alternative driver for MS SQL is available from Microsoft: » http://msdn.microsoft.com/en-us/sqlserver/ff657782.aspx.

Once you downloaded that, follow the instructions at this page:

In a nutshell:

Put the driver file in your PHP extension directory.
Modify the php.ini file to include the driver. For example:

extension=php_sqlsrv_53_nts_vc9.dll  

Restart the Web server.

See Also (copied from that page)

The PHP Manual for the SQLSRV extension is located at http://php.net/manual/en/sqlsrv.installation.php and offers the following for Installation:

The SQLSRV extension is enabled by adding appropriate DLL file to your PHP extension directory and the corresponding entry to the php.ini file. The SQLSRV download comes with several driver files. Which driver file you use will depend on 3 factors: the PHP version you are using, whether you are using thread-safe or non-thread-safe PHP, and whether your PHP installation was compiled with the VC6 or VC9 compiler. For example, if you are running PHP 5.3, you are using non-thread-safe PHP, and your PHP installation was compiled with the VC9 compiler, you should use the php_sqlsrv_53_nts_vc9.dll file. (You should use a non-thread-safe version compiled with the VC9 compiler if you are using IIS as your web server). If you are running PHP 5.2, you are using thread-safe PHP, and your PHP installation was compiled with the VC6 compiler, you should use the php_sqlsrv_52_ts_vc6.dll file.

The drivers can also be used with PDO.

array of string with unknown size

You don't have to specify the size of an array when you instantiate it.

You can still declare the array and instantiate it later. For instance:

string[] myArray;

...

myArray = new string[size];

How to set MimeBodyPart ContentType to "text/html"?

There is a method setText() which takes 3 arguments :

public void setText(String text, String charset, String subtype)
    throws MessagingException

Parameters:

text - the text content to set
charset - the charset to use for the text
subtype - the MIME subtype to use (e.g., "html")

NOTE: the subtype takes text after / in MIME types so for ex.

  • text/html would be html
  • text/css would be css
  • and so on..

Install php-zip on php 5.6 on Ubuntu

Try either

  • sudo apt-get install php-zip or
  • sudo apt-get install php5.6-zip

Then, you might have to restart your web server.

  • sudo service apache2 restart or
  • sudo service nginx restart

If you are installing on centos or fedora OS then use yum in place of apt-get. example:-

sudo yum install php-zip or sudo yum install php5.6-zip and sudo service httpd restart

JavaScript function to add X months to a date

addDateMonate : function( pDatum, pAnzahlMonate )
{
    if ( pDatum === undefined )
    {
        return undefined;
    }

    if ( pAnzahlMonate === undefined )
    {
        return pDatum;
    }

    var vv = new Date();

    var jahr = pDatum.getFullYear();
    var monat = pDatum.getMonth() + 1;
    var tag = pDatum.getDate();

    var add_monate_total = Math.abs( Number( pAnzahlMonate ) );

    var add_jahre = Number( Math.floor( add_monate_total / 12.0 ) );
    var add_monate_rest = Number( add_monate_total - ( add_jahre * 12.0 ) );

    if ( Number( pAnzahlMonate ) > 0 )
    {
        jahr += add_jahre;
        monat += add_monate_rest;

        if ( monat > 12 )
        {
            jahr += 1;
            monat -= 12;
        }
    }
    else if ( Number( pAnzahlMonate ) < 0 )
    {
        jahr -= add_jahre;
        monat -= add_monate_rest;

        if ( monat <= 0 )
        {
            jahr = jahr - 1;
            monat = 12 + monat;
        }
    }

    if ( ( Number( monat ) === 2 ) && ( Number( tag ) === 29 ) )
    {
        if ( ( ( Number( jahr ) % 400 ) === 0 ) || ( ( Number( jahr ) % 100 ) > 0 ) && ( ( Number( jahr ) % 4 ) === 0 ) )
        {
            tag = 29;
        }
        else
        {
            tag = 28;
        }
    }

    return new Date( jahr, monat - 1, tag );
}


testAddMonate : function( pDatum , pAnzahlMonate )
{
    var datum_js = fkDatum.getDateAusTTMMJJJJ( pDatum );
    var ergebnis = fkDatum.addDateMonate( datum_js, pAnzahlMonate );

    app.log( "addDateMonate( \"" + pDatum + "\", " + pAnzahlMonate + " ) = \"" + fkDatum.getStringAusDate( ergebnis ) + "\"" );
},


test1 : function()
{
    app.testAddMonate( "15.06.2010",    10 );
    app.testAddMonate( "15.06.2010",   -10 );
    app.testAddMonate( "15.06.2010",    37 );
    app.testAddMonate( "15.06.2010",   -37 );
    app.testAddMonate( "15.06.2010",  1234 );
    app.testAddMonate( "15.06.2010", -1234 );
    app.testAddMonate( "15.06.2010",  5620 );
    app.testAddMonate( "15.06.2010", -5120 );

}

*ngIf else if in template

_x000D_
_x000D_
<ion-row *ngIf="cat === 1;else second"></ion-row>_x000D_
<ng-template #second>_x000D_
    <ion-row *ngIf="cat === 2;else third"></ion-row>_x000D_
</ng-template>_x000D_
<ng-template #third>_x000D_
_x000D_
</ng-template>
_x000D_
_x000D_
_x000D_

Angular is already using ng-template under the hood in many of the structural directives that we use all the time: ngIf, ngFor and ngSwitch.

> What is ng-template in Angular

https://www.angularjswiki.com/angular/what-is-ng-template-in-angular/

How to pass json POST data to Web API method as an object?

@model MVCClient.Models.ProductDetails

@{
    ViewBag.Title = "ProductDetails";
}
<script src="~/Scripts/jquery-1.8.2.min.js"></script>
<script type="text/javascript">

    $(document).ready(function () {
        $("#Save").click(function () {
            var ProductDetails = new Object();
            ProductDetails.ProductName =  $("#txt_productName").val();
            ProductDetails.ProductDetail = $("#txt_desc").val();
            ProductDetails.Price= $("#txt_price").val();
            $.ajax({
                url: "http://localhost:24481/api/Product/addProduct",
                type: "Post",
                dataType:'JSON',
                data:ProductDetails, 

                success: function (data) {
                    alert('Updated Successfully');
                    //window.location.href = "../Index";
                },
                error: function (msg) { alert(msg); }
            });
        });
    });
    </script>
<h2>ProductDetails</h2>

<form id="form1" method="post">
    <fieldset>
        <legend>ProductDetails</legend>


        <div class="editor-label">
            @Html.LabelFor(model => model.ProductName)
        </div>
        <div class="editor-field">

            <input id="txt_productName" type="text" name="fname">
            @Html.ValidationMessageFor(model => model.ProductName)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.ProductDetail)
        </div>
        <div class="editor-field">

            <input id="txt_desc" type="text" name="fname">
            @Html.ValidationMessageFor(model => model.ProductDetail)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.Price)
        </div>
        <div class="editor-field">

            <input id="txt_price" type="text" name="fname">
            @Html.ValidationMessageFor(model => model.Price)
        </div>



        <p>
            <input id="Save" type="button" value="Create" />
        </p>
    </fieldset>

</form>
    <div>
        @Html.ActionLink("Back to List", "Index")
    </div>

</form>



@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}