Programs & Examples On #Glfw

GLFW is a free, Open Source, multi-platform library for opening a window, creating an OpenGL context and managing input. It is easy to integrate into existing applications and does not lay claim to the main loop. GLFW is written in C and has native support for Windows, Mac OS X and many Unix-like systems using the X Window System, such as Linux and FreeBSD. GLFW is licensed under the zlib/libpng license.

How to build & install GLFW 3 and use it in a Linux project

Note that you do not need that many -ls if you install glfw with the BUILD_SHARED_LIBS option. (You can enable this option by running ccmake first).

This way sudo make install will install the shared library in /usr/local/lib/libglfw.so. You can then compile the example file with a simple:

g++ main.cpp -L /usr/local/lib/ -lglfw

Then do not forget to add /usr/local/lib/ to the search path for shared libraries before running your program. This can be done using:

export LD_LIBRARY_PATH=/usr/local/lib:${LD_LIBRARY_PATH}

And you can put that in your ~/.bashrc so you don't have to type it all the time.

Maintaining href "open in new tab" with an onClick handler in React

The answer from @gunn is correct, target="_blank makes the link open in a new tab.

But this can be a security risk for you page; you can read about it here. There is a simple solution for that: adding rel="noopener noreferrer".

<a style={{display: "table-cell"}} href = "someLink" target = "_blank" 
rel = "noopener noreferrer">text</a>

Could not load file or assembly for Oracle.DataAccess in .NET

As referred to in the first answer, there are 32/64 bit scenarios which introduce build and runtime pitfalls for developers.

The solution is always to try to get right: What kind of software and OS you have installed.

For a small list of scenarios with the Oracle driver and the solution, you can visit this post.

Not showing placeholder for input type="date" field

According to the HTML standard:

The following content attributes must not be specified and do not apply to the element: accept, alt, checked, dirname, formaction, formenctype, formmethod, formnovalidate, formtarget, height, inputmode, maxlength, minlength, multiple, pattern, placeholder, size, src, and width.

Node.js/Express.js App Only Works on Port 3000

In app.js, just add...

process.env.PORT=2999;

This will isolate the PORT variable to the express application.

How merge two objects array in angularjs?

$scope.actions.data.concat is not a function 

same problem with me but i solve the problem by

 $scope.actions.data = [].concat($scope.actions.data , data)

Where are static methods and static variables stored in Java?

Static methods (in fact all methods) as well as static variables are stored in the PermGen section of the heap, since they are part of the reflection data (class related data, not instance related).

Update for clarification:

Note that only the variables and their technical values (primitives or references) are stored in PermGen space.

If your static variable is a reference to an object that object itself is stored in the normal sections of the heap (young/old generation or survivor space). Those objects (unless they are internal objects like classes etc.) are not stored in PermGen space.

Example:

static int i = 1; //the value 1 is stored in the PermGen section
static Object o = new SomeObject(); //the reference(pointer/memory address) is stored in the PermGen section, the object itself is not.


A word on garbage collection:

Do not rely on finalize() as it's not guaranteed to run. It is totally up to the JVM to decide when to run the garbage collector and what to collect, even if an object is eligible for garbage collection.

Of course you can set a static variable to null and thus remove the reference to the object on the heap but that doesn't mean the garbage collector will collect it (even if there are no more references).

Additionally finalize() is run only once, so you have to make sure it doesn't throw exceptions or otherwise prevent the object to be collected. If you halt finalization through some exception, finalize() won't be invoked on the same object a second time.

A final note: how code, runtime data etc. are stored depends on the JVM which is used, i.e. HotSpot might do it differently than JRockit and this might even differ between versions of the same JVM. The above is based on HotSpot for Java 5 and 6 (those are basically the same) since at the time of answering I'd say that most people used those JVMs. Due to major changes in the memory model as of Java 8, the statements above might not be true for Java 8 HotSpot - and I didn't check the changes of Java 7 HotSpot, so I guess the above is still true for that version, but I'm not sure here.

Replace part of a string with another string

If you want to do it quickly you can use a two scan approach. Pseudo code:

  1. first parse. find how many matching chars.
  2. expand the length of the string.
  3. second parse. Start from the end of the string when we get a match we replace, else we just copy the chars from the first string.

I am not sure if this can be optimized to an in-place algo.

And a C++11 code example but I only search for one char.

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

void ReplaceString(string& subject, char search, const string& replace)
{   
    size_t initSize = subject.size();
    int count = 0;
    for (auto c : subject) { 
        if (c == search) ++count;
    }

    size_t idx = subject.size()-1 + count * replace.size()-1;
    subject.resize(idx + 1, '\0');

    string reverseReplace{ replace };
    reverse(reverseReplace.begin(), reverseReplace.end());  

    char *end_ptr = &subject[initSize - 1];
    while (end_ptr >= &subject[0])
    {
        if (*end_ptr == search) {
            for (auto c : reverseReplace) {
                subject[idx - 1] = c;
                --idx;              
            }           
        }
        else {
            subject[idx - 1] = *end_ptr;
            --idx;
        }
        --end_ptr;
    }
}

int main()
{
    string s{ "Mr John Smith" };
    ReplaceString(s, ' ', "%20");
    cout << s << "\n";

}

How can I generate random number in specific range in Android?

Random r = new Random();
int i1 = r.nextInt(80 - 65) + 65;

This gives a random integer between 65 (inclusive) and 80 (exclusive), one of 65,66,...,78,79.

How to download all dependencies and packages to directory

Same question already answered here: How to list/download the recursive dependencies of a debian package?

try:

PACKAGES="wget unzip"
apt-get download $(apt-cache depends --recurse --no-recommends --no-suggests \
  --no-conflicts --no-breaks --no-replaces --no-enhances \
  --no-pre-depends ${PACKAGES} | grep "^\w")

How to extract or unpack an .ab file (Android Backup file)

As per https://android.stackexchange.com/a/78183/239063 you can run a one line command in Linux to add in an appropriate tar header to extract it.

( printf "\x1f\x8b\x08\x00\x00\x00\x00\x00" ; tail -c +25 backup.ab ) | tar xfvz -

Replace backup.ab with the path to your file.

Converting java.util.Properties to HashMap<String,String>

When I see Spring framework source code,I find this way

Properties props = getPropertiesFromSomeWhere();
 // change properties to map
Map<String,String> map = new HashMap(props)

How do I make a WinForms app go Full Screen

To the base question, the following will do the trick (hiding the taskbar)

private void Form1_Load(object sender, EventArgs e)
{
    this.TopMost = true;
    this.FormBorderStyle = FormBorderStyle.None;
    this.WindowState = FormWindowState.Maximized;
}

But, interestingly, if you swap those last two lines the Taskbar remains visible. I think the sequence of these actions will be hard to control with the properties window.

Letter Count on a string

The other answers show what's wrong with your code. But there's also a built-in way to do this, if you weren't just doing this for an exercise:

>>> 'banana'.count('a')
3

Danben gave this corrected version:

def count_letters(word, char):
  count = 0
  for c in word:
    if char == c:
      count += 1
  return count

Here are some other ways to do it, hopefully they will teach you more about Python!

Similar, but shorter for loop. Exploits the fact that booleans can turn into 1 if true and 0 if false:

def count_letters(word, char):
  count = 0
  for c in word:
    count += (char == c)
  return count

Short for loops can generally be turned into list/generator comprehensions. This creates a list of integers corresponding to each letter, with 0 if the letter doesn't match char and 1 if it does, and then sums them:

def count_letters(word, char):
  return sum(char == c for c in word)

The next one filters out all the characters that don't match char, and counts how many are left:

def count_letters(word, char):
  return len([c for c in word if c == char])

How to use <md-icon> in Angular Material?

By Using like
use css and font same location

@font-face {
    font-family: 'Material-Design-Icons';
    src: url('Material-Design-Icons.eot');
    src: url('Material-Design-Icons.eot?#iefix') format('embedded-opentype'),
         url('Material-Design-Icons.woff2') format('woff2'),
         url('Material-Design-Icons.woff') format('woff'),
         url('Material-Design-Icons.ttf') format('truetype'),
         url('Material-Design-Icons.svg#ge_dinar_oneregular') format('svg');
    font-weight: normal;
    font-style: normal;
}

Java: how to convert HashMap<String, Object> to array

If you want the keys and values, you can always do this via the entrySet:

hashMap.entrySet().toArray(); // returns a Map.Entry<K,V>[]

From each entry you can (of course) get both the key and value via the getKey and getValue methods

using .join method to convert array to string without commas

The .join() method has a parameter for the separator string. If you want it to be empty instead of the default comma, use

arr.join("");

Will iOS launch my app into the background if it was force-quit by the user?

Actually if you need to test background fetch you need to enable one option in scheme:

enabling bg fetch

Another way how you can test it: simulate bg fetch

Here is full information about this new feature: http://www.objc.io/issue-5/multitasking.html

How to predict input image using trained model in Keras?

You can use model.predict() to predict the class of a single image as follows [doc]:

# load_model_sample.py
from keras.models import load_model
from keras.preprocessing import image
import matplotlib.pyplot as plt
import numpy as np
import os


def load_image(img_path, show=False):

    img = image.load_img(img_path, target_size=(150, 150))
    img_tensor = image.img_to_array(img)                    # (height, width, channels)
    img_tensor = np.expand_dims(img_tensor, axis=0)         # (1, height, width, channels), add a dimension because the model expects this shape: (batch_size, height, width, channels)
    img_tensor /= 255.                                      # imshow expects values in the range [0, 1]

    if show:
        plt.imshow(img_tensor[0])                           
        plt.axis('off')
        plt.show()

    return img_tensor


if __name__ == "__main__":

    # load model
    model = load_model("model_aug.h5")

    # image path
    img_path = '/media/data/dogscats/test1/3867.jpg'    # dog
    #img_path = '/media/data/dogscats/test1/19.jpg'      # cat

    # load a single image
    new_image = load_image(img_path)

    # check prediction
    pred = model.predict(new_image)

In this example, a image is loaded as a numpy array with shape (1, height, width, channels). Then, we load it into the model and predict its class, returned as a real value in the range [0, 1] (binary classification in this example).

Can Windows' built-in ZIP compression be scripted?

There are both zip and unzip executables (as well as a boat load of other useful applications) in the UnxUtils package available on SourceForge (http://sourceforge.net/projects/unxutils). Copy them to a location in your PATH, such as 'c:\windows', and you will be able to include them in your scripts.

This is not the perfect solution (or the one you asked for) but a decent work-a-round.

Best way to integrate Python and JavaScript?

Use Js2Py to translate JavaScript to Python, this is the only tool available :)

How to convert string into float in JavaScript?

I had the same problem except I did not know in advance what were the thousands separators and the decimal separator. I ended up writing a library to do this. If you are interested it here it is : https://github.com/GuillaumeLeclerc/number-parsing

Reading from stdin

You can do something like this to read 10 bytes:

char buffer[10];
read(STDIN_FILENO, buffer, 10);

remember read() doesn't add '\0' to terminate to make it string (just gives raw buffer).

To read 1 byte at a time:

char ch;
while(read(STDIN_FILENO, &ch, 1) > 0)
{
 //do stuff
}

and don't forget to #include <unistd.h>, STDIN_FILENO defined as macro in this file.

There are three standard POSIX file descriptors, corresponding to the three standard streams, which presumably every process should expect to have:

Integer value   Name
       0        Standard input (stdin)
       1        Standard output (stdout)
       2        Standard error (stderr)

So instead STDIN_FILENO you can use 0.

Edit:
In Linux System you can find this using following command:

$ sudo grep 'STDIN_FILENO' /usr/include/* -R | grep 'define'
/usr/include/unistd.h:#define   STDIN_FILENO    0   /* Standard input.  */

Notice the comment /* Standard input. */

How to connect to mysql with laravel?

Laravel makes it very easy to manage your database connections through app/config/database.php.

As you noted, it is looking for a database called 'database'. The reason being that this is the default name in the database configuration file.

'mysql' => array(
    'driver'    => 'mysql',
    'host'      => 'localhost',
    'database'  => 'database', <------ Default name for database
    'username'  => 'root',
    'password'  => '',
    'charset'   => 'utf8',
    'collation' => 'utf8_unicode_ci',
    'prefix'    => '',
),

Change this to the name of the database that you would like to connect to like this:

'mysql' => array(
    'driver'    => 'mysql',
    'host'      => 'localhost',
    'database'  => 'my_awesome_data', <------ change name for database
    'username'  => 'root',            <------ remember credentials
    'password'  => '',
    'charset'   => 'utf8',
    'collation' => 'utf8_unicode_ci',
    'prefix'    => '',
),

Once you have this configured correctly you will easily be able to access your database!

Happy Coding!

How to redirect the output of DBMS_OUTPUT.PUT_LINE to a file?

Try This:

SELECT systimestamp INTO time_db FROM dual ;

DBMS_OUTPUT.PUT_LINE('time before procedure ' || time_db);

Read file line by line using ifstream in C++

Use ifstream to read data from a file:

std::ifstream input( "filename.ext" );

If you really need to read line by line, then do this:

for( std::string line; getline( input, line ); )
{
    ...for each line in input...
}

But you probably just need to extract coordinate pairs:

int x, y;
input >> x >> y;

Update:

In your code you use ofstream myfile;, however the o in ofstream stands for output. If you want to read from the file (input) use ifstream. If you want to both read and write use fstream.

How to monitor the memory usage of Node.js?

On Linux/Unix (note: Mac OS is a Unix) use top and press M (Shift+M) to sort processes by memory usage.

On Windows use the Task Manager.

Using CRON jobs to visit url?

Here is simple example. you can use it like

wget -q -O - http://example.com/backup >/dev/null 2>&1

and in start you can add your option like (*****). Its up to your system requirements either you want to run it every minute or hours etc.

C#/Linq: Apply a mapping function to each element in an IEnumerable?

You're looking for Select which can be used to transform\project the input sequence:

IEnumerable<string> strings = integers.Select(i => i.ToString());

How can I implement the Iterable interface?

Iterable is a generic interface. A problem you might be having (you haven't actually said what problem you're having, if any) is that if you use a generic interface/class without specifying the type argument(s) you can erase the types of unrelated generic types within the class. An example of this is in Non-generic reference to generic class results in non-generic return types.

So I would at least change it to:

public class ProfileCollection implements Iterable<Profile> { 
    private ArrayList<Profile> m_Profiles;

    public Iterator<Profile> iterator() {        
        Iterator<Profile> iprof = m_Profiles.iterator();
        return iprof; 
    }

    ...

    public Profile GetActiveProfile() {
        return (Profile)m_Profiles.get(m_ActiveProfile);
    }
}

and this should work:

for (Profile profile : m_PC) {
    // do stuff
}

Without the type argument on Iterable, the iterator may be reduced to being type Object so only this will work:

for (Object profile : m_PC) {
    // do stuff
}

This is a pretty obscure corner case of Java generics.

If not, please provide some more info about what's going on.

Nodemailer with Gmail and NodeJS

For me is working this way, using port and security (I had issues to send emails from gmail using PHP without security settings)

I hope will help someone.

var sendEmail = function(somedata){
  var smtpConfig = {
    host: 'smtp.gmail.com',
    port: 465,
    secure: true, // use SSL, 
                  // you can try with TLS, but port is then 587
    auth: {
      user: '***@gmail.com', // Your email id
      pass: '****' // Your password
    }
  };

  var transporter = nodemailer.createTransport(smtpConfig);
  // replace hardcoded options with data passed (somedata)
  var mailOptions = {
    from: '[email protected]', // sender address
    to: '[email protected]', // list of receivers
    subject: 'Test email', // Subject line
    text: 'this is some text', //, // plaintext body
    html: '<b>Hello world ?</b>' // You can choose to send an HTML body instead
  }

  transporter.sendMail(mailOptions, function(error, info){
    if(error){
      return false;
    }else{
      console.log('Message sent: ' + info.response);
      return true;
    };
  });
}

exports.contact = function(req, res){
   // call sendEmail function and do something with it
   sendEmail(somedata);
}

all the config are listed here (including examples)

What is the proper way to format a multi-line dict in Python?

dict(rank = int(lst[0]),
                grade = str(lst[1]),
                channel=str(lst[2])),
                videos = float(lst[3].replace(",", " ")),
                subscribers = float(lst[4].replace(",", "")),
                views = float(lst[5].replace(",", "")))

How do I remove a MySQL database?

If you are using an SQL script when you are creating your database and have any users created by your script, you need to drop them too. Lastly you need to flush the users; i.e., force MySQL to read the user's privileges again.

-- DELETE ALL RECIPE

drop schema <database_name>;
-- Same as `drop database <database_name>`

drop user <a_user_name>;
-- You may need to add a hostname e.g `drop user bob@localhost`

FLUSH PRIVILEGES;

Good luck!

HTTP Error 500.19 and error code : 0x80070021

In my case, there were rules for IIS URL Rewrite module but I didn't have that module installed. You should check your web.config if there are any modules included but not installed.

How can I dynamically set the position of view in Android?

For support to all API levels you can use it like this:

ViewPropertyAnimator.animate(view).translationYBy(-yourY).translationXBy(-yourX).setDuration(0);

PHP header() redirect with POST variables

// from http://wezfurlong.org/blog/2006/nov/http-post-from-php-without-curl
function do_post_request($url, $data, $optional_headers = null)
{
  $params = array('http' => array(
              'method' => 'POST',
              'content' => $data
            ));
  if ($optional_headers !== null) {
    $params['http']['header'] = $optional_headers;
  }
  $ctx = stream_context_create($params);
  $fp = @fopen($url, 'rb', false, $ctx);
  if (!$fp) {
    throw new Exception("Problem with $url, $php_errormsg");
  }
  $response = @stream_get_contents($fp);
  if ($response === false) {
    throw new Exception("Problem reading data from $url, $php_errormsg");
  }
  return $response;
}

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

After struggling with various techniques for a couple of days I have to say that this appears to be impossible. Even using javascript (which I don't want to do) it doesn't seem possible.

To clarify for those who may not have understood - this is what I am looking for: in publishing it is quite common to layout an inset (picture, table, figure, etc.) so that its bottom lines up with the bottom of the last line of text of a block (or page) with text flowing around the inset in a natural manner above and to the right or left depending on which side of the page the inset is on. In html/css it is trivial to use the float style to line up the top of an inset with the top of a block but to my surprise it appears impossible to line up the bottom of the text and inset despite it being a common layout task.

I guess I'll have to revisit the design goals for this item unless anyone has a last minute suggestion.

sprintf like functionality in Python

I'm not completely certain that I understand your goal, but you can use a StringIO instance as a buffer:

>>> import StringIO 
>>> buf = StringIO.StringIO()
>>> buf.write("A = %d, B = %s\n" % (3, "bar"))
>>> buf.write("C=%d\n" % 5)
>>> print(buf.getvalue())
A = 3, B = bar
C=5

Unlike sprintf, you just pass a string to buf.write, formatting it with the % operator or the format method of strings.

You could of course define a function to get the sprintf interface you're hoping for:

def sprintf(buf, fmt, *args):
    buf.write(fmt % args)

which would be used like this:

>>> buf = StringIO.StringIO()
>>> sprintf(buf, "A = %d, B = %s\n", 3, "foo")
>>> sprintf(buf, "C = %d\n", 5)
>>> print(buf.getvalue())
A = 3, B = foo
C = 5

Filtering a spark dataframe based on date

I find the most readable way to express this is using a sql expression:

df.filter("my_date < date'2015-01-01'")

we can verify this works correctly by looking at the physical plan from .explain()

+- *(1) Filter (isnotnull(my_date#22) && (my_date#22 < 16436))

Deserialize JSON with Jackson into Polymorphic Types - A Complete Example is giving me a compile error

You need only one line before the declaration of the class Animal for correct polymorphic serialization/deserialization:

@JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.PROPERTY, property = "@class")
public abstract class Animal {
   ...
}

This line means: add a meta-property on serialization or read a meta-property on deserialization (include = JsonTypeInfo.As.PROPERTY) called "@class" (property = "@class") that holds the fully-qualified Java class name (use = JsonTypeInfo.Id.CLASS).

So, if you create a JSON directly (without serialization) remember to add the meta-property "@class" with the desired class name for correct deserialization.

More information here

random number generator between 0 - 1000 in c#

Use this:

static int RandomNumber(int min, int max)
{
    Random random = new Random(); return random.Next(min, max);

}

This is example for you to modify and use in your application.

Using margin / padding to space <span> from the rest of the <p>

Overall just add display:block; to your span. You can leave your html unchanged.

Demo

You can do it with the following css:

p {
    font-size:24px; 
    font-weight: 300; 
    -webkit-font-smoothing: subpixel-antialiased; 
    margin-top:0px;
}

p span {
    font-size:16px; 
    font-style: italic; 
    margin-top:20px; 
    padding-left:10px; 
    display:inline-block;
}

Add new row to excel Table (VBA)

Tbl.ListRows.Add doesn't work for me and I believe lot others are facing the same problem. I use the following workaround:

    'First check if the last row is empty; if not, add a row
    If table.ListRows.count > 0 Then
        Set lastRow = table.ListRows(table.ListRows.count).Range
        For col = 1 To lastRow.Columns.count
            If Trim(CStr(lastRow.Cells(1, col).Value)) <> "" Then
                lastRow.Cells(1, col).EntireRow.Insert
                'Cut last row and paste to second last
                lastRow.Cut Destination:=table.ListRows(table.ListRows.count - 1).Range
                Exit For
            End If
        Next col
    End If

    'Populate last row with the form data
    Set lastRow = table.ListRows(table.ListRows.count).Range
    Range("E7:E10").Copy
    lastRow.PasteSpecial Transpose:=True
    Range("E7").Select
    Application.CutCopyMode = False

Hope it helps someone out there.

Beginner Python Practice?

You may be interested in Python interactive tutorial for begginers and advance users , it has many available practices together with interactive interface + advance development tricks for advance users.

Angular 2.0 router not working on reloading the browser

I fixed this (using Java / Spring backend) by adding a handler that matches everything defined in my Angular routes, that sends back index.html instead of a 404. This then effectively (re)bootstraps the application and loads the correct page. I also have a 404 handler for anything that isn't caught by this.

@Controller         ////don't use RestController or it will just send back the string "index.html"
public class Redirect {

    private static final Logger logger = LoggerFactory.getLogger(Redirect.class);

    @RequestMapping(value = {"comma", "sep", "list", "of", "routes"})
    public String redirectToIndex(HttpServletRequest request) {
        logger.warn("Redirect api called for URL {}. Sending index.html back instead. This will happen on a page refresh or reload when the page is on an Angular route", request.getRequestURL());
        return "/index.html";
    }
}

Python, add items from txt file into a list

names=[line.strip() for line in open('names.txt')]

Where to declare variable in react js

Assuming that onMove is an event handler, it is likely that its context is something other than the instance of MyContainer, i.e. this points to something different.

You can manually bind the context of the function during the construction of the instance via Function.bind:

class MyContainer extends Component {
  constructor(props) {
    super(props);

    this.onMove = this.onMove.bind(this);

    this.test = "this is a test";
  }

  onMove() {
    console.log(this.test);
  }
}

Also, test !== testVariable.

How to find a value in an array and remove it by using PHP array functions?

Just in case you want to use any of mentioned codes, be aware that array_search returns FALSE when the "needle" is not found in "haystack" and therefore these samples would unset the first (zero-indexed) item. Use this instead:

<?php
$haystack = Array('one', 'two', 'three');
if (($key = array_search('four', $haystack)) !== FALSE) {
  unset($haystack[$key]);
}
var_dump($haystack);

The above example will output:

Array
(
    [0] => one
    [1] => two
    [2] => three
)

And that's good!

TypeError: ufunc 'add' did not contain a loop with signature matching types

You have a numpy array of strings, not floats. This is what is meant by dtype('<U9') -- a little endian encoded unicode string with up to 9 characters.

try:

return sum(np.asarray(listOfEmb, dtype=float)) / float(len(listOfEmb))

However, you don't need numpy here at all. You can really just do:

return sum(float(embedding) for embedding in listOfEmb) / len(listOfEmb)

Or if you're really set on using numpy.

return np.asarray(listOfEmb, dtype=float).mean()

Pseudo-terminal will not be allocated because stdin is not a terminal

After reading a lot of these answers I thought I would share my resulting solution. All I added is /bin/bash before the heredoc and it doesn't give the error anymore.

Use this:

ssh user@machine /bin/bash <<'ENDSSH'
   hostname
ENDSSH

Instead of this (gives error):

ssh user@machine <<'ENDSSH'
   hostname
ENDSSH

Or use this:

ssh user@machine /bin/bash < run-command.sh

Instead of this (gives error):

ssh user@machine < run-command.sh

EXTRA:

If you still want a remote interactive prompt e.g. if the script you're running remotely prompts you for a password or other information, because the previous solutions won't allow you to type into the prompts.

ssh -t user@machine "$(<run-command.sh)"

And if you also want to log the entire session in a file logfile.log:

ssh -t user@machine "$(<run-command.sh)" | tee -a logfile.log

"Default Activity Not Found" on Android Studio upgrade

100% working

You must be seeing this

enter image description here

First open your manifest and check if this present,

  <activity
      android:name="com.your.package.name.YourActivity"
      android:label="@string/app_name">
       <intent-filter>
           <action android:name="android.intent.action.MAIN" />
           <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
   </activity>

If not present add it

If the above is present but still you see default activity not found.

Follow these steps:

1. Click edit configuration

enter image description here

2. On clicking edit configuration you'll see that launch option is set on DEFAULT ACTIVITY

enter image description here

  1. Change it to nothing.

enter image description here

Problem solved!

Happy Coding.

PreparedStatement setNull(..)

You could also consider using preparedStatement.setObject(index,value,type);

Mysql Compare two datetime fields

The query you want to show as an example is:

SELECT * FROM temp WHERE mydate > '2009-06-29 16:00:44';

04:00:00 is 4AM, so all the results you're displaying come after that, which is correct.

If you want to show everything after 4PM, you need to use the correct (24hr) notation in your query.

To make things a bit clearer, try this:

SELECT mydate, DATE_FORMAT(mydate, '%r') FROM temp;

That will show you the date, and its 12hr time.

Set encoding and fileencoding to utf-8 in Vim

You can set the variable 'fileencodings' in your .vimrc.

This is a list of character encodings considered when starting to edit an existing file. When a file is read, Vim tries to use the first mentioned character encoding. If an error is detected, the next one in the list is tried. When an encoding is found that works, 'fileencoding' is set to it. If all fail, 'fileencoding' is set to an empty string, which means the value of 'encoding' is used.

See :help filencodings

If you often work with e.g. cp1252, you can add it there:

set fileencodings=ucs-bom,utf-8,cp1252,default,latin9

VB.NET - Click Submit Button on Webbrowser page

I am quite benefited with http://stackoverflow.com. I was wandering from hours for automatic login and submit from vb application to another web site. Due to help of this site I am able to complete my task

I have to login following web php page.

<HTML>

<body>
<div align="center"><img src="banner.png" height="80px" /></div>
<script type="text/javascript">
$(document).ready(function(){
            $("#login").validate();
            $("#login_container").css({'position': 'absolute', 
                'top' : (($(window).height()/2) - $("#login_container").height()/2)+'px'});
            $("#login_container").css({'left' : (($(window).width()/2) - $("#login_container").width()/2)+'px'});
        });
    </script>
    <div id="login_container">
        <form name="login" id="login" action="?q=login" method="post">
        <table>
          <tr><td>Username</td><td><input type="text" name="name" class="required"/></td></tr>
          <tr><td>Password</td><td><input type="password" name="password" class="required"/></td></tr>
          <tr><td></td><td><input type="submit" name="subimt" value="Login" /></td></tr>
        </table>
        </form>
    </div>
</body>
</html>

For automatic Login and clicking I wrote following VB.Net Code. In form1 I placed a button and a Webbrowser control

Imports System.IO
Imports System.Windows.Forms



Public Class Form1


    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click


        WebBrowser1.Navigate("http://xyz.com")



    End Sub

    Private Sub WebBrowser1_DocumentCompleted(ByVal sender As Object, ByVal e As System.Windows.Forms.WebBrowserDocumentCompletedEventArgs) Handles WebBrowser1.DocumentCompleted
        WebBrowser1.Document.GetElementById("name").SetAttribute("Value", "bharatlal")
        WebBrowser1.Document.GetElementById("password").SetAttribute("Value", "mahato")
        WebBrowser1.Document.GetElementById("subimt").Focus()
        WebBrowser1.Document.GetElementById("subimt").InvokeMember("click")
    End Sub
End Class

comparing two strings in SQL Server

There is no direct string compare function in SQL Server

CASE
  WHEN str1 = str2 THEN 0
  WHEN str1 < str2 THEN -1
  WHEN str1 > str2 THEN 1
  ELSE NULL --one of the strings is NULL so won't compare (added on edit)
END

Notes

  • you can wraps this via a UDF using CREATE FUNCTION etc
  • you may need NULL handling (in my code above, any NULL will report 1)
  • str1 and str2 will be column names or @variables

How do I remove repeated elements from ArrayList?

If you're willing to use a third-party library, you can use the method distinct() in Eclipse Collections (formerly GS Collections).

ListIterable<Integer> integers = FastList.newListWith(1, 3, 1, 2, 2, 1);
Assert.assertEquals(
    FastList.newListWith(1, 3, 2),
    integers.distinct());

The advantage of using distinct() instead of converting to a Set and then back to a List is that distinct() preserves the order of the original List, retaining the first occurrence of each element. It's implemented by using both a Set and a List.

MutableSet<T> seenSoFar = UnifiedSet.newSet();
int size = list.size();
for (int i = 0; i < size; i++)
{
    T item = list.get(i);
    if (seenSoFar.add(item))
    {
        targetCollection.add(item);
    }
}
return targetCollection;

If you cannot convert your original List into an Eclipse Collections type, you can use ListAdapter to get the same API.

MutableList<Integer> distinct = ListAdapter.adapt(integers).distinct();

Note: I am a committer for Eclipse Collections.

How to delete columns that contain ONLY NAs?

One way of doing it:

df[, colSums(is.na(df)) != nrow(df)]

If the count of NAs in a column is equal to the number of rows, it must be entirely NA.

Or similarly

df[colSums(!is.na(df)) > 0]

How can I check the system version of Android?

Given you have bash on your android device, you can use this bash function :

function androidCodeName {
    androidRelease=$(getprop ro.build.version.release)
    androidCodeName=$(getprop ro.build.version.codename)

    # Time "androidRelease" x10 to test it as an integer
    case $androidRelease in
        [0-9].[0-9]|[0-9].[0-9].|[0-9].[0-9].[0-9])  androidRelease=$(echo $androidRelease | cut -d. -f1-2 | tr -d .);;
        [0-9].) androidRelease=$(echo $androidRelease | sed 's/\./0/');;
        [0-9]) androidRelease+="0";;
    esac

    [ -n "$androidRelease" ] && [ $androidCodeName = REL ] && {
    # Do not use "androidCodeName" when it equals to "REL" but infer it from "androidRelease"
        androidCodeName=""
        case $androidRelease in
        10) androidCodeName+=NoCodename;;
        11) androidCodeName+="Petit Four";;
        15) androidCodeName+=Cupcake;;
        20|21) androidCodeName+=Eclair;;
        22) androidCodeName+=FroYo;;
        23) androidCodeName+=Gingerbread;;
        30|31|32) androidCodeName+=Honeycomb;;
        40) androidCodeName+="Ice Cream Sandwich";;
        41|42|43) androidCodeName+="Jelly Bean";;
        44) androidCodeName+=KitKat;;
        50|51) androidCodeName+=Lollipop;;
        60) androidCodeName+=Marshmallow;;
        70|71) androidCodeName+=Nougat;;
        80|81) androidCodeName+=Oreo;;
        90) androidCodeName+=Pie;;
        100) androidCodeName+=ToBeReleased;;
        *) androidCodeName=unknown;;
        esac
    }
    echo $androidCodeName
}

Comparing two arrays of objects, and exclude the elements who match values into new array in JS

I have searched a lot for a solution in which I can compare two array of objects with different attribute names (something like a left outer join). I came up with this solution. Here I used Lodash. I hope this will help you.

var Obj1 = [
    {id:1, name:'Sandra'},
    {id:2, name:'John'},   
];

var Obj2 = [
    {_id:2, name:'John'},
    {_id:4, name:'Bobby'}
];

var Obj3 = lodash.differenceWith(Obj1, Obj2, function (o1, o2) {
    return o1['id'] === o2['_id']
});

console.log(Obj3);
//  {id:1, name:'Sandra'}

CSS: create white glow around image

Depends on what your target browsers are. In newer ones it's as simple as:

   -moz-box-shadow: 0 0 5px #fff;
-webkit-box-shadow: 0 0 5px #fff;
        box-shadow: 0 0 5px #fff;

For older browsers you have to implement workarounds, e.g., based on this example, but you will most probably need extra mark-up.

Plotting a list of (x, y) coordinates in python matplotlib

If you want to plot a single line connecting all the points in the list

plt.plot(li[:])

plt.show()

This will plot a line connecting all the pairs in the list as points on a Cartesian plane from the starting of the list to the end. I hope that this is what you wanted.

How can I get a specific number child using CSS?

For IE 7 & 8 (and other browsers without CSS3 support not including IE6) you can use the following to get the 2nd and 3rd children:

2nd Child:

td:first-child + td

3rd Child:

td:first-child + td + td

Then simply add another + td for each additional child you wish to select.

If you want to support IE6 that can be done too! You simply need to use a little javascript (jQuery in this example):

$(function() {
    $('td:first-child').addClass("firstChild");
    $(".table-class tr").each(function() {
        $(this).find('td:eq(1)').addClass("secondChild");
        $(this).find('td:eq(2)').addClass("thirdChild");
    });
});

Then in your css you simply use those class selectors to make whatever changes you like:

table td.firstChild { /*stuff here*/ }
table td.secondChild { /*stuff to apply to second td in each row*/ }

AltGr key not working, instead I have to use Ctrl+AltGr

I found a solution for my problem while writing my question !

Going into my remote session i tried two key combinations, and it solved the problem on my Desktop : Alt+Enter and Ctrl+Enter (i don't know which one solved the problem though)

I tried to reproduce the problem, but i couldn't... but i'm almost sure it's one of the key combinations described in the question above (since i experienced this problem several times)

So it seems the problem comes from the use of RDP (windows7 and 8)

Update 2017: Problem occurs on Windows 10 aswell.

Sort Go map values by keys

This provides you the code example on sorting map. Basically this is what they provide:

var keys []int
for k := range myMap {
    keys = append(keys, k)
}
sort.Ints(keys)

// Benchmark1-8      2863149           374 ns/op         152 B/op          5 allocs/op

and this is what I would suggest using instead:

keys := make([]int, 0, len(myMap))
for k := range myMap {
    keys = append(keys, k)
}
sort.Ints(keys)

// Benchmark2-8      5320446           230 ns/op          80 B/op          2 allocs/op

Full code can be found in this Go Playground.

Build the full path filename in Python

Just use os.path.join to join your path with the filename and extension. Use sys.argv to access arguments passed to the script when executing it:

#!/usr/bin/env python3
# coding: utf-8

# import netCDF4 as nc
import numpy as np
import numpy.ma as ma
import csv as csv

import os.path
import sys

basedir = '/data/reu_data/soil_moisture/'
suffix = 'nc'


def read_fid(filename):
    fid = nc.MFDataset(filename,'r')
    fid.close()
    return fid

def read_var(file, varname):
    fid = nc.Dataset(file, 'r')
    out = fid.variables[varname][:]
    fid.close()
    return out


if __name__ == '__main__':
    if len(sys.argv) < 2:
        print('Please specify a year')

    else:
        filename = os.path.join(basedir, '.'.join((sys.argv[1], suffix)))
        time = read_var(ncf, 'time')
        lat = read_var(ncf, 'lat')
        lon = read_var(ncf, 'lon')
        soil = read_var(ncf, 'soilw')

Simply run the script like:

   # on windows-based systems
   python script.py year

   # on unix-based systems
   ./script.py year

Does JavaScript have a built in stringbuilder class?

That code looks like the route you want to take with a few changes.

You'll want to change the append method to look like this. I've changed it to accept the number 0, and to make it return this so you can chain your appends.

StringBuilder.prototype.append = function (value) {
    if (value || value === 0) {
        this.strings.push(value);
    }
    return this;
}

Best way to represent a fraction in Java?

Please make it an immutable type! The value of a fraction doesn't change - a half doesn't become a third, for example. Instead of setDenominator, you could have withDenominator which returns a new fraction which has the same numerator but the specified denominator.

Life is much easier with immutable types.

Overriding equals and hashcode would be sensible too, so it can be used in maps and sets. Outlaw Programmer's points about arithmetic operators and string formatting are good too.

As a general guide, have a look at BigInteger and BigDecimal. They're not doing the same thing, but they're similar enough to give you good ideas.

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'id' in 'where clause' (SQL: select * from `songs` where `id` = 5 limit 1)

When you use find(), it automatically assumes your primary key column is going to be id. In order for this to work correctly, you should set your primary key in your model.

So in Song.php, within the class, add the line...

protected $primaryKey = 'SongID';

If there is any possibility of changing your schema, I'd highly recommend naming all your primary key columns id, it's what Laravel assumes and will probably save you from more headaches down the road.

Should I always use a parallel stream when possible?

I watched one of the presentations of Brian Goetz (Java Language Architect & specification lead for Lambda Expressions). He explains in detail the following 4 points to consider before going for parallelization:

Splitting / decomposition costs
– Sometimes splitting is more expensive than just doing the work!
Task dispatch / management costs
– Can do a lot of work in the time it takes to hand work to another thread.
Result combination costs
– Sometimes combination involves copying lots of data. For example, adding numbers is cheap whereas merging sets is expensive.
Locality
– The elephant in the room. This is an important point which everyone may miss. You should consider cache misses, if a CPU waits for data because of cache misses then you wouldn't gain anything by parallelization. That's why array-based sources parallelize the best as the next indices (near the current index) are cached and there are fewer chances that CPU would experience a cache miss.

He also mentions a relatively simple formula to determine a chance of parallel speedup.

NQ Model:

N x Q > 10000

where,
N = number of data items
Q = amount of work per item

HTML5 textarea placeholder not appearing

its because there is a space somewhere. I was using jsfiddle and there was a space after the tag. After I deleted the space it started working

Git: Find the most recent common ancestor of two branches

As noted in a prior answer, although git merge-base works,

$ git merge-base myfeature develop
050dc022f3a65bdc78d97e2b1ac9b595a924c3f2

If myfeature is the current branch, as is common, you can use --fork-point:

$ git merge-base --fork-point develop
050dc022f3a65bdc78d97e2b1ac9b595a924c3f2

This argument works only in sufficiently recent versions of git. Unfortunately it doesn't always work, however, and it is not clear why. Please refer to the limitations noted toward the end of this answer.


For full commit info, consider:

$ git log -1 $(git merge-base --fork-point develop) 

Using HTML and Local Images Within UIWebView

I had a simmilar problem, but all the suggestions didn't help.

However, the problem was the *.png itself. It had no alpha channel. Somehow Xcode ignores all png files without alpha channel during the deploy process.

How to convert array values to lowercase in PHP?

Hi, try this solution. Simple use php array map

function myfunction($value)
{
 return strtolower($value);
}

$new_array = ["Value1","Value2","Value3" ];
print_r(array_map("myfunction",$new_array ));

Output Array ( [0] => value1 [1] => value2 [2] => value3 )

Unable to show a Git tree in terminal

Keeping your commands short will make them easier to remember:

git log --graph --oneline

How to sort List of objects by some property

Java-8 solution using Stream API:

A. When timeStarted and timeEnded are public (as mentioned in the requirement) and therefore do not (need to) have public getter methods:

List<ActiveAlarm> sorted = 
    list.stream()
        .sorted(Comparator.comparingLong((ActiveAlarm alarm) -> alarm.timeStarted)
                        .thenComparingLong((ActiveAlarm alarm) -> alarm.timeEnded))
        .collect(Collectors.toList());

B. When timeStarted and timeEnded have public getter methods:

List<ActiveAlarm> sorted = 
    list.stream()
        .sorted(Comparator.comparingLong(ActiveAlarm::getTimeStarted)
                        .thenComparingLong(ActiveAlarm::getTimeEnded))
        .collect(Collectors.toList());

If you want to sort the original list itself:

A. When timeStarted and timeEnded are public (as mentioned in the requirement) and therefore do not (need to) have public getter methods:

list.sort(Comparator.comparingLong((ActiveAlarm alarm) -> alarm.timeStarted)
                    .thenComparingLong((ActiveAlarm alarm) -> alarm.timeEnded));

B. When timeStarted and timeEnded have public getter methods:

list.sort(Comparator.comparingLong(ActiveAlarm::getTimeStarted)
                    .thenComparingLong(ActiveAlarm::getTimeEnded));

FIFO based Queue implementations?

A LinkedList can be used as a Queue - but you need to use it right. Here is an example code :

@Test
public void testQueue() {
    LinkedList<Integer> queue = new LinkedList<>();
    queue.add(1);
    queue.add(2);
    System.out.println(queue.pop());
    System.out.println(queue.pop());
}

Output :

1
2

Remember, if you use push instead of add ( which you will very likely do intuitively ), this will add element at the front of the list, making it behave like a stack.

So this is a Queue only if used in conjunction with add.

Try this :

@Test
public void testQueue() {
    LinkedList<Integer> queue = new LinkedList<>();
    queue.push(1);
    queue.push(2);
    System.out.println(queue.pop());
    System.out.println(queue.pop());
}

Output :

2
1

"Actual or formal argument lists differs in length"

Say you have defined your class like this:

    @Data
    @AllArgsConstructor(staticName = "of")
    private class Pair<P,Q> {

        public P first;
        public Q second;
    }

So when you will need to create a new instance, it will need to take the parameters and you will provide it like this as defined in the annotation.

Pair<Integer, String> pair = Pair.of(menuItemId, category);

If you define it like this, you will get the error asked for.

Pair<Integer, String> pair = new Pair(menuItemId, category);

Is if(document.getElementById('something')!=null) identical to if(document.getElementById('something'))?

document.getElementById('something') can be 'undefined'. Usually (thought not always) it's sufficient to do tests like if (document.getElementById('something')).

Fatal error in launcher: Unable to create process using ""C:\Program Files (x86)\Python33\python.exe" "C:\Program Files (x86)\Python33\pip.exe""

On Windows I had solved this problem in the following way :

1) uninstalled Python

2) navigated to C:\Users\MyName\AppData\Local\Programs(your should turn on hidden files visibility Show hidden files instruction)

3) deleted 'Python' folder

4) installed Python

Python argparse command line flags without arguments

Here's a quick way to do it, won't require anything besides sys.. though functionality is limited:

flag = "--flag" in sys.argv[1:]

[1:] is in case if the full file name is --flag

How to convert QString to std::string?

Best thing to do would be to overload operator<< yourself, so that QString can be passed as a type to any library expecting an output-able type.

std::ostream& operator<<(std::ostream& str, const QString& string) {
    return str << string.toStdString();
}

java.lang.UnsatisfiedLinkError: dalvik.system.PathClassLoader

This could be device related issue.
I was getting this error in MI devices only, code was working with all other devices.

This might help:

 defaultConfig{
      ...    
      externalNativeBuild {
                    cmake {
                        cppFlags "-frtti -fexceptions"
                    }
                }
    }

Using ALTER to drop a column if it exists in MySQL

I realise this thread is quite old now, but I was having the same problem. This was my very basic solution using the MySQL Workbench, but it worked fine...

  1. get a new sql editor and execute SHOW TABLES to get a list of your tables
  2. select all of the rows, and choose copy to clipboard (unquoted) from the context menu
  3. paste the list of names into another editor tab
  4. write your query, ie ALTER TABLE x DROP a;
  5. do some copying and pasting, so you end up with separate query for each table
  6. Toggle whether the workbench should stop when an error occurs
  7. Hit execute and look through the output log

any tables which had the table now haven't any tables which didn't will have shown an error in the logs

then you can find/replace 'drop a' change it to 'ADD COLUMN b INT NULL' etc and run the whole thing again....

a bit clunky, but at last you get the end result and you can control/monitor the whole process and remember to save you sql scripts in case you need them again.

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.

JavaScript/jQuery to download file via POST with JSON data

I know this kind of old, but I think I have come up with a more elegant solution. I had the exact same problem. The issue I was having with the solutions suggested were that they all required the file being saved on the server, but I did not want to save the files on the server, because it introduced other problems (security: the file could then be accessed by non-authenticated users, cleanup: how and when do you get rid of the files). And like you, my data was complex, nested JSON objects that would be hard to put into a form.

What I did was create two server functions. The first validated the data. If there was an error, it would be returned. If it was not an error, I returned all of the parameters serialized/encoded as a base64 string. Then, on the client, I have a form that has only one hidden input and posts to a second server function. I set the hidden input to the base64 string and submit the format. The second server function decodes/deserializes the parameters and generates the file. The form could submit to a new window or an iframe on the page and the file will open up.

There's a little bit more work involved, and perhaps a little bit more processing, but overall, I felt much better with this solution.

Code is in C#/MVC

    public JsonResult Validate(int reportId, string format, ReportParamModel[] parameters)
    {
        // TODO: do validation

        if (valid)
        {
            GenerateParams generateParams = new GenerateParams(reportId, format, parameters);

            string data = new EntityBase64Converter<GenerateParams>().ToBase64(generateParams);

            return Json(new { State = "Success", Data = data });
        }

        return Json(new { State = "Error", Data = "Error message" });
    }

    public ActionResult Generate(string data)
    {
        GenerateParams generateParams = new EntityBase64Converter<GenerateParams>().ToEntity(data);

        // TODO: Generate file

        return File(bytes, mimeType);
    }

on the client

    function generate(reportId, format, parameters)
    {
        var data = {
            reportId: reportId,
            format: format,
            params: params
        };

        $.ajax(
        {
            url: "/Validate",
            type: 'POST',
            data: JSON.stringify(data),
            dataType: 'json',
            contentType: 'application/json; charset=utf-8',
            success: generateComplete
        });
    }

    function generateComplete(result)
    {
        if (result.State == "Success")
        {
            // this could/should already be set in the HTML
            formGenerate.action = "/Generate";
            formGenerate.target = iframeFile;

            hidData = result.Data;
            formGenerate.submit();
        }
        else
            // TODO: display error messages
    }

Convert serial.read() into a useable string using Arduino?

I could get away with this:

void setup() {
  Serial.begin(9600);
}

void loop() {
  String message = "";
  while (Serial.available())
    message.concat((char) Serial.read());
  if (message != "")
    Serial.println(message);
}

mysql query: SELECT DISTINCT column1, GROUP BY column2

You can just add the DISTINCT(ip), but it has to come at the start of the query. Be sure to escape PHP variables that go into the SQL string.

SELECT DISTINCT(ip), name, COUNT(name) nameCnt, 
time, price, SUM(price) priceSum
FROM tablename 
WHERE time >= $yesterday AND time <$today 
GROUP BY ip, name

How to push changes to github after jenkins build completes?

Found an answer myself, this blog helped: http://thingsyoudidntknowaboutjenkins.tumblr.com/post/23596855946/git-plugin-part-3

Basically need to execute:

git checkout master

before modifying any files

then

git commit -am "Updated version number"

after modified files

and then use post build action of Git Publisher with an option of Merge Results which will push changes to github on successful build.

Python: Remove division decimal

When a number as a decimal it is usually a float in Python.

If you want to remove the decimal and keep it an integer (int). You can call the int() method on it like so...

>>> int(2.0)
2

However, int rounds down so...

>>> int(2.9)
2

If you want to round to the nearest integer you can use round:

>>> round(2.9)
3.0
>>> round(2.4)
2.0

And then call int() on that:

>>> int(round(2.9))
3
>>> int(round(2.4))
2

How do I run a Python script on my web server?

Very simply, you can rename your Python script to "pythonscript.cgi". Post that in your cgi-bin directory, add the appropriate permissions and browse to it.

This is a great link you can start with.

Here's another good one.

Hope that helps.


EDIT (09/12/2015): The second link has long been removed. Replaced it with one that provides information referenced from the original.

How to run Spring Boot web application in Eclipse itself?

First Method:(if STS is available in eclipse)
1.right click on project->run as ->Spring Boot app.

Second Method:
1.right click on project->run as ->run configuration
2. set base directory of you project ie.${workspace_loc:/first}
3. set goal spring-boot:run
4. Run

Third Method:
1.Right click on @SpringBootApplication annotation class ->Run as ->Java Application

Using Linq to group a list of objects into a new grouped list of list of objects

For type

public class KeyValue
{
    public string KeyCol { get; set; }
    public string ValueCol { get; set; }
}

collection

var wordList = new Model.DTO.KeyValue[] {
    new Model.DTO.KeyValue {KeyCol="key1", ValueCol="value1" },
    new Model.DTO.KeyValue {KeyCol="key2", ValueCol="value1" },
    new Model.DTO.KeyValue {KeyCol="key3", ValueCol="value2" },
    new Model.DTO.KeyValue {KeyCol="key4", ValueCol="value2" },
    new Model.DTO.KeyValue {KeyCol="key5", ValueCol="value3" },
    new Model.DTO.KeyValue {KeyCol="key6", ValueCol="value4" }
};

our linq query look like below

var query =from m in wordList group m.KeyCol by m.ValueCol into g
select new { Name = g.Key, KeyCols = g.ToList() };

or for array instead of list like below

var query =from m in wordList group m.KeyCol by m.ValueCol into g
select new { Name = g.Key, KeyCols = g.ToList().ToArray<string>() };

C# How do I click a button by hitting Enter whilst textbox has focus?

The usual way to do this is to set the Form's AcceptButton to the button you want "clicked". You can do this either in the VS designer or in code and the AcceptButton can be changed at any time.

This may or may not be applicable to your situation, but I have used this in conjunction with GotFocus events for different TextBoxes on my form to enable different behavior based on where the user hit Enter. For example:

void TextBox1_GotFocus(object sender, EventArgs e)
{
    this.AcceptButton = ProcessTextBox1;
}

void TextBox2_GotFocus(object sender, EventArgs e)
{
    this.AcceptButton = ProcessTextBox2;
}

One thing to be careful of when using this method is that you don't leave the AcceptButton set to ProcessTextBox1 when TextBox3 becomes focused. I would recommend using either the LostFocus event on the TextBoxes that set the AcceptButton, or create a GotFocus method that all of the controls that don't use a specific AcceptButton call.

error: package javax.servlet does not exist

The javax.servlet dependency is missing in your pom.xml. Add the following to the dependencies-Node:

<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>javax.servlet-api</artifactId>
    <version>3.0.1</version>
    <scope>provided</scope>
</dependency>

how to return a char array from a function in C

Daniel is right: http://ideone.com/kgbo1C#view_edit_box

Change

test=substring(i,j,*s);

to

test=substring(i,j,s);  

Also, you need to forward declare substring:

char *substring(int i,int j,char *ch);

int main // ...

Best way to represent a Grid or Table in AngularJS with Bootstrap 3?

I had the same requirement and solved it using these components:

The table component ng-grid is capable of displaying hundreds of rows in a scrollable grid. If you have to deal with thousands of entries you are better off using ng-grid's paginator. The documentation of ng-grid is excellent and contains many examples. Sorting and searching are supported even in combination with pagination.

Here is a screenshot from a current project to give you an impression how it looks like:

enter image description here

[UPDATE July 2017]

After having ng-grid in production for a couple of years, I can still tell that there are no major issues with this component. Yes, plenty of minor bugs, but no show stoppers (at least in my use cases). Having said that, I would strongly advice against using this component if you start a project from the scratch. This component is a good option only if you are bound to AngularJS 1.0.x. If you are free to choose the Angular version, go for a newer component. A list of table components for Angular 4 was compiled by Sam Deering in this blog.

How to add a title to a html select tag

You can use the following

<select data-hai="whatup">
      <option label="Select your city">Select your city</option>
      <option value="sydney">Sydney</option>
      <option value="melbourne">Melbourne</option>
      <option value="cromwell">Cromwell</option>
      <option value="queenstown">Queenstown</option>
</select>

"Adaptive Server is unavailable or does not exist" error connecting to SQL Server from PHP

I've found an issue happen to be with the Firewall. So, make sure your IP is whitelisted and the firewall does not block your connection. You can check connectivity with:

tsql -H somehost.com -p 1433

In my case, the output was:

Error 20009 (severity 9):
  Unable to connect: Adaptive Server is unavailable or does not exist
  OS error 111, "Connection refused"
There was a problem connecting to the server

Shell script variable not empty (-z option)

I think this is the syntax you are looking for:

if [ -z != $errorstatus ] 
then
commands
else
commands
fi

Swift: Determine iOS Screen size

In Swift 3.0

let screenSize = UIScreen.main.bounds
let screenWidth = screenSize.width
let screenHeight = screenSize.height

In older swift: Do something like this:

let screenSize: CGRect = UIScreen.mainScreen().bounds

then you can access the width and height like this:

let screenWidth = screenSize.width
let screenHeight = screenSize.height

if you want 75% of your screen's width you can go:

let screenWidth = screenSize.width * 0.75

Swift 4.0

// Screen width.
public var screenWidth: CGFloat {
    return UIScreen.main.bounds.width
}

// Screen height.
public var screenHeight: CGFloat {
    return UIScreen.main.bounds.height
}

In Swift 5.0

let screenSize: CGRect = UIScreen.main.bounds

How to create an array of 20 random bytes?

If you want a cryptographically strong random number generator (also thread safe) without using a third party API, you can use SecureRandom.

Java 6 & 7:

SecureRandom random = new SecureRandom();
byte[] bytes = new byte[20];
random.nextBytes(bytes);

Java 8 (even more secure):

byte[] bytes = new byte[20];
SecureRandom.getInstanceStrong().nextBytes(bytes);

intellij incorrectly saying no beans of type found for autowired repository

just add below two annotations to your POJO.

@ComponentScan
@Configuration
public class YourClass {
    //TODO
}

Matplotlib: Specify format of floats for tick labels

If you are directly working with matplotlib's pyplot (plt) and if you are more familiar with the new-style format string, you can try this:

from matplotlib.ticker import StrMethodFormatter
plt.gca().yaxis.set_major_formatter(StrMethodFormatter('{x:,.0f}')) # No decimal places
plt.gca().yaxis.set_major_formatter(StrMethodFormatter('{x:,.2f}')) # 2 decimal places

From the documentation:

class matplotlib.ticker.StrMethodFormatter(fmt)

Use a new-style format string (as used by str.format()) to format the tick.

The field used for the value must be labeled x and the field used for the position must be labeled pos.

How to find day of week in php in a specific timezone

My solution is this:

$tempDate = '2012-07-10';
echo date('l', strtotime( $tempDate));

Output is: Tuesday

$tempDate = '2012-07-10';
echo date('D', strtotime( $tempDate));

Output is: Tue

LINK : fatal error LNK1561: entry point must be defined ERROR IN VC++

change it to Console (/SUBSYSTEM:CONSOLE) it will work

Generating (pseudo)random alpha-numeric strings

You can use the following code. It is similar to existing functions except that you can force special character count:

function random_string() {
    // 8 characters: 7 lower-case alphabets and 1 digit
    $character_sets = [
        ["count" => 7, "characters" => "abcdefghijklmnopqrstuvwxyz"],
        ["count" => 1, "characters" => "0123456789"]
    ];
    $temp_array = array();
    foreach ($character_sets as $character_set) {
        for ($i = 0; $i < $character_set["count"]; $i++) {
            $random = random_int(0, strlen($character_set["characters"]) - 1);
            $temp_array[] = $character_set["characters"][$random];
        }
    }
    shuffle($temp_array);
    return implode("", $temp_array);
}

"Multiple definition", "first defined here" errors

I am adding this A because I got caught with a bizarre version of this which really had me scratching my head for about a hour until I spotted the root cause. My load was failing because of multiple repeats of this format

<path>/linit.o:(.rodata1.libs+0x50): multiple definition of `lua_lib_BASE'
<path>/linit.o:(.rodata1.libs+0x50): first defined here

I turned out to be a bug in my Makefile magic where I had a list of C files and using vpath etc., so the compiles would pick them up from the correct directory in hierarchy. However one C file was repeated in the list, at the end of one line and the start of the next so the gcc load generated by the make had the .o file twice on the command line. Durrrrh. The multiple definitions were from multiple occurances of the same file. The linker ignored duplicates apart from static initialisers!

How to compare two floating point numbers in Bash?

beware when comparing numbers that are package versions, like checking if grep 2.20 is greater than version 2.6:

$ awk 'BEGIN { print (2.20 >= 2.6) ? "YES" : "NO" }'
NO

$ awk 'BEGIN { print (2.2 >= 2.6) ? "YES" : "NO" }'
NO

$ awk 'BEGIN { print (2.60 == 2.6) ? "YES" : "NO" }'
YES

I solved such problem with such shell/awk function:

# get version of GNU tool
toolversion() {
    local prog="$1" operator="$2" value="$3" version

    version=$($prog --version | awk '{print $NF; exit}')

    awk -vv1="$version" -vv2="$value" 'BEGIN {
        split(v1, a, /\./); split(v2, b, /\./);
        if (a[1] == b[1]) {
            exit (a[2] '$operator' b[2]) ? 0 : 1
        }
        else {
            exit (a[1] '$operator' b[1]) ? 0 : 1
        }
    }'
}

if toolversion grep '>=' 2.6; then
   # do something awesome
fi

Javascript get the text value of a column from a particular row of an html table

in case if your table has tbody

let tbl = document.getElementById("tbl").getElementsByTagName('tbody')[0];
console.log(tbl.rows[0].cells[0].innerHTML)

IE Driver download location Link for Selenium

Use the below link to download IE Driver latest version

IE Driver

How do I run SSH commands on remote system using Java?

Have a look at Runtime.exec() Javadoc

Process p = Runtime.getRuntime().exec("ssh myhost");
PrintStream out = new PrintStream(p.getOutputStream());
BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));

out.println("ls -l /home/me");
while (in.ready()) {
  String s = in.readLine();
  System.out.println(s);
}
out.println("exit");

p.waitFor();

CardView Corner Radius

You can put your ImageView inside a CardView, and add those properties to the ImageView:

android:cropToPadding="true"
android:paddingBottom="15dp"

That way you will get rid of the rounded bottom corner, but keep in mind that this comes in the price of having a small portion of your image cut off.

How to add button in ActionBar(Android)?

you have to create an entry inside res/menu,override onCreateOptionsMenu and inflate it

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.yourentry, menu);
    return true;
}

an entry for the menu could be:

<menu xmlns:android="http://schemas.android.com/apk/res/android" >
    <item
        android:id="@+id/action_cart"
        android:icon="@drawable/cart"
        android:orderInCategory="100"
        android:showAsAction="always"/> 
</menu>

How To Execute SSH Commands Via PHP

//Update 2018, works//

Method1:

Download phpseclib v1 and use this code:

<?php
set_include_path(__DIR__ . '/phpseclib1.0.11');
include("Net/SSH2.php");

$key ="MyPassword";
  /* ### if using PrivateKey ### 
  include("Crypt/RSA.php");
  $key = new Crypt_RSA();
  $key->loadKey(file_get_contents('private-key.ppk'));
  */

$ssh = new Net_SSH2('www.example.com', 22);   // Domain or IP
if (!$ssh->login('your_username', $key))  exit('Login Failed');

echo $ssh->exec('pwd');
?>

or Method2:

Download newest phpseclib v2 (requires composer install at first):

<?php

set_include_path($path=__DIR__ . '/phpseclib-master/phpseclib');
include ($path.'/../vendor/autoload.php');

$loader = new \Composer\Autoload\ClassLoader();

use phpseclib\Net\SSH2;

$key ="MyPassword";
  /* ### if using PrivateKey ### 
  use phpseclib\Crypt\RSA;
  $key = new RSA();
  $key->load(file_get_contents('private-key.ppk'));
  */

$ssh = new SSH2('www.example.com', 22);   // Domain or IP
if (!$ssh->login('your_username', $key))   exit('Login Failed'); 

echo $ssh->exec('pwd');
?>

p.s. if you get "Connection timed out" then it's probably the issue of HOST/FIREWALL (local or remote) or like that, not a fault of script.

How do I create a master branch in a bare Git repository?

You don't need to use a second repository - you can do commands like git checkout and git commit on a bare repository, if only you supply a dummy work directory using the --work-tree option.

Prepare a dummy directory:

$ rm -rf /tmp/empty_directory
$ mkdir  /tmp/empty_directory

Create the master branch without a parent (works even on a completely empty repo):

$ cd your-bare-repository.git

$ git checkout --work-tree=/tmp/empty_directory --orphan master
Switched to a new branch 'master'                  <--- abort if "master" already exists

Create a commit (it can be a message-only, without adding any files, because what you need is simply having at least one commit):

$ git commit -m "Initial commit" --allow-empty --work-tree=/tmp/empty_directory 

$ git branch
* master

Clean up the directory, it is still empty.

$ rmdir  /tmp/empty_directory

Tested on git 1.9.1. (Specifically for OP, the posh-git is just a PowerShell wrapper for standard git.)

Passing an array as parameter in JavaScript

JavaScript is a dynamically typed language. This means that you never need to declare the type of a function argument (or any other variable). So, your code will work as long as arrayP is an array and contains elements with a value property.

Built in Python hash() function

Polynomial hash for strings. 1000000009 and 239 are arbitrary prime numbers. Unlikely to have collisions by accident. Modular arithmetic is not very fast, but for preventing collisions this is more reliable than taking it modulo a power of 2. Of course, it is easy to find a collision on purpose.

mod=1000000009
def hash(s):
    result=0
    for c in s:
        result = (result * 239 + ord(c)) % mod
    return result % mod

Android toolbar center title and custom font

    public class TestActivity extends AppCompatActivity {
    private Toolbar toolbar;

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

        toolbar = (Toolbar) findViewById(R.id.tool_bar); // Attaching the layout to the toolbar object
        setSupportActionBar(toolbar);

        customizeToolbar(toolbar);
    }

    public void customizeToolbar(Toolbar toolbar){
        // Save current title and subtitle
        final CharSequence originalTitle = toolbar.getTitle();
        final CharSequence originalSubtitle = toolbar.getSubtitle();

        // Temporarily modify title and subtitle to help detecting each
        toolbar.setTitle("title");
        toolbar.setSubtitle("subtitle");

        for(int i = 0; i < toolbar.getChildCount(); i++){
            View view = toolbar.getChildAt(i);

            if(view instanceof TextView){
                TextView textView = (TextView) view;


                if(textView.getText().equals("title")){
                    // Customize title's TextView
                    Toolbar.LayoutParams params = new Toolbar.LayoutParams(Toolbar.LayoutParams.WRAP_CONTENT, Toolbar.LayoutParams.MATCH_PARENT);
                    params.gravity = Gravity.CENTER_HORIZONTAL;
                    textView.setLayoutParams(params);

                    // Apply custom font using the Calligraphy library
                    Typeface typeface = TypefaceUtils.load(getAssets(), "fonts/myfont-1.otf");
                    textView.setTypeface(typeface);

                } else if(textView.getText().equals("subtitle")){
                    // Customize subtitle's TextView
                    Toolbar.LayoutParams params = new Toolbar.LayoutParams(Toolbar.LayoutParams.WRAP_CONTENT, Toolbar.LayoutParams.MATCH_PARENT);
                    params.gravity = Gravity.CENTER_HORIZONTAL;
                    textView.setLayoutParams(params);

                    // Apply custom font using the Calligraphy library
                    Typeface typeface = TypefaceUtils.load(getAssets(), "fonts/myfont-2.otf");
                    textView.setTypeface(typeface);
                }
            }
        }

        // Restore title and subtitle
        toolbar.setTitle(originalTitle);
        toolbar.setSubtitle(originalSubtitle);
    }
}

Equivalent to AssemblyInfo in dotnet core/csproj

Those settings has moved into the .csproj file.

By default they don't show up but you can discover them from Visual Studio 2017 in the project properties Package tab.

Project properties, tab Package

Once saved those values can be found in MyProject.csproj

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <TargetFramework>net461</TargetFramework>
    <Version>1.2.3.4</Version>
    <Authors>Author 1</Authors>
    <Company>Company XYZ</Company>
    <Product>Product 2</Product>
    <PackageId>MyApp</PackageId>
    <AssemblyVersion>2.0.0.0</AssemblyVersion>
    <FileVersion>3.0.0.0</FileVersion>
    <NeutralLanguage>en</NeutralLanguage>
    <Description>Description here</Description>
    <Copyright>Copyright</Copyright>
    <PackageLicenseUrl>License URL</PackageLicenseUrl>
    <PackageProjectUrl>Project URL</PackageProjectUrl>
    <PackageIconUrl>Icon URL</PackageIconUrl>
    <RepositoryUrl>Repo URL</RepositoryUrl>
    <RepositoryType>Repo type</RepositoryType>
    <PackageTags>Tags</PackageTags>
    <PackageReleaseNotes>Release</PackageReleaseNotes>
  </PropertyGroup>

In the file explorer properties information tab, FileVersion is shown as "File Version" and Version is shown as "Product version"

Oracle PL Sql Developer cannot find my tnsnames.ora file

You most certainly have a databases tab in sql developer (all versions I've used in the past have this). Maybe check again? Perhaps, you're looking in the wrong location.

On a mac, the preferences is under "Oracle SQL Developer" (top left) -> Preferences -> Database -> Advanced -> section called Tnsnames Directory is where you specify the file.

On windows (going from memory so might have to search if this isn't correct) Tools -> Preferences -> Database -> Advanced -> section called Tnsnames Directory is where you specify the file.

See this image enter image description here

kill -3 to get java thread dump

You could alternatively use jstack (Included with JDK) to take a thread dump and write the output wherever you want. Is that not available in a unix environment?

jstack PID > outfile

Prompt Dialog in Windows Forms

The answer of Bas can get you in memorytrouble theoretically, since ShowDialog won't be disposed. I think this is a more proper way. Also mention the textLabel being readable with longer text.

public class Prompt : IDisposable
{
    private Form prompt { get; set; }
    public string Result { get; }

    public Prompt(string text, string caption)
    {
        Result = ShowDialog(text, caption);
    }
    //use a using statement
    private string ShowDialog(string text, string caption)
    {
        prompt = new Form()
        {
            Width = 500,
            Height = 150,
            FormBorderStyle = FormBorderStyle.FixedDialog,
            Text = caption,
            StartPosition = FormStartPosition.CenterScreen,
            TopMost = true
        };
        Label textLabel = new Label() { Left = 50, Top = 20, Text = text, Dock = DockStyle.Top, TextAlign = ContentAlignment.MiddleCenter };
        TextBox textBox = new TextBox() { Left = 50, Top = 50, Width = 400 };
        Button confirmation = new Button() { Text = "Ok", Left = 350, Width = 100, Top = 70, DialogResult = DialogResult.OK };
        confirmation.Click += (sender, e) => { prompt.Close(); };
        prompt.Controls.Add(textBox);
        prompt.Controls.Add(confirmation);
        prompt.Controls.Add(textLabel);
        prompt.AcceptButton = confirmation;

        return prompt.ShowDialog() == DialogResult.OK ? textBox.Text : "";
    }

    public void Dispose()
    {
        //See Marcus comment
        if (prompt != null) { 
            prompt.Dispose(); 
        }
    }
}

Implementation:

using(Prompt prompt = new Prompt("text", "caption")){
    string result = prompt.Result;
}

How to set a single, main title above all the subplots with Pyplot?

If your subplots also have titles, you may need to adjust the main title size:

plt.suptitle("Main Title", size=16)

redistributable offline .NET Framework 3.5 installer for Windows 8

Try this command:

Dism.exe /online /enable-feature /featurename:NetFX3 /Source:I:\Sources\sxs /LimitAccess

I: partition of your Windows DVD.

Using set_facts and with_items together in Ansible

Updated 2018-06-08: My previous answer was a bit of hack so I have come back and looked at this again. This is a cleaner Jinja2 approach.

- name: Set fact 4
  set_fact:
    foo: "{% for i in foo_result.results %}{% do foo.append(i) %}{% endfor %}{{ foo }}"

I am adding this answer as current best answer for Ansible 2.2+ does not completely cover the original question. Thanks to Russ Huguley for your answer this got me headed in the right direction but it left me with a concatenated string not a list. This solution gets a list but becomes even more hacky. I hope this gets resolved in a cleaner manner.

- name: build foo_string
  set_fact:
    foo_string: "{% for i in foo_result.results %}{{ i.ansible_facts.foo_item }}{% if not loop.last %},{% endif %}{%endfor%}"

- name: set fact foo
  set_fact:
    foo: "{{ foo_string.split(',') }}"

How to avoid "StaleElementReferenceException" in Selenium?

The reason why the StaleElementReferenceException occurs has been laid out already: updates to the DOM between finding and doing something with the element.

For the click-Problem I've recently used a solution like this:

public void clickOn(By locator, WebDriver driver, int timeout)
{
    final WebDriverWait wait = new WebDriverWait(driver, timeout);
    wait.until(ExpectedConditions.refreshed(
        ExpectedConditions.elementToBeClickable(locator)));
    driver.findElement(locator).click();
}

The crucial part is the "chaining" of Selenium's own ExpectedConditions via the ExpectedConditions.refreshed(). This actually waits and checks if the element in question has been refreshed during the specified timeout and additionally waits for the element to become clickable.

Have a look at the documentation for the refreshed method.

Android: ListView elements with multiple clickable buttons

I am not sure about be the best way, but works fine and all code stays in your ArrayAdapter.

package br.com.fontolan.pessoas.arrayadapter;

import java.util.List;

import android.content.Context;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import br.com.fontolan.pessoas.R;
import br.com.fontolan.pessoas.model.Telefone;

public class TelefoneArrayAdapter extends ArrayAdapter<Telefone> {

private TelefoneArrayAdapter telefoneArrayAdapter = null;
private Context context;
private EditText tipoEditText = null;
private EditText telefoneEditText = null;
private ImageView deleteImageView = null;

public TelefoneArrayAdapter(Context context, List<Telefone> values) {
    super(context, R.layout.telefone_form, values);
    this.telefoneArrayAdapter = this;
    this.context = context;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View view = inflater.inflate(R.layout.telefone_form, parent, false);

    tipoEditText = (EditText) view.findViewById(R.id.telefone_form_tipo);
    telefoneEditText = (EditText) view.findViewById(R.id.telefone_form_telefone);
    deleteImageView = (ImageView) view.findViewById(R.id.telefone_form_delete_image);

    final int i = position;
    final Telefone telefone = this.getItem(position);
    tipoEditText.setText(telefone.getTipo());
    telefoneEditText.setText(telefone.getTelefone());

    TextWatcher tipoTextWatcher = new TextWatcher() {
        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        @Override
        public void afterTextChanged(Editable s) {
            telefoneArrayAdapter.getItem(i).setTipo(s.toString());
            telefoneArrayAdapter.getItem(i).setIsDirty(true);
        }
    };

    TextWatcher telefoneTextWatcher = new TextWatcher() {
        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        @Override
        public void afterTextChanged(Editable s) {
            telefoneArrayAdapter.getItem(i).setTelefone(s.toString());
            telefoneArrayAdapter.getItem(i).setIsDirty(true);
        }
    };

    tipoEditText.addTextChangedListener(tipoTextWatcher);
    telefoneEditText.addTextChangedListener(telefoneTextWatcher);

    deleteImageView.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            telefoneArrayAdapter.remove(telefone);
        }
    });

    return view;
}

}

How to set width to 100% in WPF

It is the container of the Grid that is imposing on its width. In this case, that's a ListBoxItem, which is left-aligned by default. You can set it to stretch as follows:

<ListBox>
    <!-- other XAML omitted, you just need to add the following bit -->
    <ListBox.ItemContainerStyle>
        <Style TargetType="ListBoxItem">
            <Setter Property="HorizontalAlignment" Value="Stretch"/>
        </Style>
    </ListBox.ItemContainerStyle>
</ListBox>

How to diff one file to an arbitrary version in Git?

git diff -w HEAD origin/master path/to/file

MongoDB what are the default user and password?

In addition with what @Camilo Silva already mentioned, if you want to give free access to create databases, read, write databases, etc, but you don't want to create a root role, you can change the 3rd step with the following:

use admin
db.createUser(
  {
    user: "myUserAdmin",
    pwd: "abc123",
    roles: [ { role: "userAdminAnyDatabase", db: "admin" }, 
             { role: "dbAdminAnyDatabase", db: "admin" }, 
             { role: "readWriteAnyDatabase", db: "admin" } ]
  }
)

How can I resize an image dynamically with CSS as the browser width/height changes?

This can be done with pure CSS and does not even require media queries.

To make the images flexible, simply add max-width:100% and height:auto. Image max-width:100% and height:auto works in IE7, but not in IE8 (yes, another weird IE bug). To fix this, you need to add width:auto\9 for IE8.

source: http://webdesignerwall.com/tutorials/responsive-design-with-css3-media-queries

CSS:

img {
    max-width: 100%;
    height: auto;
    width: auto\9; /* ie8 */
}

And if you want to enforce a fixed max width of the image, just place it inside a container, for example:

<div style="max-width:500px;">
    <img src="..." />
</div>

JSFiddle example here. No JavaScript required. Works in latest versions of Chrome, Firefox and IE (which is all I've tested).

Inline style to act as :hover in CSS

If you are only debugging, you might use javascript to modify the css:

<a onmouseover="this.style.textDecoration='underline';" 
    onmouseout="this.style.textDecoration='none';">bar</a>

Maven 3 and JUnit 4 compilation problem: package org.junit does not exist

Me too had the same problem as shown below.

enter image description here

To resolve the issue, below lines are added to dependencies section in the app level build.gradle.

compile 'junit:junit:4.12'
androidTestCompile 'com.android.support.test:runner:0.5'

Gradle build then reported following warning.

Warning:Conflict with dependency 'com.android.support:support-annotations'. 
Resolved versions for app (25.1.0) and test app (23.1.1) differ. 
See http://g.co/androidstudio/app-test-app-conflict for details.

To solve this warning, following section is added to the app level build.gradle.

configurations.all {
    resolutionStrategy {
        force 'com.android.support:support-annotations:23.1.1'
    }
}

java create date object using a value string

It is because value coming String (Java Date object constructor for getting string is deprecated)

and Date(String) is deprecated.

Have a look at jodatime or you could put @SuppressWarnings({“deprecation”}) outside the method calling the Date(String) constructor.

How do I fix the error 'Named Pipes Provider, error 40 - Could not open a connection to' SQL Server'?

I had the same problem and solved the problem by disabling my firewall(ESET).

The first step to solve this problem should be to try pinging your own computer from another computer. If you have firewall on, you may not be able to ping yourself. I tried pinging my own pc, then ping was failed(didnt get response from the server)

Best IDE for HTML5, Javascript, CSS, Jquery support with GUI building tools

My personal experience to build website with html, css en javascript is just to stick with plain text editors with ftp support. I am using Espresso or/and Coda on my mac. But Textmate with Cyberduck(ftp client) is also a great combination, imo. For developing in Windows I recommend notepad++.

How do I create dynamic variable names inside a loop?

You can use eval() method to declare dynamic variables. But better to use an Array.

for (var i = 0; i < coords.length; ++i) {
    var str ="marker"+ i+" = undefined";
    eval(str);
}

Hide all elements with class using plain Javascript

As simple as the following:

let elements = document.querySelectorAll('.custom-class')

elements.forEach((item: any) => {
  item.style.display = 'none'
})

With that, you avoid all the looping, indexing, and such.

Pass PDO prepared statement to variables

Instead of using ->bindParam() you can pass the data only at the time of ->execute():

$data = [   ':item_name' => $_POST['item_name'],   ':item_type' => $_POST['item_type'],   ':item_price' => $_POST['item_price'],   ':item_description' => $_POST['item_description'],   ':image_location' => 'images/'.$_FILES['file']['name'],   ':status' => 0,   ':id' => 0, ];  $stmt->execute($data); 

In this way you would know exactly what values are going to be sent.

jQuery load first 3 elements, click "load more" to display next 5 elements

Simple and with little changes. And also hide load more when entire list is loaded.

jsFiddle here.

$(document).ready(function () {
    // Load the first 3 list items from another HTML file
    //$('#myList').load('externalList.html li:lt(3)');
    $('#myList li:lt(3)').show();
    $('#showLess').hide();
    var items =  25;
    var shown =  3;
    $('#loadMore').click(function () {
        $('#showLess').show();
        shown = $('#myList li:visible').size()+5;
        if(shown< items) {$('#myList li:lt('+shown+')').show();}
        else {$('#myList li:lt('+items+')').show();
             $('#loadMore').hide();
             }
    });
    $('#showLess').click(function () {
        $('#myList li').not(':lt(3)').hide();
    });
});

Downloading folders from aws s3, cp or sync?

You've many options to do that, but the best one is using the AWS CLI.

Here's a walk-through:

  1. Download and install AWS CLI in your machine:

  2. Configure AWS CLI:

enter image description here

Make sure you input valid access and secret keys, which you received when you created the account.

  1. Sync the S3 bucket using:

     aws s3 sync s3://yourbucket/yourfolder /local/path
    

In the above command, replace the following fields:

  • yourbucket/yourfolder >> your S3 bucket and the folder that you want to download.
  • /local/path >> path in your local system where you want to download all the files.

HTML5 phone number validation with pattern

How about this? /(7|8|9)\d{9}/

It starts by either looking for 7 or 8 or 9, and then followed by 9 digits.

Check if two unordered lists are equal

If elements are always nearly sorted as in your example then builtin .sort() (timsort) should be fast:

>>> a = [1,1,2]
>>> b = [1,2,2]
>>> a.sort()
>>> b.sort()
>>> a == b
False

If you don't want to sort inplace you could use sorted().

In practice it might always be faster then collections.Counter() (despite asymptotically O(n) time being better then O(n*log(n)) for .sort()). Measure it; If it is important.

Detect if checkbox is checked or unchecked in Angular.js ng-change event

You could just use the bound ng-model (answers[item.questID]) value itself in your ng-change method to detect if it has been checked or not.

Example:-

<input type="checkbox" ng-model="answers[item.questID]" 
     ng-change="stateChanged(item.questID)" /> <!-- Pass the specific id -->

and

$scope.stateChanged = function (qId) {
   if($scope.answers[qId]){ //If it is checked
       alert('test');
   }
}

When to use static methods

A static method has two main purposes:

  1. For utility or helper methods that don't require any object state. Since there is no need to access instance variables, having static methods eliminates the need for the caller to instantiate the object just to call the method.
  2. For the state that is shared by all instances of the class, like a counter. All instance must share the same state. Methods that merely use that state should be static as well.

Can I use multiple "with"?

Yes - just do it this way:

WITH DependencedIncidents AS
(
  ....
),  
lalala AS
(
  ....
)

You don't need to repeat the WITH keyword

Adding sheets to end of workbook in Excel (normal method not working?)

A common mistake is

mainWB.Sheets.Add(After:=Sheets.Count)

which leads to Error 1004. Although it is not clear at all from the official documentation, it turns out that the 'After' parameter cannot be an integer, it must be a reference to a sheet in the same workbook.

How to install MySQLdb package? (ImportError: No module named setuptools)

well installing C compiler or GCC didn't work but I found a way to successfully install mysqldb package

kindly follow Mike schrieb's (Thanks to him) instructions here . In my case, I used setuptools-0.6c11-py2.7.egg and setuptools-0.6c11 . Then download the executable file here then install that file. hope it helps :)

Difference between SRC and HREF

after going through the HTML 5.1 ducumentation (1 November 2016):


part 4 (The elements of HTML)

chapter 2 (Document metadata)

section 4 (The link element) states that:

The destination of the link(s) is given by the href attribute, which must be present and must contain a valid non-empty URL potentially surrounded by spaces. If the href attribute is absent, then the element does not define a link.

does not contain the src attribute ...

witch is logical because it is a link .


chapter 12 (Scripting)

section 1 (The script element) states that:

Classic scripts may either be embedded inline or may be imported from an external file using the src attribute, which if specified gives the URL of the external script resource to use. If src is specified, it must be a valid non-empty URL potentially surrounded by spaces. The contents of inline script elements, or the external script resource, must conform with the requirements of the JavaScript specification’s Script production for classic scripts.

it doesn't even mention the href attribute ...

this indicates that while using script tags always use the src attribute !!!


chapter 7 (Embedded content)

section 5 (The img element)

The image given by the src and srcset attributes, and any previous sibling source element's srcset attributes if the parent is a picture element, is the embedded content.

also doesn't mention the href attribute ...

this indicates that when using img tags the src attribute should be used aswell ...


Reference link to the W3C Recommendation

jquery ui Dialog: cannot call methods on dialog prior to initialization

This is also some work around:

$("div[aria-describedby='divDialog'] .ui-button.ui-widget.ui-state-default.ui-corner-all.ui-button-icon-only.ui-dialog-titlebar-close").click();

How do you specify table padding in CSS? ( table, not cell padding )

table.foobar
{
   padding:30px; /* if border is not collapsed */
}

or 

table.foobar
{
   border-spacing:0;
}
table.foobar>tbody
{
   display:table;
   border-spacing:0; /* or other preferred */
   border:30px solid transparent; /* 30px is the "padding" */
}

Works in Firefox, Chrome, IE11, Edge.

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

Perhaps this will work?

<c:forEach items="${myParams.items}" var="currentItem" varStatus="stat">
  <c:set var="myVar" value="${stat.first ? '' : myVar} ${currentItem}" />
</c:forEach>

Why std::cout instead of simply cout?

Everything in the Standard Template/Iostream Library resides in namespace std. You've probably used:

using namespace std;

In your classes, and that's why it worked.

Javascript Iframe innerHTML

Having something like the following would work.

<iframe id = "testframe" onload = populateIframe(this.id);></iframe>

// The following function should be inside a script tag

function populateIframe(id) { 

    var text = "This is a Test"
var iframe = document.getElementById(id); 

var doc; 

if(iframe.contentDocument) { 
    doc = iframe.contentDocument; 
} else {
    doc = iframe.contentWindow.document; 
}

doc.body.innerHTML = text; 

  }

Immediate exit of 'while' loop in C++

You should never use a break statement to exit a loop. Of course you can do it, but that doesn't mean you should. It just isn't good programming practice. The more elegant way to exit is the following:

while(choice!=99)
{
    cin>>choice;
    if (choice==99)
        //exit here and don't get additional input
    else
       cin>>gNum;
}

if choice is 99 there is nothing else to do and the loop terminates.

How do I select child elements of any depth using XPath?

You're almost there. Simply use:

//form[@id='myform']//input[@type='submit']

The // shortcut can also be used inside an expression.

Location for session files in Apache/PHP

First check the value of session.save_path using ini_get('session.save_path') or phpinfo(). If that is non-empty, then it will show where the session files are saved. In many scenarios it is empty by default, in which case read on:

On Ubuntu or Debian machines, if session.save_path is not set, then session files are saved in /var/lib/php5.

On RHEL and CentOS systems, if session.save_path is not set, session files will be saved in /var/lib/php/session

I think that if you compile PHP from source, then when session.save_path is not set, session files will be saved in /tmp (I have not tested this myself though).

PHP: How to send HTTP response code?

If your version of PHP does not include this function:

<?php

function http_response_code($code = NULL) {
        if ($code !== NULL) {
            switch ($code) {
                case 100: $text = 'Continue';
                    break;
                case 101: $text = 'Switching Protocols';
                    break;
                case 200: $text = 'OK';
                    break;
                case 201: $text = 'Created';
                    break;
                case 202: $text = 'Accepted';
                    break;
                case 203: $text = 'Non-Authoritative Information';
                    break;
                case 204: $text = 'No Content';
                    break;
                case 205: $text = 'Reset Content';
                    break;
                case 206: $text = 'Partial Content';
                    break;
                case 300: $text = 'Multiple Choices';
                    break;
                case 301: $text = 'Moved Permanently';
                    break;
                case 302: $text = 'Moved Temporarily';
                    break;
                case 303: $text = 'See Other';
                    break;
                case 304: $text = 'Not Modified';
                    break;
                case 305: $text = 'Use Proxy';
                    break;
                case 400: $text = 'Bad Request';
                    break;
                case 401: $text = 'Unauthorized';
                    break;
                case 402: $text = 'Payment Required';
                    break;
                case 403: $text = 'Forbidden';
                    break;
                case 404: $text = 'Not Found';
                    break;
                case 405: $text = 'Method Not Allowed';
                    break;
                case 406: $text = 'Not Acceptable';
                    break;
                case 407: $text = 'Proxy Authentication Required';
                    break;
                case 408: $text = 'Request Time-out';
                    break;
                case 409: $text = 'Conflict';
                    break;
                case 410: $text = 'Gone';
                    break;
                case 411: $text = 'Length Required';
                    break;
                case 412: $text = 'Precondition Failed';
                    break;
                case 413: $text = 'Request Entity Too Large';
                    break;
                case 414: $text = 'Request-URI Too Large';
                    break;
                case 415: $text = 'Unsupported Media Type';
                    break;
                case 500: $text = 'Internal Server Error';
                    break;
                case 501: $text = 'Not Implemented';
                    break;
                case 502: $text = 'Bad Gateway';
                    break;
                case 503: $text = 'Service Unavailable';
                    break;
                case 504: $text = 'Gateway Time-out';
                    break;
                case 505: $text = 'HTTP Version not supported';
                    break;
                default:
                    exit('Unknown http status code "' . htmlentities($code) . '"');
                    break;
            }
            $protocol = (isset($_SERVER['SERVER_PROTOCOL']) ? $_SERVER['SERVER_PROTOCOL'] : 'HTTP/1.0');
            header($protocol . ' ' . $code . ' ' . $text);
            $GLOBALS['http_response_code'] = $code;
        } else {
            $code = (isset($GLOBALS['http_response_code']) ? $GLOBALS['http_response_code'] : 200);
        }
        return $code;
    }

Initializing default values in a struct

You don't even need to define a constructor

struct foo {
    bool a = true;
    bool b = true;
    bool c;
 } bar;

To clarify: these are called brace-or-equal-initializers (because you may also use brace initialization instead of equal sign). This is not only for aggregates: you can use this in normal class definitions. This was added in C++11.

Convert INT to VARCHAR SQL

Use the STR function:

SELECT STR(field_name) FROM table_name

Arguments

float_expression

Is an expression of approximate numeric (float) data type with a decimal point.

length

Is the total length. This includes decimal point, sign, digits, and spaces. The default is 10.

decimal

Is the number of places to the right of the decimal point. decimal must be less than or equal to 16. If decimal is more than 16 then the result is truncated to sixteen places to the right of the decimal point.

source: https://msdn.microsoft.com/en-us/library/ms189527.aspx

Default parameters with C++ constructors

In my experience, default parameters seem cool at the time and make my laziness factor happy, but then down the road I'm using the class and I am surprised when the default kicks in. So I don't really think it's a good idea; better to have a className::className() and then a className::init(arglist). Just for that maintainability edge.

What does "#include <iostream>" do?

That is a C++ standard library header file for input output streams. It includes functionality to read and write from streams. You only need to include it if you wish to use streams.

twitter bootstrap typeahead ajax example

Edit: typeahead is no longer bundled in Bootstrap 3. Check out:

As of Bootstrap 2.1.0 up to 2.3.2, you can do this:

$('.typeahead').typeahead({
    source: function (query, process) {
        return $.get('/typeahead', { query: query }, function (data) {
            return process(data.options);
        });
    }
});

To consume JSON data like this:

{
    "options": [
        "Option 1",
        "Option 2",
        "Option 3",
        "Option 4",
        "Option 5"
    ]
}

Note that the JSON data must be of the right mime type (application/json) so jQuery recognizes it as JSON.

How to add percent sign to NSString

iOS 9.2.1, Xcode 7.2.1, ARC enabled

You can always append the '%' by itself without any other format specifiers in the string you are appending, like so...

int test = 10;

NSString *stringTest = [NSString stringWithFormat:@"%d", test];
stringTest = [stringTest stringByAppendingString:@"%"];
NSLog(@"%@", stringTest);

For iOS7.0+

To expand the answer to other characters that might cause you conflict you may choose to use:

- (NSString *)stringByAddingPercentEncodingWithAllowedCharacters:(NSCharacterSet *)allowedCharacters

Written out step by step it looks like this:

int test = 10;

NSString *stringTest = [NSString stringWithFormat:@"%d", test];
stringTest = [[stringTest stringByAppendingString:@"%"] 
             stringByAddingPercentEncodingWithAllowedCharacters:
             [NSCharacterSet alphanumericCharacterSet]];
stringTest = [stringTest stringByRemovingPercentEncoding];

NSLog(@"percent value of test: %@", stringTest);

Or short hand:

NSLog(@"percent value of test: %@", [[[[NSString stringWithFormat:@"%d", test] 
stringByAppendingString:@"%"] stringByAddingPercentEncodingWithAllowedCharacters:
[NSCharacterSet alphanumericCharacterSet]] stringByRemovingPercentEncoding]);

Thanks to all the original contributors. Hope this helps. Cheers!

How to sum data.frame column values?

To sum values in data.frame you first need to extract them as a vector.

There are several way to do it:

# $ operatior
x <- people$Weight
x
# [1] 65 70 64

Or using [, ] similar to matrix:

x <- people[, 'Weight']
x
# [1] 65 70 64

Once you have the vector you can use any vector-to-scalar function to aggregate the result:

sum(people[, 'Weight'])
# [1] 199

If you have NA values in your data, you should specify na.rm parameter:

sum(people[, 'Weight'], na.rm = TRUE)

Error on renaming database in SQL Server 2008 R2

1.database set 1st single user mode

ALTER DATABASE BOSEVIKRAM SET SINGLE_USER WITH ROLLBACK IMMEDIATE

2.RENAME THE DATABASE

ALTER DATABASE BOSEVIKRAM MODIFY NAME = [BOSEVIKRAM_Deleted]

3.DATABAE SET MULIUSER MODE

ALTER DATABASE BOSEVIKRAM_Deleted SET MULTI_USER WITH ROLLBACK IMMEDIATE

Copy folder recursively in Node.js

It looks like ncp and wrench both are no longer maintained. Probably the best option is to use fs-extra

The Developer of Wrench directs users to use fs-extra as he has deprecated his library

copySync & moveSync both will copy and move folders even if they have files or subfolders and you can easily move or copy files using it

const fse = require('fs-extra');

const srcDir = `path/to/file`;
const destDir = `path/to/destination/directory`;
                              
// To copy a folder or file  
fse.copySync(srcDir, destDir, function (err) {
  if (err) {                 ^
    console.error(err);      |___{ overwrite: true } // add if you want to replace existing folder or file with same name
  } else {
    console.log("success!");
  }
});

OR

// To copy a folder or file  
fse.moveSync(srcDir, destDir, function (err) {
  if (err) {                 ^
    console.error(err);      |___{ overwrite: true } // add if you want to replace existing folder or file with same name
  } else {
    console.log("success!");
  }
});

How to determine equality for two JavaScript objects?

How to determine that the partial object (Partial<T>) is equal to the original object (T) in typescript.

function compareTwoObjects<T>(original: T, partial: Partial<T>): boolean {
  return !Object.keys(partial).some((key) => partial[key] !== original[key]);
}

P.S. Initially I was planning to create a new question with an answer. But such a question already exists and marked as a duplicate.

JavaScript closure inside loops – simple practical example

With the support of ES6, the best way to this is to use let and const keywords for this exact circumstance. So var variable get hoisted and with the end of loop the value of i gets updated for all the closures..., we can just use let to set a loop scope variable like this:

var funcs = [];
for (let i = 0; i < 3; i++) {          
    funcs[i] = function() {            
      console.log("My value: " + i); 
    };
}

How do I monitor the computer's CPU, memory, and disk usage in Java?

Along the lines of what I mentioned in this post. I recommend you use the SIGAR API. I use the SIGAR API in one of my own applications and it is great. You'll find it is stable, well supported, and full of useful examples. It is open-source with a GPL 2 Apache 2.0 license. Check it out. I have a feeling it will meet your needs.

Using Java and the Sigar API you can get Memory, CPU, Disk, Load-Average, Network Interface info and metrics, Process Table information, Route info, etc.

Java constructor/method with optional parameters?

You can use varargs for optional parameters:

public class Booyah {
    public static void main(String[] args) {
        woohoo(1);
        woohoo(2, 3);
    }
    static void woohoo(int required, Integer... optional) {
        Integer lala;
        if (optional.length == 1) {
            lala = optional[0];
        } else {
            lala = 2;
        }
        System.out.println(required + lala);
    }
}

Also it's important to note the use of Integer over int. Integer is a wrapper around the primitive int, which allows one to make comparisons with null as necessary.

Round button with text and icon in flutter

Use Column or Row in a Button child, Row for horizontal button, Column for vertical, and dont forget to contain it with the size you need:

Container(
  width: 120.0,
  height: 30.0,
  child: RaisedButton(
    color: Color(0XFFFF0000),
    child: Row(
      children: <Widget>[
        Text('Play this song', style: TextStyle(color: Colors.white),),
        Icon(Icons.play_arrow, color: Colors.white,),
      ],
    ),
  ),
),

How to convert image to byte array

Code:

using System.IO;

byte[] img = File.ReadAllBytes(openFileDialog1.FileName);

Find a file with a certain extension in folder

As per my understanding, this can be done in two ways :

1) You can use Directory Class with Getfiles method and traverse across all files to check our required extension.

Directory.GetFiles("your_folder_path)[i].Contains("*.txt")

2) You can use Path Class with GetExtension Method which takes file path as a parameter and verifies the extension.To get the file path, just have a looping condition that will fetch a single file and return the filepath that can be used for verification.

Path.GetExtension(your_file_path).Equals(".json")

Note : Both the logic has to be inside a looping condition.

how to send an array in url request

Separate with commas:

http://localhost:8080/MovieDB/GetJson?name=Actor1,Actor2,Actor3&startDate=20120101&endDate=20120505

or:

http://localhost:8080/MovieDB/GetJson?name=Actor1&name=Actor2&name=Actor3&startDate=20120101&endDate=20120505

or:

http://localhost:8080/MovieDB/GetJson?name[0]=Actor1&name[1]=Actor2&name[2]=Actor3&startDate=20120101&endDate=20120505

Either way, your method signature needs to be:

@RequestMapping(value = "/GetJson", method = RequestMethod.GET) 
public void getJson(@RequestParam("name") String[] ticker, @RequestParam("startDate") String startDate, @RequestParam("endDate") String endDate) {
   //code to get results from db for those params.
 }

libz.so.1: cannot open shared object file

After checking to which package does the libz.so.1 belongs (http://packages.ubuntu.com/lucid/i386/zlib1g/filelist) you should try to install zlib1g:

sudo apt-get install zlib1g

As pointed by @E-rich, it may be required to add a :i386 suffix to the package name for the package manager correctly identify it:

sudo apt-get install zlib1g:i386


EDIT (for CentOS or other distro that makes use of yum):

If someone using CentOS (or any other distro that makes use of yum) that may end up reading this question, @syslogic proposed the following solution in the comments:

yum install zlib.i686

or, for 32-bit binaries:

yum install zlib.i386

Is there a concise way to iterate over a stream with indices in Java 8?

One possible way is to index each element on the flow:

AtomicInteger index = new AtomicInteger();
Stream.of(names)
  .map(e->new Object() { String n=e; public i=index.getAndIncrement(); })
  .filter(o->o.n.length()<=o.i) // or do whatever you want with pairs...
  .forEach(o->System.out.println("idx:"+o.i+" nam:"+o.n));

Using an anonymous class along a stream is not well-used while being very useful.

How to set a JVM TimeZone Properly

You can also set the default time zone in your code by using following code.

TimeZone.setDefault(TimeZone.getTimeZone("UTC"));

To Yours

 TimeZone.setDefault(TimeZone.getTimeZone("Europe/Sofia"));

What is the difference between DBMS and RDBMS?

DBMS: is a software system that allows Defining, Creation, Querying, Update, and Administration of data stored in data files.

Features:

  • Normal book keeping system, Flat files, MS Excel, FoxPRO, XML, etc.
  • Less or No provision for: Constraints, Security, ACID rules, users, etc.

RDBMS: is a DBMS that is based on Relational model that stores data in tabular form.

  • SQL Server, Sybase, Oracle, MySQL, IBM DB2, MS Access, etc.

Features:

  • Database, with Tables having relations maintained by FK
  • DDL, DML
  • Data Integrity & ACID rules
  • Multiple User Access
  • Backup & Restore
  • Database Administration

JavaScript variable number of arguments to function

Use the arguments object when inside the function to have access to all arguments passed in.

Instantly detect client disconnection from server socket

Expanding on comments by mbargiel and mycelo on the accepted answer, the following can be used with a non-blocking socket on the server end to inform whether the client has shut down.

This approach does not suffer the race condition that affects the Poll method in the accepted answer.

// Determines whether the remote end has called Shutdown
public bool HasRemoteEndShutDown
{
    get
    {
        try
        {
            int bytesRead = socket.Receive(new byte[1], SocketFlags.Peek);

            if (bytesRead == 0)
                return true;
        }
        catch
        {
            // For a non-blocking socket, a SocketException with 
            // code 10035 (WSAEWOULDBLOCK) indicates no data available.
        }

        return false;
    }
}

The approach is based on the fact that the Socket.Receive method returns zero immediately after the remote end shuts down its socket and we've read all of the data from it. From Socket.Receive documentation:

If the remote host shuts down the Socket connection with the Shutdown method, and all available data has been received, the Receive method will complete immediately and return zero bytes.

If you are in non-blocking mode, and there is no data available in the protocol stack buffer, the Receive method will complete immediately and throw a SocketException.

The second point explains the need for the try-catch.

Use of the SocketFlags.Peek flag leaves any received data untouched for a separate receive mechanism to read.

The above will work with a blocking socket as well, but be aware that the code will block on the Receive call (until data is received or the receive timeout elapses, again resulting in a SocketException).

How do I use a pipe to redirect the output of one command to the input of another?

Try this. Copy this into a batch file - such as send.bat - and then simply run send.bat to send the message from the temperature program to the prismcom program.

temperature.exe > msg.txt
set /p msg= < msg.txt
prismcom.exe usb "%msg%"

What is the use of System.in.read()?

May be this example will help you.

import java.io.IOException;

public class MainClass {

    public static void main(String[] args) {
        int inChar;
        System.out.println("Enter a Character:");
        try {
            inChar = System.in.read();
            System.out.print("You entered ");
            System.out.println(inChar);
        }
        catch (IOException e){
            System.out.println("Error reading from user");
        }
    }
}

MVC : The parameters dictionary contains a null entry for parameter 'k' of non-nullable type 'System.Int32'

It seems that your action needs k but ModelBinder can not find it (from form, or request or view data or ..) Change your action to this:

public ActionResult DetailsData(int? k)
    {

        EmployeeContext Ec = new EmployeeContext();
        if (k != null)
        {
           Employee emp = Ec.Employees.Single(X => X.EmpId == k.Value);

           return View(emp);
        }
        return View();
    }

java.lang.Exception: No runnable methods exception in running JUnits

I was able to fix by manually adding the junit jar to my project classpath. The easiest way I found to do this was by adding a /lib directory in the project root. Then i just put the junit.jar inside /lib and junit tests starting working for me.

How to count how many values per level in a given factor?

Here 2 ways to do it:

set.seed(1)
tt <- sample(letters,100,rep=TRUE)

## using table
table(tt)
tt
a b c d e f g h i j k l m n o p q r s t u v w x y z 
2 3 3 3 2 4 6 1 6 5 6 4 7 2 2 2 5 4 5 3 8 4 5 4 3 1 
## using tapply
tapply(tt,tt,length)
a b c d e f g h i j k l m n o p q r s t u v w x y z 
2 3 3 3 2 4 6 1 6 5 6 4 7 2 2 2 5 4 5 3 8 4 5 4 3 1 

c++ boost split string

The problem is somewhere else in your code, because this works:

string line("test\ttest2\ttest3");
vector<string> strs;
boost::split(strs,line,boost::is_any_of("\t"));

cout << "* size of the vector: " << strs.size() << endl;    
for (size_t i = 0; i < strs.size(); i++)
    cout << strs[i] << endl;

and testing your approach, which uses a vector iterator also works:

string line("test\ttest2\ttest3");
vector<string> strs;
boost::split(strs,line,boost::is_any_of("\t"));

cout << "* size of the vector: " << strs.size() << endl;
for (vector<string>::iterator it = strs.begin(); it != strs.end(); ++it)
{
    cout << *it << endl;
}

Again, your problem is somewhere else. Maybe what you think is a \t character on the string, isn't. I would fill the code with debugs, starting by monitoring the insertions on the vector to make sure everything is being inserted the way its supposed to be.

Output:

* size of the vector: 3
test
test2
test3

Error message: "'chromedriver' executable needs to be available in the path"

Best way for sure is here:

Download and unzip chromedriver and put 'chromedriver.exe' in C:\Python27\Scripts and then you need not to provide the path of driver, just

driver= webdriver.Chrome()

You are done no need to add paths or anything

Java default constructor

A default constructor is automatically generated by the compiler if you do not explicitly define at least one constructor in your class. You've defined two, so your class does not have a default constructor.

Per The Java Language Specification Third Edition:

8.8.9 Default Constructor

If a class contains no constructor declarations, then a default constructor that takes no parameters is automatically provided...

Can not deserialize instance of java.lang.String out of START_ARRAY token

The error is:

Can not deserialize instance of java.lang.String out of START_ARRAY token at [Source: line: 1, column: 1095] (through reference chain: JsonGen["platforms"])

In JSON, platforms look like this:

"platforms": [
    {
        "platform": "iphone"
    },
    {
        "platform": "ipad"
    },
    {
        "platform": "android_phone"
    },
    {
        "platform": "android_tablet"
    }
]

So try change your pojo to something like this:

private List platforms;

public List getPlatforms(){
    return this.platforms;
}

public void setPlatforms(List platforms){
    this.platforms = platforms;
}

EDIT: you will need change mobile_networks too. Will look like this:

private List mobile_networks;

public List getMobile_networks() {
    return mobile_networks;
}

public void setMobile_networks(List mobile_networks) {
    this.mobile_networks = mobile_networks;
}

Stored procedure return into DataSet in C# .Net

Try this

    DataSet ds = new DataSet("TimeRanges");
    using(SqlConnection conn = new SqlConnection("ConnectionString"))
    {               
            SqlCommand sqlComm = new SqlCommand("Procedure1", conn);               
            sqlComm.Parameters.AddWithValue("@Start", StartTime);
            sqlComm.Parameters.AddWithValue("@Finish", FinishTime);
            sqlComm.Parameters.AddWithValue("@TimeRange", TimeRange);

            sqlComm.CommandType = CommandType.StoredProcedure;

            SqlDataAdapter da = new SqlDataAdapter();
            da.SelectCommand = sqlComm;

            da.Fill(ds);
     }

Best practice: PHP Magic Methods __set and __get

I use __get (and public properties) as much as possible, because they make code much more readable. Compare:

this code unequivocally says what i'm doing:

echo $user->name;

this code makes me feel stupid, which i don't enjoy:

function getName() { return $this->_name; }
....

echo $user->getName();

The difference between the two is particularly obvious when you access multiple properties at once.

echo "
    Dear $user->firstName $user->lastName!
    Your purchase:
        $product->name  $product->count x $product->price
"

and

echo "
    Dear " . $user->getFirstName() . " " . $user->getLastName() . "
    Your purchase: 
        " . $product->getName() . " " . $product->getCount() . "  x " . $product->getPrice() . " ";

Whether $a->b should really do something or just return a value is the responsibility of the callee. For the caller, $user->name and $user->accountBalance should look the same, although the latter may involve complicated calculations. In my data classes i use the following small method:

 function __get($p) { 
      $m = "get_$p";
      if(method_exists($this, $m)) return $this->$m();
      user_error("undefined property $p");
 }

when someone calls $obj->xxx and the class has get_xxx defined, this method will be implicitly called. So you can define a getter if you need it, while keeping your interface uniform and transparent. As an additional bonus this provides an elegant way to memorize calculations:

  function get_accountBalance() {
      $result = <...complex stuff...>
      // since we cache the result in a public property, the getter will be called only once
      $this->accountBalance = $result;
  }

  ....


   echo $user->accountBalance; // calculate the value
   ....
   echo $user->accountBalance; // use the cached value

Bottom line: php is a dynamic scripting language, use it that way, don't pretend you're doing Java or C#.

POST unchecked HTML checkboxes

Checkboxes usually represent binary data that are stored in database as Yes/No, Y/N or 1/0 values. HTML checkboxes do have bad nature to send value to server only if checkbox is checked! That means that server script on other site must know in advance what are all possible checkboxes on web page in order to be able to store positive (checked) or negative (unchecked) values. Actually only negative values are problem (when user unchecks previously (pre)checked value - how can server know this when nothing is sent if it does not know in advance that this name should be sent). If you have a server side script which dynamically creates UPDATE script there's a problem because you don't know what all checkboxes should be received in order to set Y value for checked and N value for unchecked (not received) ones.

Since I store values 'Y' and 'N' in my database and represent them via checked and unchecked checkboxes on page, I added hidden field for each value (checkbox) with 'Y' and 'N' values then use checkboxes just for visual representation, and use simple JavaScript function check() to set value of if according to selection.

<input type="hidden" id="N1" name="N1" value="Y" />
<input type="checkbox"<?php if($N1==='Y') echo ' checked="checked"'; ?> onclick="check(this);" />
<label for="N1">Checkbox #1</label>

use one JavaScript onclick listener and call function check() for each checkboxe on my web page:

function check(me)
{
  if(me.checked)
  {
    me.previousSibling.previousSibling.value='Y';
  }
  else
  {
    me.previousSibling.previousSibling.value='N';
  }
}

This way 'Y' or 'N' values are always sent to server side script, it knows what are fields that should be updated and there's no need for conversion of checbox "on" value into 'Y' or not received checkbox into 'N'.

NOTE: white space or new line is also a sibling so here I need .previousSibling.previousSibling.value. If there's no space between then only .previousSibling.value


You don't need to explicitly add onclick listener like before, you can use jQuery library to dynamically add click listener with function to change value to all checkboxes in your page:

$('input[type=checkbox]').click(function()
{
  if(this.checked)
  {
    $(this).prev().val('Y');
  }
  else
  {
    $(this).prev().val('N');
  }
});

PHP cURL not working - WAMP on Windows 7 64 bit

Ensure that your system PATH environment variable contains the directory in which PHP is installed. Stop the Apache server and restart it once more. With luck CURL will start working.

UITableView set to static cells. Is it possible to hide some of the cells programmatically?

The best way is as described in the following blog http://ali-reynolds.com/2013/06/29/hide-cells-in-static-table-view/

Design your static table view as normal in interface builder – complete with all potentially hidden cells. But there is one thing you must do for every potential cell that you want to hide – check the “Clip subviews” property of the cell, otherwise the content of the cell doesn’t disappear when you try and hide it (by shrinking it’s height – more later).

SO – you have a switch in a cell and the switch is supposed to hide and show some static cells. Hook it up to an IBAction and in there do this:

[self.tableView beginUpdates];
[self.tableView endUpdates];

That gives you nice animations for the cells appearing and disappearing. Now implement the following table view delegate method:

- (float)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 1 && indexPath.row == 1) { // This is the cell to hide - change as you need
    // Show or hide cell
        if (self.mySwitch.on) {
            return 44; // Show the cell - adjust the height as you need
        } else {
            return 0; // Hide the cell
        }
   }
   return 44;
}

And that’s it. Flip the switch and the cell hides and reappears with a nice, smooth animation.

Positioning the colorbar

The best way to get good control over the colorbar position is to give it its own axis. Like so:

# What I imagine your plotting looks like so far
fig = plt.figure()
ax1 = fig.add_subplot(111)
ax1.plot(your_data)

# Now adding the colorbar
cbaxes = fig.add_axes([0.8, 0.1, 0.03, 0.8]) 
cb = plt.colorbar(ax1, cax = cbaxes)  

The numbers in the square brackets of add_axes refer to [left, bottom, width, height], where the coordinates are just fractions that go from 0 to 1 of the plotting area.

Assign pandas dataframe column dtypes

You're better off using typed np.arrays, and then pass the data and column names as a dictionary.

import numpy as np
import pandas as pd
# Feature: np arrays are 1: efficient, 2: can be pre-sized
x = np.array(['a', 'b'], dtype=object)
y = np.array([ 1 ,  2 ], dtype=np.int32)
df = pd.DataFrame({
   'x' : x,    # Feature: column name is near data array
   'y' : y,
   }
 )