Programs & Examples On #Web frameworks

A web application framework is a software framework that is designed to support the development of dynamic websites, web applications and web services. The framework aims to alleviate the overhead associated with common activities performed in Web development.

Can anyone recommend a simple Java web-app framework?

Grails is the way to go if you like to do the CRUD easily and create a quick prototype application, plays nice with Eclipse as well. Follow the 'Build your first Grails application' tutorial here http://grails.org/Tutorials and you can be up and running your own application in less than an hour.

What Scala web-frameworks are available?

Prikrutil, I think we're on the same boat. I also come to Scala from Erlang. I like Nitrogen a lot so I decided to created a Scala web framework inspired by it.

Take a look at Xitrum. Its doc is quite extensive. From README:

Xitrum is an async and clustered Scala web framework and web server on top of Netty and Hazelcast:

  • It fills the gap between Scalatra and Lift: more powerful than Scalatra and easier to use than Lift. You can easily create both RESTful APIs and postbacks. Xitrum is controller-first like Scalatra, not view-first like Lift.
  • Annotation is used for URL routes, in the spirit of JAX-RS. You don't have to declare all routes in a single place.
  • Typesafe, in the spirit of Scala.
  • Async, in the spirit of Netty.
  • Sessions can be stored in cookies or clustered Hazelcast.
  • jQuery Validation is integrated for browser side and server side validation. i18n using GNU gettext, which means unlike most other solutions, both singular and plural forms are supported.
  • Conditional GET using ETag.

Hazelcast also gives:

  • In-process and clustered cache, you don't need separate cache servers.
  • In-process and clustered Comet, you can scale Comet to multiple web servers.

Follow the tutorial for a quick start.

How can I insert new line/carriage returns into an element.textContent?

nelek's answer is the best one posted so far, but it relies on setting the css value: white-space: pre, which might be undesirable.

I'd like to offer a different solution, which tries to tackle the real question that should've been asked here:

"How to insert untrusted text into a DOM element?"

If you trust the text, why not just use innerHTML?

domElement.innerHTML = trustedText.replace(/\r/g, '').replace(/\n/g, '<br>');

should be sufficient for all the reasonable cases.

If you decided you should use .textContent instead of .innerHTML, it means you don't trust the text that you're about to insert, right? This is a reasonable concern.

For example, you have a form where the user can create a post, and after posting it, the post text is stored in your database, and later on appended to pages whenever other users visit the relevant page.

If you use innerHTML here, you get a security breach. i.e., a user can post something like

[script]alert(1);[/script]

(try to imagine that [] are <>, apparently stack overflow is appending text in unsafe ways!)

which won't trigger an alert if you use innerHTML, but it should give you an idea why using innerHTML can have issues. a smarter user would post

[img src="invalid_src" onerror="alert(1)"]

which would trigger an alert for every other user that visits the page. Now we have a problem. An even smarter user would put display: none on that img style, and make it post the current user's cookies to a cross domain site. Congratulations, all your user login details are now exposed on the internet.

So, the important thing to understand is, using innerHTML isn't wrong, it's perfect if you're just using it to build templates using only your own trusted developer code. The real question should've been "how do I append untrusted user text that has newlines to my HTML document".

This raises a question: which strategy do we use for newlines? do we use [br] elements? [p]s or [div]s?

Here is a short function that solves the problem:

function insertUntrustedText(domElement, untrustedText, newlineStrategy) {
    domElement.innerHTML = '';
    var lines = untrustedText.replace(/\r/g, '').split('\n');
    var linesLength = lines.length;
    if(newlineStrategy === 'br') {
        for(var i = 0; i < linesLength; i++) {
            domElement.appendChild(document.createTextNode(lines[i]));
            domElement.appendChild(document.createElement('br'));
        }
    }
    else {
        for(var i = 0; i < linesLength; i++) {
            var lineElement = document.createElement(newlineStrategy);
            lineElement.textContent = lines[i];
            domElement.appendChild(lineElement);
        }
    }
}

You can basically throw this somewhere in your common_functions.js file and then just fire and forget whenever you need to append any user/api/etc -> untrusted text (i.e. not-written-by-your-own-developer-team) to your html pages.

usage example:

insertUntrustedText(document.querySelector('.myTextParent'), 'line1\nline2\r\nline3', 'br');

the parameter newlineStrategy accepts only valid dom element tags, so if you want [br] newlines, pass 'br', if you want each line in a [p] element, pass 'p', etc.

Get program path in VB.NET?

Try this: My.Application.Info.DirectoryPath [MSDN]

This is using the My feature of VB.NET. This particular property is available for all non-web project types, since .NET Framework 2.0, including Console Apps as you require.

As long as you trust Microsoft to continue to keep this working correctly for all the above project types, this is simpler to use than accessing the other "more direct" solutions.

Dim appPath As String = My.Application.Info.DirectoryPath

Convert date time string to epoch in Bash

A lot of these answers overly complicated and also missing how to use variables. This is how you would do it more simply on standard Linux system (as previously mentioned the date command would have to be adjusted for Mac Users) :

Sample script:

#!/bin/bash
orig="Apr 28 07:50:01"
epoch=$(date -d "${orig}" +"%s")
epoch_to_date=$(date -d @$epoch +%Y%m%d_%H%M%S)    

echo "RESULTS:"
echo "original = $orig"
echo "epoch conv = $epoch"
echo "epoch to human readable time stamp = $epoch_to_date"

Results in :

RESULTS:
original = Apr 28 07:50:01
epoch conv = 1524916201 
epoch to human readable time stamp = 20180428_075001

Or as a function :

# -- Converts from human to epoch or epoch to human, specifically "Apr 28 07:50:01" human.
#    typeset now=$(date +"%s")
#    typeset now_human_date=$(convert_cron_time "human" "$now")

function convert_cron_time() {
    case "${1,,}" in
        epoch)
            # human to epoch (eg. "Apr 28 07:50:01" to 1524916201)
            echo $(date -d "${2}" +"%s")
            ;;
        human)
            # epoch to human (eg. 1524916201 to "Apr 28 07:50:01")
            echo $(date -d "@${2}" +"%b %d %H:%M:%S")
            ;;
    esac
}

Excel Calculate the date difference from today from a cell of "7/6/2012 10:26:42"

You can use the datedif function to find out difference in days.

=DATEDIF(A1,TODAY(),"d")

Quote from excel.datedif.com

The mysterious datedif function in Microsoft Excel

The Datedif function is used to calculate interval between two dates in days, months or years.

This function is available in all versions of Excel but is not documented. It is not even listed in the "Insert Function" dialog box. Hence it must be typed manually in the formula box. Syntax

DATEDIF( start_date, end_date, interval_unit )

start_date from date end_date to date (must be after start_date) interval_unit Unit to be used for output interval Values for interval_unit

interval_unit Description

D Number of days

M Number of complete months

Y Number of complete years

YD Number of days excluding years

MD Number of days excluding months and years

YM Number of months excluding years

Errors

Error Description

#NUM! The end_date is later than (greater than) the start_date or interval_unit has an invalid value. #VALUE! end_date or start_date is invalid.

PHP Date Time Current Time Add Minutes

This is an old question that seems answered, but as someone pointed out above, if you use the DateTime class and PHP < 5.3.0, you can't use the add method, but you can use modify:

$date = new DateTime();
$date->modify("+30 minutes"); //or whatever value you want

How do I export (and then import) a Subversion repository?

Assuming you have the necessary privileges to run svnadmin, you need to use the dump and load commands.

Convert string to binary then back again using PHP

Your hash is already binary and ready to be used with your database.

However you must need to convert it into a format the database column definition expects.

Any string in PHP (until 5.3) is a binary string. That means it contains only binary data.

However because of backwards compatiblity with PHP 6 you can already cast your string explicitly as binary:

 $string = 'my binary string';
 $binary = b'my binary string';

But that is merely for compatibility reasons, in your code you can just do:

  $string = $binary; // "convert" binary string into string
  $binary = $string  // "convert" string into binary string

Because it's the same. The "convert" is superfluous.

How to pass a value to razor variable from javascript variable?

Razor View Server Side variable can be read to Client Side JavaScript using @ While and JavaScript client side variable can read to Razor View using @:

How can I put a ListView into a ScrollView without it collapsing?

There are plenty of situations where it makes a lot of sense to have ListView's in a ScrollView.

Here's code based on DougW's suggestion... works in a fragment, takes less memory.

public static void setListViewHeightBasedOnChildren(ListView listView) {
    ListAdapter listAdapter = listView.getAdapter();
    if (listAdapter == null) {
        return;
    }
    int desiredWidth = MeasureSpec.makeMeasureSpec(listView.getWidth(), MeasureSpec.AT_MOST);
    int totalHeight = 0;
    View view = null;
    for (int i = 0; i < listAdapter.getCount(); i++) {
        view = listAdapter.getView(i, view, listView);
        if (i == 0) {
            view.setLayoutParams(new ViewGroup.LayoutParams(desiredWidth, LayoutParams.WRAP_CONTENT));
        }
        view.measure(desiredWidth, MeasureSpec.UNSPECIFIED);
        totalHeight += view.getMeasuredHeight();
    }
    ViewGroup.LayoutParams params = listView.getLayoutParams();
    params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
    listView.setLayoutParams(params);
    listView.requestLayout();
}

call setListViewHeightBasedOnChildren(listview) on each embedded listview.

std::vector versus std::array in C++

Using the std::vector<T> class:

  • ...is just as fast as using built-in arrays, assuming you are doing only the things built-in arrays allow you to do (read and write to existing elements).

  • ...automatically resizes when new elements are inserted.

  • ...allows you to insert new elements at the beginning or in the middle of the vector, automatically "shifting" the rest of the elements "up"( does that make sense?). It allows you to remove elements anywhere in the std::vector, too, automatically shifting the rest of the elements down.

  • ...allows you to perform a range-checked read with the at() method (you can always use the indexers [] if you don't want this check to be performed).

There are two three main caveats to using std::vector<T>:

  1. You don't have reliable access to the underlying pointer, which may be an issue if you are dealing with third-party functions that demand the address of an array.

  2. The std::vector<bool> class is silly. It's implemented as a condensed bitfield, not as an array. Avoid it if you want an array of bools!

  3. During usage, std::vector<T>s are going to be a bit larger than a C++ array with the same number of elements. This is because they need to keep track of a small amount of other information, such as their current size, and because whenever std::vector<T>s resize, they reserve more space then they need. This is to prevent them from having to resize every time a new element is inserted. This behavior can be changed by providing a custom allocator, but I never felt the need to do that!


Edit: After reading Zud's reply to the question, I felt I should add this:

The std::array<T> class is not the same as a C++ array. std::array<T> is a very thin wrapper around C++ arrays, with the primary purpose of hiding the pointer from the user of the class (in C++, arrays are implicitly cast as pointers, often to dismaying effect). The std::array<T> class also stores its size (length), which can be very useful.

Jquery $.ajax fails in IE on cross domain calls

Add extra transport to jquery for IE. ( Just add this code in your script at the end )

$.ajaxTransport("+*", function( options, originalOptions, jqXHR ) {

    if(jQuery.browser.msie && window.XDomainRequest) {

        var xdr;

        return {

            send: function( headers, completeCallback ) {

                // Use Microsoft XDR
                xdr = new XDomainRequest();

                xdr.open("get", options.url);

                xdr.onload = function() {

                    if(this.contentType.match(/\/xml/)){

                        var dom = new ActiveXObject("Microsoft.XMLDOM");
                        dom.async = false;
                        dom.loadXML(this.responseText);
                        completeCallback(200, "success", [dom]);

                    }else{

                        completeCallback(200, "success", [this.responseText]);

                    }

                };

                xdr.ontimeout = function(){
                    completeCallback(408, "error", ["The request timed out."]);
                };

                xdr.onerror = function(){
                    completeCallback(404, "error", ["The requested resource could not be found."]);
                };

                xdr.send();
          },
          abort: function() {
              if(xdr)xdr.abort();
          }
        };
      }
    });

This solved my problem with Jquery $.ajax failing for Cross Domain AJAX request.

Cheers.

Remove innerHTML from div

jQuery Data is a different concept than HTML. removeData is not for removing element content, it's for removing data items you've previously stored.

Just do

divToUpdate.html("");

or

divToUpdate.empty();

How to vertically center a container in Bootstrap?

The Flexible box way

Vertical alignment is now very simple by the use of Flexible box layout. Nowadays, this method is supported in a wide range of web browsers except Internet Explorer 8 & 9. Therefore we'd need to use some hacks/polyfills or different approaches for IE8/9.

In the following I'll show you how to do that in only 3 lines of text (regardless of old flexbox syntax).

Note: it's better to use an additional class instead of altering .jumbotron to achieve the vertical alignment. I'd use vertical-center class name for instance.

Example Here (A Mirror on jsbin).

<div class="jumbotron vertical-center"> <!-- 
                      ^--- Added class  -->
  <div class="container">
    ...
  </div>
</div>
.vertical-center {
  min-height: 100%;  /* Fallback for browsers do NOT support vh unit */
  min-height: 100vh; /* These two lines are counted as one :-)       */

  display: flex;
  align-items: center;
}

Important notes (Considered in the demo):

  1. A percentage values of height or min-height properties is relative to the height of the parent element, therefore you should specify the height of the parent explicitly.

  2. Vendor prefixed / old flexbox syntax omitted in the posted snippet due to brevity, but exist in the online example.

  3. In some of old web browsers such as Firefox 9 (in which I've tested), the flex container - .vertical-center in this case - won't take the available space inside the parent, therefore we need to specify the width property like: width: 100%.

  4. Also in some of web browsers as mentioned above, the flex item - .container in this case - may not appear at the center horizontally. It seems the applied left/right margin of auto doesn't have any effect on the flex item.
    Therefore we need to align it by box-pack / justify-content.

For further details and/or vertical alignment of columns, you could refer to the topic below:


The traditional way for legacy web browsers

This is the old answer I wrote at the time I answered this question. This method has been discussed here and it's supposed to work in Internet Explorer 8 and 9 as well. I'll explain it in short:

In inline flow, an inline level element can be aligned vertically to the middle by vertical-align: middle declaration. Spec from W3C:

middle
Align the vertical midpoint of the box with the baseline of the parent box plus half the x-height of the parent.

In cases that the parent - .vertical-center element in this case - has an explicit height, by any chance if we could have a child element having the exact same height of the parent, we would be able to move the baseline of the parent to the midpoint of the full-height child and surprisingly make our desired in-flow child - the .container - aligned to the center vertically.

Getting all together

That being said, we could create a full-height element within the .vertical-center by ::before or ::after pseudo elements and also change the default display type of it and the other child, the .container to inline-block.

Then use vertical-align: middle; to align the inline elements vertically.

Here you go:

<div class="jumbotron vertical-center">
  <div class="container">
    ...
  </div>
</div>
.vertical-center {
  height:100%;
  width:100%;

  text-align: center;  /* align the inline(-block) elements horizontally */
  font: 0/0 a;         /* remove the gap between inline(-block) elements */
}

.vertical-center:before {    /* create a full-height inline block pseudo=element */
  content: " ";
  display: inline-block;
  vertical-align: middle;    /* vertical alignment of the inline element */
  height: 100%;
}

.vertical-center > .container {
  max-width: 100%;

  display: inline-block;
  vertical-align: middle;  /* vertical alignment of the inline element */
                           /* reset the font property */
  font: 16px/1 "Helvetica Neue", Helvetica, Arial, sans-serif;
}

WORKING DEMO.

Also, to prevent unexpected issues in extra small screens, you can reset the height of the pseudo-element to auto or 0 or change its display type to none if needed so:

@media (max-width: 768px) {
  .vertical-center:before {
    height: auto;
    /* Or */
    display: none;
  }
}

UPDATED DEMO

And one more thing:

If there are footer/header sections around the container, it's better to position that elements properly (relative, absolute? up to you.) and add a higher z-index value (for assurance) to keep them always on the top of the others.

How can I create an array/list of dictionaries in python?

I assume that motifWidth contains an integer.

In Python, lists do not change size unless you tell them to. Hence, Python throws an exception when you try to change an element that isn't there. I believe you want:

weightMatrix = []
for k in range(motifWidth):
    weightMatrix.append({'A':0,'C':0,'G':0,'T':0})

For what it's worth, when asking questions in the future, it would help if you included the stack trace showing the error that you're getting rather than just saying "it isn't working". That would help us directly figure out the cause of the problem, rather than trying to puzzle it out from your code.

Hope that helps!

Extract csv file specific columns to list in Python

This looks like a problem with line endings in your code. If you're going to be using all these other scientific packages, you may as well use Pandas for the CSV reading part, which is both more robust and more useful than just the csv module:

import pandas
colnames = ['year', 'name', 'city', 'latitude', 'longitude']
data = pandas.read_csv('test.csv', names=colnames)

If you want your lists as in the question, you can now do:

names = data.name.tolist()
latitude = data.latitude.tolist()
longitude = data.longitude.tolist()

Display Last Saved Date on worksheet

thought I would update on this.

Found out that adding to the VB Module behind the spreadsheet does not actually register as a Macro.

So here is the solution:

  1. Press ALT + F11
  2. Click Insert > Module
  3. Paste the following into the window:

Code

Function LastSavedTimeStamp() As Date
  LastSavedTimeStamp = ActiveWorkbook.BuiltinDocumentProperties("Last Save Time")
End Function
  1. Save the module, close the editor and return to the worksheet.
  2. Click in the Cell where the date is to be displayed and enter the following formula:

Code

=LastSavedTimeStamp()

Bitwise operation and usage

Bit representations of integers are often used in scientific computing to represent arrays of true-false information because a bitwise operation is much faster than iterating through an array of booleans. (Higher level languages may use the idea of a bit array.)

A nice and fairly simple example of this is the general solution to the game of Nim. Take a look at the Python code on the Wikipedia page. It makes heavy use of bitwise exclusive or, ^.

How to get the ASCII value of a character

The accepted answer is correct, but there is a more clever/efficient way to do this if you need to convert a whole bunch of ASCII characters to their ASCII codes at once. Instead of doing:

for ch in mystr:
    code = ord(ch)

or the slightly faster:

for code in map(ord, mystr):

you convert to Python native types that iterate the codes directly. On Python 3, it's trivial:

for code in mystr.encode('ascii'):

and on Python 2.6/2.7, it's only slightly more involved because it doesn't have a Py3 style bytes object (bytes is an alias for str, which iterates by character), but they do have bytearray:

# If mystr is definitely str, not unicode
for code in bytearray(mystr):

# If mystr could be either str or unicode
for code in bytearray(mystr, 'ascii'):

Encoding as a type that natively iterates by ordinal means the conversion goes much faster; in local tests on both Py2.7 and Py3.5, iterating a str to get its ASCII codes using map(ord, mystr) starts off taking about twice as long for a len 10 str than using bytearray(mystr) on Py2 or mystr.encode('ascii') on Py3, and as the str gets longer, the multiplier paid for map(ord, mystr) rises to ~6.5x-7x.

The only downside is that the conversion is all at once, so your first result might take a little longer, and a truly enormous str would have a proportionately large temporary bytes/bytearray, but unless this forces you into page thrashing, this isn't likely to matter.

How can I align all elements to the left in JPanel?

The easiest way I've found to place objects on the left is using FlowLayout.

JPanel panel = new JPanel(new FlowLayout(FlowLayout.LEFT));

adding a component normally to this panel will place it on the left

Appending to an object

Do you have the ability to change the outer-most structure to an array? So it would look like this

var alerts = [{"app":"helloworld","message":null},{"app":"helloagain","message":"another message"}];

So when you needed to add one, you can just push it onto the array

alerts.push( {"app":"goodbyeworld","message":"cya"} );

Then you have a built-in zero-based index for how the errors are enumerated.

nodejs module.js:340 error: cannot find module

I had the same problem, but finally I tried copying the Node_modules folder in the same project folder, and it worked.

How to pass parameters to ThreadStart method in Thread?

According to your question...

How to pass parameters to Thread.ThreadStart() method in C#?

...and the error you encountered, you would have to correct your code from

Thread thread = new Thread(new ThreadStart(download(filename));

to

Thread thread = new Thread(new ThreadStart(download));
thread.Start(filename);



However, the question is more complex as it seems at first.

The Thread class currently (4.7.2) provides several constructors and a Start method with overloads.

These relevant constructors for this question are:

public Thread(ThreadStart start);

and

public Thread(ParameterizedThreadStart start);

which either take a ThreadStart delegate or a ParameterizedThreadStart delegate.

The corresponding delegates look like this:

public delegate void ThreadStart();
public delegate void ParameterizedThreadStart(object obj);

So as can be seen, the correct constructor to use seems to be the one taking a ParameterizedThreadStart delegate so that some method conform to the specified signature of the delegate can be started by the thread.

A simple example for instanciating the Thread class would be

Thread thread = new Thread(new ParameterizedThreadStart(Work));

or just

Thread thread = new Thread(Work);

The signature of the corresponding method (called Work in this example) looks like this:

private void Work(object data)
{
   ...
}

What is left is to start the thread. This is done by using either

public void Start();

or

public void Start(object parameter);

While Start() would start the thread and pass null as data to the method, Start(...) can be used to pass anything into the Work method of the thread.

There is however one big problem with this approach: Everything passed into the Work method is cast into an object. That means within the Work method it has to be cast to the original type again like in the following example:

public static void Main(string[] args)
{
    Thread thread = new Thread(Work);

    thread.Start("I've got some text");
    Console.ReadLine();
}

private static void Work(object data)
{
    string message = (string)data; // Wow, this is ugly

    Console.WriteLine($"I, the thread write: {message}");
}



Casting is something you typically do not want to do.

What if someone passes something else which is not a string? As this seems not possible at first (because It is my method, I know what I do or The method is private, how should someone ever be able to pass anything to it?) you may possibly end up with exactly that case for various reasons. As some cases may not be a problem, others are. In such cases you will probably end up with an InvalidCastException which you probably will not notice because it simply terminates the thread.

As a solution you would expect to get a generic ParameterizedThreadStart delegate like ParameterizedThreadStart<T> where T would be the type of data you want to pass into the Work method. Unfortunately something like this does not exist (yet?).

There is however a suggested solution to this issue. It involves creating a class which contains both, the data to be passed to the thread as well as the method that represents the worker method like this:

public class ThreadWithState
{
    private string message;

    public ThreadWithState(string message)
    {
        this.message = message;
    }

    public void Work()
    {
        Console.WriteLine($"I, the thread write: {this.message}");
    }
}

With this approach you would start the thread like this:

ThreadWithState tws = new ThreadWithState("I've got some text");
Thread thread = new Thread(tws.Work);

thread.Start();

So in this way you simply avoid casting around and have a typesafe way of providing data to a thread ;-)

What primitive data type is time_t?

Unfortunately, it's not completely portable. It's usually integral, but it can be any "integer or real-floating type".

subsampling every nth entry in a numpy array

You can use numpy's slicing, simply start:stop:step.

>>> xs
array([1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4])
>>> xs[1::4]
array([2, 2, 2])

This creates a view of the the original data, so it's constant time. It'll also reflect changes to the original array and keep the whole original array in memory:

>>> a
array([1, 2, 3, 4, 5])
>>> b = a[::2]         # O(1), constant time
>>> b[:] = 0           # modifying the view changes original array
>>> a                  # original array is modified
array([0, 2, 0, 4, 0])

so if either of the above things are a problem, you can make a copy explicitly:

>>> a
array([1, 2, 3, 4, 5])
>>> b = a[::2].copy()  # explicit copy, O(n)
>>> b[:] = 0           # modifying the copy
>>> a                  # original is intact
array([1, 2, 3, 4, 5])

This isn't constant time, but the result isn't tied to the original array. The copy also contiguous in memory, which can make some operations on it faster.

Using If/Else on a data frame

Try this

frame$twohouses <- ifelse(frame$data>1, 2, 1)
 frame
   data twohouses
1     0         1
2     1         1
3     2         2
4     3         2
5     4         2
6     2         2
7     3         2
8     1         1
9     4         2
10    3         2
11    2         2
12    4         2
13    0         1
14    1         1
15    2         2
16    0         1
17    2         2
18    1         1
19    2         2
20    0         1
21    4         2

Can I pass an argument to a VBScript (vbs file launched with cscript)?

You can use WScript.Arguments to access the arguments passed to your script.

Calling the script:

cscript.exe test.vbs "C:\temp\"

Inside your script:

Set File = FSO.OpenTextFile(WScript.Arguments(0) &"\test.txt", 2, True)

Don't forget to check if there actually has been an argument passed to your script. You can do so by checking the Count property:

if WScript.Arguments.Count = 0 then
    WScript.Echo "Missing parameters"
end if

If your script is over after you close the file then there is no need to set the variables to Nothing. The resources will be cleaned up automatically when the cscript.exe process terminates. Setting a variable to Nothing usually is only necessary if you explicitly want to free resources during the execution of your script. In that case, you would set variables which contain a reference to a COM object to Nothing, which would release the COM object before your script terminates. This is just a short answer to your bonus question, you will find more information in these related questions:

Is there a need to set Objects to Nothing inside VBA Functions

When must I set a variable to “Nothing” in VB6?

Substring in excel

I believe we can start from basic to achieve desired result.

For example, I had a situation to extract data after "/". The given excel field had a value of 2rko6xyda14gdl7/VEERABABU%20MATCHA%20IN131621.jpg . I simply wanted to extract the text from "I5" cell after slash symbol. So firstly I want to find where "/" symbol is (FIND("/",I5). This gives me the position of "/". Then I should know the length of text, which i can get by LEN(I5).so total length minus the position of "/" . which is LEN(I5)-(FIND("/",I5)) . This will first find the "/" position and then get me the total text that needs to be extracted. The RIGHT function is RIGHT(I5,12) will simply extract all the values of last 12 digits starting from right most character. So I will replace the above function "LEN(I5)-(FIND("/",I5))" for 12 number in the RIGHT function to get me dynamically the number of characters I need to extract in any given cell and my solution is presented as given below

The approach was

=RIGHT(I5,LEN(I5)-(FIND("/",I5))) will give me out as VEERABABU%20MATCHA%20IN131621.jpg . I think I am clear.

break statement in "if else" - java

The issue is that you are trying to have multiple statements in an if without using {}. What you currently have is interpreted like:

if( choice==5 )
{
    System.out.println( ... );
}
break;
else
{
    //...
}

You really want:

if( choice==5 )
{
    System.out.println( ... );
    break;
}
else
{
    //...
}

Also, as Farce has stated, it would be better to use else if for all the conditions instead of if because if choice==1, it will still go through and check if choice==5, which would fail, and it will still go into your else block.

if( choice==1 )
    //...
else if( choice==2 )
    //...
else if( choice==3 )
    //...
else if( choice==4 )
    //...
else if( choice==5 )
{
    //...
}
else
    //...

A more elegant solution would be using a switch statement. However, break only breaks from the most inner "block" unless you use labels. So you want to label your loop and break from that if the case is 5:

LOOP:
for(;;)
{
    System.out.println("---> Your choice: ");
    choice = input.nextInt();
    switch( choice )
    {
        case 1:
            playGame();
            break;
        case 2:
            loadGame();
            break;
        case 2:
            options();
            break;
        case 4:
            credits();
            break;
        case 5:
            System.out.println("End of Game\n Thank you for playing with us!");
            break LOOP;
        default:
            System.out.println( ... );
    }
}

Instead of labeling the loop, you could also use a flag to tell the loop to stop.

bool finished = false;
while( !finished )
{
    switch( choice )
    {
        // ...
        case 5:
            System.out.println( ... )
            finished = true;
            break;
        // ...
    }
}

Custom Date Format for Bootstrap-DatePicker

I solve it editing the file bootstrap-datapicker.js.

Look for the text bellow in the file and edit the variable "Format:"

var defaults = $.fn.datepicker.defaults = {
    assumeNearbyYear: false,
    autoclose: false,
    beforeShowDay: $.noop,
    beforeShowMonth: $.noop,
    beforeShowYear: $.noop,
    beforeShowDecade: $.noop,
    beforeShowCentury: $.noop,
    calendarWeeks: false,
    clearBtn: false,
    toggleActive: false,
    daysOfWeekDisabled: [],
    daysOfWeekHighlighted: [],
    datesDisabled: [],
    endDate: Infinity,
    forceParse: true,
    format: 'dd/mm/yyyy',
    keyboardNavigation: true,
    language: 'en',
    minViewMode: 0,
    maxViewMode: 4,
    multidate: false,
    multidateSeparator: ',',
    orientation: "auto",
    rtl: false,
    startDate: -Infinity,
    startView: 0,
    todayBtn: false,
    todayHighlight: false,
    weekStart: 0,
    disableTouchKeyboard: false,
    enableOnReadonly: true,
    showOnFocus: true,
    zIndexOffset: 10,
    container: 'body',
    immediateUpdates: false,
    title: '',
    templates: {
        leftArrow: '&laquo;',
        rightArrow: '&raquo;'
    }
};

Iterate over each line in a string in PHP

It's overly-complicated and ugly but in my opinion this is the way to go:

$fp = fopen("php://memory", 'r+');
fputs($fp, $data);
rewind($fp);
while($line = fgets($fp)){
  // deal with $line
}
fclose($fp);

Check if TextBox is empty and return MessageBox?

Adding on to what @tjg184 said, you could do something like...

if (String.IsNullOrEmpty(MaterialTextBox.Text.Trim())) 

...

Sort array by firstname (alphabetically) in Javascript

If compared strings contain unicode characters you can use localeCompare function of String class like the following:

users.sort(function(a,b){
    return a.firstname.localeCompare(b.firstname);
})

String MinLength and MaxLength validation don't work (asp.net mvc)

Try using this attribute, for example for password min length:

[StringLength(100, ErrorMessage = "???????????? ????? ?????? 20 ????????", MinimumLength = User.PasswordMinLength)]

What are access specifiers? Should I inherit with private, protected or public?

what are Access Specifiers?

There are 3 access specifiers for a class/struct/Union in C++. These access specifiers define how the members of the class can be accessed. Of course, any member of a class is accessible within that class(Inside any member function of that same class). Moving ahead to type of access specifiers, they are:

Public - The members declared as Public are accessible from outside the Class through an object of the class.

Protected - The members declared as Protected are accessible from outside the class BUT only in a class derived from it.

Private - These members are only accessible from within the class. No outside Access is allowed.

An Source Code Example:

class MyClass
{
    public:
        int a;
    protected:
        int b;
    private:
        int c;
};

int main()
{
    MyClass obj;
    obj.a = 10;     //Allowed
    obj.b = 20;     //Not Allowed, gives compiler error
    obj.c = 30;     //Not Allowed, gives compiler error
}

Inheritance and Access Specifiers

Inheritance in C++ can be one of the following types:

  • Private Inheritance
  • Public Inheritance
  • Protected inheritance

Here are the member access rules with respect to each of these:

First and most important rule Private members of a class are never accessible from anywhere except the members of the same class.

Public Inheritance:

All Public members of the Base Class become Public Members of the derived class &
All Protected members of the Base Class become Protected Members of the Derived Class.

i.e. No change in the Access of the members. The access rules we discussed before are further then applied to these members.

Code Example:

Class Base
{
    public:
        int a;
    protected:
        int b;
    private:
        int c;
};

class Derived:public Base
{
    void doSomething()
    {
        a = 10;  //Allowed 
        b = 20;  //Allowed
        c = 30;  //Not Allowed, Compiler Error
    }
};

int main()
{
    Derived obj;
    obj.a = 10;  //Allowed
    obj.b = 20;  //Not Allowed, Compiler Error
    obj.c = 30;  //Not Allowed, Compiler Error

}

Private Inheritance:

All Public members of the Base Class become Private Members of the Derived class &
All Protected members of the Base Class become Private Members of the Derived Class.

An code Example:

Class Base
{
    public:
      int a;
    protected:
      int b;
    private:
      int c;
};

class Derived:private Base   //Not mentioning private is OK because for classes it  defaults to private 
{
    void doSomething()
    {
        a = 10;  //Allowed 
        b = 20;  //Allowed
        c = 30;  //Not Allowed, Compiler Error
    }
};

class Derived2:public Derived
{
    void doSomethingMore()
    {
        a = 10;  //Not Allowed, Compiler Error, a is private member of Derived now
        b = 20;  //Not Allowed, Compiler Error, b is private member of Derived now
        c = 30;  //Not Allowed, Compiler Error
    }
};

int main()
{
    Derived obj;
    obj.a = 10;  //Not Allowed, Compiler Error
    obj.b = 20;  //Not Allowed, Compiler Error
    obj.c = 30;  //Not Allowed, Compiler Error

}

Protected Inheritance:

All Public members of the Base Class become Protected Members of the derived class &
All Protected members of the Base Class become Protected Members of the Derived Class.

A Code Example:

Class Base
{
    public:
        int a;
    protected:
        int b;
    private:
        int c;
};

class Derived:protected Base  
{
    void doSomething()
    {
        a = 10;  //Allowed 
        b = 20;  //Allowed
        c = 30;  //Not Allowed, Compiler Error
    }
};

class Derived2:public Derived
{
    void doSomethingMore()
    {
        a = 10;  //Allowed, a is protected member inside Derived & Derived2 is public derivation from Derived, a is now protected member of Derived2
        b = 20;  //Allowed, b is protected member inside Derived & Derived2 is public derivation from Derived, b is now protected member of Derived2
        c = 30;  //Not Allowed, Compiler Error
    }
};

int main()
{
    Derived obj;
    obj.a = 10;  //Not Allowed, Compiler Error
    obj.b = 20;  //Not Allowed, Compiler Error
    obj.c = 30;  //Not Allowed, Compiler Error
}

Remember the same access rules apply to the classes and members down the inheritance hierarchy.


Important points to note:

- Access Specification is per-Class not per-Object

Note that the access specification C++ work on per-Class basis and not per-object basis.
A good example of this is that in a copy constructor or Copy Assignment operator function, all the members of the object being passed can be accessed.

- A Derived class can only access members of its own Base class

Consider the following code example:

class Myclass
{ 
    protected: 
       int x; 
}; 

class derived : public Myclass
{
    public: 
        void f( Myclass& obj ) 
        { 
            obj.x = 5; 
        } 
};

int main()
{
    return 0;
}

It gives an compilation error:

prog.cpp:4: error: ‘int Myclass::x’ is protected

Because the derived class can only access members of its own Base Class. Note that the object obj being passed here is no way related to the derived class function in which it is being accessed, it is an altogether different object and hence derived member function cannot access its members.


What is a friend? How does friend affect access specification rules?

You can declare a function or class as friend of another class. When you do so the access specification rules do not apply to the friended class/function. The class or function can access all the members of that particular class.

So do friends break Encapsulation?

No they don't, On the contrary they enhance Encapsulation!

friendship is used to indicate a intentional strong coupling between two entities.
If there exists a special relationship between two entities such that one needs access to others private or protected members but You do not want everyone to have access by using the public access specifier then you should use friendship.

Sql error on update : The UPDATE statement conflicted with the FOREIGN KEY constraint

Reason is as @MilicaMedic says. Alternative solution is disable all constraints, do the update and then enable the constraints again like this. Very useful when updating test data in test environments.

exec sp_MSforeachtable "ALTER TABLE ? NOCHECK CONSTRAINT all"

update patient set id_no='7008255601088' where id_no='8008255601088'
update patient_address set id_no='7008255601088' where id_no='8008255601088'

exec sp_MSforeachtable "ALTER TABLE ? WITH CHECK CHECK CONSTRAINT all"

Source:

https://stackoverflow.com/a/161410/3850405

SSL cert "err_cert_authority_invalid" on mobile chrome only

I solved my problem with this commands:

cat __mydomain_com.crt __mydomain_com.ca-bundle > __mydomain_com_combine.crt

and after:

cat __mydomain_com_combine.crt COMODORSADomainValidationSecureServerCA.crt 
COMODORSAAddTrustCA.crt AddTrustExternalCARoot.crt > mydomain.pem

And in my domain nginx .conf I put on the server 443:

ssl_certificate          ssl/mydomain.pem;
ssl_certificate_key      ssl/mydomain.private.key;

I don't forget restart your "Nginx"

service nginx restart

How do I configure PyCharm to run py.test tests?

Enable Pytest for you project

  1. Open the Settings/Preferences | Tools | Python Integrated Tools settings dialog as described in Choosing Your Testing Framework.
  2. In the Default test runner field select pytest.
  3. Click OK to save the settings.

enter image description here

Minimum 6 characters regex expression

This match 6 or more any chars but newline:

/^.{6,}$/

How do I activate C++ 11 in CMake?

I think just these two lines are enough.

set(CMAKE_CXX_STANDARD 11)

set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11")

C error: undefined reference to function, but it IS defined

Add the "extern" keyword to the function definitions in point.h

Sum values in foreach loop php

$sum = 0;
foreach($group as $key=>$value)
{
   $sum+= $value;
}
echo $sum;

How to format an inline code in Confluence?

To insert inline monospace font in Confluence, surround the text in double curly-braces.

This is an {{example}}.

If you're using Confluence 4.x or higher, you can also just select the "Preformatted" option from the paragraph style menu. Please note that will apply to the entire line.

Full reference here.

MySQL, Check if a column exists in a table with SQL

This works well for me.

SHOW COLUMNS FROM `table` LIKE 'fieldname';

With PHP it would be something like...

$result = mysql_query("SHOW COLUMNS FROM `table` LIKE 'fieldname'");
$exists = (mysql_num_rows($result))?TRUE:FALSE;

How to insert double and float values to sqlite?

SQL Supports following types of affinities:

  • TEXT
  • NUMERIC
  • INTEGER
  • REAL
  • BLOB

If the declared type for a column contains any of these "REAL", "FLOAT", or "DOUBLE" then the column has 'REAL' affinity.

How do I clear all options in a dropdown box?

This is a short way:

document.getElementById('mySelect').innerText = null;

One line, no for, no JQuery, simple.

Python: avoid new line with print command

You simply need to do:

print 'lakjdfljsdf', # trailing comma

However in:

print 'lkajdlfjasd', 'ljkadfljasf'

There is implicit whitespace (ie ' ').

You also have the option of:

import sys
sys.stdout.write('some data here without a new line')

'node' is not recognized as an internal or an external command, operable program or batch file while using phonegap/cordova

Great answers, but you could just open the command prompt and type in

 SET PATH=C:\Program Files\Nodejs;%PATH%

Convert a date format in epoch

Create Common Method to Convert String to Date format

public static void main(String[] args) throws Exception {
    long test = ConvertStringToDate("May 26 10:41:23", "MMM dd hh:mm:ss");
    long test2 = ConvertStringToDate("Tue, Jun 06 2017, 12:30 AM", "EEE, MMM dd yyyy, hh:mm a");
    long test3 = ConvertStringToDate("Jun 13 2003 23:11:52.454 UTC", "MMM dd yyyy HH:mm:ss.SSS zzz");
}

private static long ConvertStringToDate(String dateString, String format) {
    try {
        return new SimpleDateFormat(format).parse(dateString).getTime();
    } catch (ParseException e) {}
    return 0;
}

@Cacheable key on multiple method arguments

You can use a Spring-EL expression, for eg on JDK 1.7:

@Cacheable(value="bookCache", key="T(java.util.Objects).hash(#p0,#p1, #p2)")

How to get length of a list of lists in python

"The above text file used has 3 lines of 4 elements separated by commas. The variable numLines prints out as '4' not '3'. So, len(myLines) is returning the number of elements in each list not the length of the list of lists."

It sounds like you're reading in a .csv with 3 rows and 4 columns. If this is the case, you can find the number of rows and lines by using the .split() method:

text = open("filetest.txt", "r").read()
myRows = text.split("\n")      #this method tells Python to split your filetest object each time it encounters a line break 
print len(myRows)              #will tell you how many rows you have
for row in myRows:
  myColumns = row.split(",")   #this method will consider each of your rows one at a time. For each of those rows, it will split that row each time it encounters a comma.  
  print len(myColumns)         #will tell you, for each of your rows, how many columns that row contains

Openstreetmap: embedding map in webpage (like Google Maps)

I would also take a look at CloudMade's developer tools. They offer a beautifully styled OSM base map service, an OpenLayers plugin, and even their own light-weight, very fast JavaScript mapping client. They also host their own routing service, which you mentioned as a possible requirement. They have great documentation and examples.

How to print a debug log?

You can use the php curl module to make calls to http://liveoutput.com/. This works great in an secure, corporate environment where certain restrictions in the php.ini exists that restrict usage of file_put_contents.

Content Type application/soap+xml; charset=utf-8 was not supported by service

My problem was our own collection class, which was flagged with [DataContract]. From my point of view, this was a clean approach and it worked fine with XmlSerializer but for the WCF endpoint it was breaking and we had to remove it. XmlSerializer still works without.

Not working

[DataContract]
public class AttributeCollection : List<KeyValuePairSerializable<string, string>>

Working

public class AttributeCollection : List<KeyValuePairSerializable<string, string>>

Creating an empty bitmap and drawing though canvas in Android

This is probably simpler than you're thinking:

int w = WIDTH_PX, h = HEIGHT_PX;

Bitmap.Config conf = Bitmap.Config.ARGB_8888; // see other conf types
Bitmap bmp = Bitmap.createBitmap(w, h, conf); // this creates a MUTABLE bitmap
Canvas canvas = new Canvas(bmp);

// ready to draw on that bitmap through that canvas

Here's a series of tutorials I've found on the topic: Drawing with Canvas Series

How to retrieve Key Alias and Key Password for signed APK in android studio(migrated from Eclipse)

In any case you are confused with your password.You can use hit and trial. It will ask you for password.If it right then it will show you the list.

  • List item

$ keytool -list -v -keystore filename

How do I use JDK 7 on Mac OSX?

How about Netbeans, here is an article how to set it up with NB7:

http://netbeanside61.blogspot.com/2011/06/downloading-openjdk7-binary-for-mac-os.html

Maybe similar steps for Eclipse.

Replace missing values with column mean

With the data.table package you could use the set() function and loop over the columns and replace the NAs or whatever you like with an aggregate or value of your choice (here: mean):

require(data.table)

# data
dt = copy(iris[ ,-5])
setDT(dt)
dt[1:4, Sepal.Length := NA] # introduce NAs

# replace NAs with mean (or whatever function you like)
for (j in seq_along(names(dt))) {
  set(dt,
      i = which(is.na(dt[[j]])),
      j = j, 
      value = mean(dt[[j]], na.rm = TRUE))
}

Using LIKE operator with stored procedure parameters

Your datatype for @location nchar(20) should be @location nvarchar(20), since nChar has a fixed length (filled with Spaces).
If Location is nchar too you will have to convert it:

 ... Cast(Location as nVarchar(200)) like '%'+@location+'%' ...   

To enable nullable parameters with and AND condition just use IsNull or Coalesce for comparison, which is not needed in your example using OR.

e.g. if you would like to compare for Location AND Date and Time.

@location nchar(20),
@time time,
@date date
as
select DonationsTruck.VechileId, Phone, Location, [Date], [Time]
from Vechile, DonationsTruck
where Vechile.VechileId = DonationsTruck.VechileId
and (((Location like '%'+IsNull(@location,Location)+'%')) and [Date]=IsNUll(@date,date) and [Time] = IsNull(@time,Time))

What is the documents directory (NSDocumentDirectory)?

Your app only (on a non-jailbroken device) runs in a "sandboxed" environment. This means that it can only access files and directories within its own contents. For example Documents and Library.

See the iOS Application Programming Guide.

To access the Documents directory of your applications sandbox, you can use the following:

iOS 8 and newer, this is the recommended method

+ (NSURL *)applicationDocumentsDirectory
{
     return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
}

if you need to support iOS 7 or earlier

+ (NSString *) applicationDocumentsDirectory 
{    
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *basePath = paths.firstObject;
    return basePath;
}

This Documents directory allows you to store files and subdirectories your app creates or may need.

To access files in the Library directory of your apps sandbox use (in place of paths above):

[NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) objectAtIndex:0]

Invalid length for a Base-64 char array

I'm not Reputable enough to upvote or comment yet, but LukeH's answer was spot on for me.

As AES encryption is the standard to use now, it produces a base64 string (at least all the encrypt/decrypt implementations I've seen). This string has a length in multiples of 4 (string.length % 4 = 0)

The strings I was getting contained + and = on the beginning or end, and when you just concatenate that into a URL's querystring, it will look right (for instance, in an email you generate), but when the the link is followed and the .NET page recieves it and puts it into this.Page.Request.QueryString, those special characters will be gone and your string length will not be in a multiple of 4.

As the are special characters at the FRONT of the string (ex: +), as well as = at the end, you can't just add some = to make up the difference as you are altering the cypher text in a way that doesn't match what was actually in the original querystring.

So, wrapping the cypher text with HttpUtility.URLEncode (not HtmlEncode) transforms the non-alphanumeric characters in a way that ensures .NET parses them back into their original state when it is intepreted into the querystring collection.

The good thing is, we only need to do the URLEncode when generating the querystring for the URL. On the incoming side, it's automatically translated back into the original string value.

Here's some example code

string cryptostring = MyAESEncrypt(MySecretString);
string URL = WebFunctions.ToAbsoluteUrl("~/ResetPassword.aspx?RPC=" + HttpUtility.UrlEncode(cryptostring));

How to retrieve the current value of an oracle sequence without increment it?

This is not an answer, really and I would have entered it as a comment had the question not been locked. This answers the question:

Why would you want it?

Assume you have a table with the sequence as the primary key and the sequence is generated by an insert trigger. If you wanted to have the sequence available for subsequent updates to the record, you need to have a way to extract that value.

In order to make sure you get the right one, you might want to wrap the INSERT and RonK's query in a transaction.

RonK's Query:

select MY_SEQ_NAME.currval from DUAL;

In the above scenario, RonK's caveat does not apply since the insert and update would happen in the same session.

Jquery show/hide table rows

Change your black and white IDs to classes instead (duplicate IDs are invalid), add 2 buttons with the proper IDs, and do this:

var rows = $('table.someclass tr');

$('#showBlackButton').click(function() {
    var black = rows.filter('.black').show();
    rows.not( black ).hide();
});

$('#showWhiteButton').click(function() {
    var white = rows.filter('.white').show();
    rows.not( white ).hide();
});

$('#showAll').click(function() {
    rows.show();
});

<button id="showBlackButton">show black</button>
<button id="showWhiteButton">show white</button>
<button id="showAll">show all</button>

<table class="someclass" border="0" cellpadding="0" cellspacing="0" summary="bla bla bla">
    <caption>bla bla bla</caption>
    <thead>
          <tr class="black">
            ...
          </tr>
    </thead>
    <tbody>
        <tr class="white">
            ...
        </tr>
        <tr class="black">
           ...
        </tr>
    </tbody>
</table>

It uses the filter()[docs] method to filter the rows with the black or white class (depending on the button).

Then it uses the not()[docs] method to do the opposite filter, excluding the black or white rows that were previously found.


EDIT: You could also pass a selector to .not() instead of the previously found set. It may perform better that way:

rows.not( `.black` ).hide();

// ...

rows.not( `.white` ).hide();

...or better yet, just keep a cached set of both right from the start:

var rows = $('table.someclass tr');
var black = rows.filter('.black');
var white = rows.filter('.white');

$('#showBlackButton').click(function() {
    black.show();
    white.hide();
});

$('#showWhiteButton').click(function() {
    white.show();
    black.hide();
});

Set database timeout in Entity Framework

I just ran in to this problem and resolved it by updating my application configuration file. For the connection in question, specify "Connection Timeout=60" (I am using entity framework version 5.0.0.0)

ConnectionTimeout Setting

How can I use JSON data to populate the options of a select box?

I know this question is a bit old, but I'd use a jQuery template and a $.ajax call:

ASPX:
<select id="mySelect" name="mySelect>
    <option value="0">-select-</option>
</select>
<script id="mySelectTemplate" type="text/x-jquery-tmpl">
    <option value="${CityId}">${CityName}</option>
</script>

JS:
$.ajax({ 
    url: location.pathname + '/GetCities', 
    type: 'POST', 
    contentType: 'application/json; charset=utf-8', 
    dataType: 'json', 
    success: function (response) { 
        $('#mySelectTemplate').tmpl(response.d).appendTo('#mySelect'); 
    } 
});

In addition to the above you'll need a web method (GetCities) that returns a list of objects that include the data elements you're using in your template. I often use Entity Framework and my web method will call a manager class that is getting values from the database using linq. By doing that you can have your input save to the database and refreshing your select list is as simple as calling the databind in JS in the success of your save.

Add a new column to existing table in a migration

WARNING this is a destructive action. If you use this ensure you back up your database first

you can simply modify your existing migration file, for example adding a column in your table, and then in your terminal typing :

$ php artisan migrate:refresh

Difference between INNER JOIN and LEFT SEMI JOIN

An INNER JOIN can return data from the columns from both tables, and can duplicate values of records on either side have more than one match. A LEFT SEMI JOIN can only return columns from the left-hand table, and yields one of each record from the left-hand table where there is one or more matches in the right-hand table (regardless of the number of matches). It's equivalent to (in standard SQL):

SELECT name
FROM table_1 a
WHERE EXISTS(
    SELECT * FROM table_2 b WHERE (a.name=b.name))

If there are multiple matching rows in the right-hand column, an INNER JOIN will return one row for each match on the right table, while a LEFT SEMI JOIN only returns the rows from the left table, regardless of the number of matching rows on the right side. That's why you're seeing a different number of rows in your result.

I am trying to get the names within table_1 that only appear in table_2.

Then a LEFT SEMI JOIN is the appropriate query to use.

Construct a manual legend for a complicated plot

You need to map attributes to aesthetics (colours within the aes statement) to produce a legend.

cols <- c("LINE1"="#f04546","LINE2"="#3591d1","BAR"="#62c76b")
ggplot(data=data,aes(x=a)) + 
  geom_bar(stat="identity", aes(y=h, fill = "BAR"),colour="#333333")+ #green
  geom_line(aes(y=b,group=1, colour="LINE1"),size=1.0) +   #red
  geom_point(aes(y=b, colour="LINE1"),size=3) +           #red
  geom_errorbar(aes(ymin=d, ymax=e, colour="LINE1"), width=0.1, size=.8) + 
  geom_line(aes(y=c,group=1,colour="LINE2"),size=1.0) +   #blue 
  geom_point(aes(y=c,colour="LINE2"),size=3) +           #blue
  geom_errorbar(aes(ymin=f, ymax=g,colour="LINE2"), width=0.1, size=.8) + 
  scale_colour_manual(name="Error Bars",values=cols) + scale_fill_manual(name="Bar",values=cols) +
  ylab("Symptom severity") + xlab("PHQ-9 symptoms") +
  ylim(0,1.6) +
  theme_bw() +
  theme(axis.title.x = element_text(size = 15, vjust=-.2)) +
  theme(axis.title.y = element_text(size = 15, vjust=0.3))

enter image description here

I understand where Roland is coming from, but since this is only 3 attributes, and complications arise from superimposing bars and error bars this may be reasonable to leave the data in wide format like it is. It could be slightly reduced in complexity by using geom_pointrange.


To change the background color for the error bars legend in the original, add + theme(legend.key = element_rect(fill = "white",colour = "white")) to the plot specification. To merge different legends, you typically need to have a consistent mapping for all elements, but it is currently producing an artifact of a black background for me. I thought guide = guide_legend(fill = NULL,colour = NULL) would set the background to null for the legend, but it did not. Perhaps worth another question.

ggplot(data=data,aes(x=a)) + 
  geom_bar(stat="identity", aes(y=h,fill = "BAR", colour="BAR"))+ #green
  geom_line(aes(y=b,group=1, colour="LINE1"),size=1.0) +   #red
  geom_point(aes(y=b, colour="LINE1", fill="LINE1"),size=3) +           #red
  geom_errorbar(aes(ymin=d, ymax=e, colour="LINE1"), width=0.1, size=.8) + 
  geom_line(aes(y=c,group=1,colour="LINE2"),size=1.0) +   #blue 
  geom_point(aes(y=c,colour="LINE2", fill="LINE2"),size=3) +           #blue
  geom_errorbar(aes(ymin=f, ymax=g,colour="LINE2"), width=0.1, size=.8) + 
  scale_colour_manual(name="Error Bars",values=cols, guide = guide_legend(fill = NULL,colour = NULL)) + 
  scale_fill_manual(name="Bar",values=cols, guide="none") +
  ylab("Symptom severity") + xlab("PHQ-9 symptoms") +
  ylim(0,1.6) +
  theme_bw() +
  theme(axis.title.x = element_text(size = 15, vjust=-.2)) +
  theme(axis.title.y = element_text(size = 15, vjust=0.3))

enter image description here


To get rid of the black background in the legend, you need to use the override.aes argument to the guide_legend. The purpose of this is to let you specify a particular aspect of the legend which may not be being assigned correctly.

ggplot(data=data,aes(x=a)) + 
  geom_bar(stat="identity", aes(y=h,fill = "BAR", colour="BAR"))+ #green
  geom_line(aes(y=b,group=1, colour="LINE1"),size=1.0) +   #red
  geom_point(aes(y=b, colour="LINE1", fill="LINE1"),size=3) +           #red
  geom_errorbar(aes(ymin=d, ymax=e, colour="LINE1"), width=0.1, size=.8) + 
  geom_line(aes(y=c,group=1,colour="LINE2"),size=1.0) +   #blue 
  geom_point(aes(y=c,colour="LINE2", fill="LINE2"),size=3) +           #blue
  geom_errorbar(aes(ymin=f, ymax=g,colour="LINE2"), width=0.1, size=.8) + 
  scale_colour_manual(name="Error Bars",values=cols, 
                      guide = guide_legend(override.aes=aes(fill=NA))) + 
  scale_fill_manual(name="Bar",values=cols, guide="none") +
  ylab("Symptom severity") + xlab("PHQ-9 symptoms") +
  ylim(0,1.6) +
  theme_bw() +
  theme(axis.title.x = element_text(size = 15, vjust=-.2)) +
  theme(axis.title.y = element_text(size = 15, vjust=0.3))

enter image description here

How to check if spark dataframe is empty?

In Scala you can use implicits to add the methods isEmpty() and nonEmpty() to the DataFrame API, which will make the code a bit nicer to read.

object DataFrameExtensions {
  implicit def extendedDataFrame(dataFrame: DataFrame): ExtendedDataFrame = 
    new ExtendedDataFrame(dataFrame: DataFrame)

  class ExtendedDataFrame(dataFrame: DataFrame) {
    def isEmpty(): Boolean = dataFrame.head(1).isEmpty // Any implementation can be used
    def nonEmpty(): Boolean = !isEmpty
  }
}

Here, other methods can be added as well. To use the implicit conversion, use import DataFrameExtensions._ in the file you want to use the extended functionality. Afterwards, the methods can be used directly as so:

val df: DataFrame = ...
if (df.isEmpty) {
  // Do something
}

python ValueError: invalid literal for float()

I would all but guarantee that the issue is some sort of non-printing character that's present in the value you pulled off your socket. It looks like you're using Python 2.x, in which case you can check for them with this:

print repr(temp)

You'll likely see something in there that's escaped in the form \x00. These non-printing characters don't show up when you print directly to the console, but their presence is enough to negatively impact the parsing of a string value into a float.

-- Edited for question changes --

It turns this is partly accurate for your issue - the root cause however appears to be that you're reading more information than you expect from your socket or otherwise receiving multiple values. You could do something like

map(float, temp.strip().split('\r\n'))

In order to convert each of the values, but if your function is supposed to return a single float value this is likely to cause confusion. Anyway, the issue certainly revolves around the presence of characters you did not expect to see in the value you retrieved from your socket.

Basic HTTP and Bearer Token Authentication

Try this one to push basic authentication at url:

curl -i http://username:[email protected]/api/users -H "Authorization: Bearer mytoken123"
               ^^^^^^^^^^^^^^^^^^

If above one doesn't work, then you have nothing to do with it. So try the following alternates.

You can pass the token under another name. Because you are handling the authorization from your Application. So you can easily use this flexibility for this special purpose.

curl -i http://dev.myapp.com/api/users \
  -H "Authorization: Basic Ym9zY236Ym9zY28=" \
  -H "Application-Authorization: mytoken123"

Notice I have changed the header into Application-Authorization. So from your application catch the token under that header and process what you need to do.

Another thing you can do is, to pass the token through the POST parameters and grab the parameter's value from the Server side. For example passing token with curl post parameter:

-d "auth-token=mytoken123"

How to enable directory listing in apache web server

Once I changed Options -Index to Options +Index in my conf file, I removed the welcome page and restarted services.

$ sudo rm -f /etc/httpd/conf.d/welcome.conf
$ sudo service httpd restart

I was able to see directory listings after that.

Show loading gif after clicking form submit using jQuery

Button inputs don't have a submit event. Try attaching the event handler to the form instead:

<script type="text/javascript">
     $('#login_form').submit(function() {
       $('#gif').show(); 
       return true;
     });
 </script>

Batch file for PuTTY/PSFTP file transfer automation

You need to store the psftp script (lines from open to bye) into a separate file and pass that to psftp using -b switch:

cd "C:\Program Files (x86)\PuTTY"
psftp -b "C:\path\to\script\script.txt"

Reference:
https://the.earth.li/~sgtatham/putty/latest/htmldoc/Chapter6.html#psftp-option-b


EDIT: For username+password: As you cannot use psftp commands in a batch file, for the same reason, you cannot specify the username and the password as psftp commands. These are inputs to the open command. While you can specify the username with the open command (open <user>@<IP>), you cannot specify the password this way. This can be done on a psftp command line only. Then it's probably cleaner to do all on the command-line:

cd "C:\Program Files (x86)\PuTTY"
psftp -b script.txt <user>@<IP> -pw <PW>

And remove the open, <user> and <PW> lines from your script.txt.

Reference:
https://the.earth.li/~sgtatham/putty/latest/htmldoc/Chapter6.html#psftp-starting
https://the.earth.li/~sgtatham/putty/latest/htmldoc/Chapter3.html#using-cmdline-pw


What you are doing atm is that you run psftp without any parameter or commands. Once you exit it (like by typing bye), your batch file continues trying to run open command (and others), what Windows shell obviously does not understand.


If you really want to keep everything in one file (the batch file), you can write commands to psftp standard input, like:

(
    echo cd ...
    echo lcd ...
    echo put log.sh
) | psftp -b script.txt <user>@<IP> -pw <PW>

Using ConfigurationManager to load config from an arbitrary location

In addition to Ishmaeel's answer, the method OpenMappedMachineConfiguration() will always return a Configuration object. So to check to see if it loaded you should check the HasFile property where true means it came from a file.

How to call a method function from another class?

In class WeatherRecord:

First import the class if they are in different package else this statement is not requires

Import <path>.ClassName



Then, just referene or call your object like:

Date d;
TempratureRange tr;
d = new Date();
tr = new TempratureRange;
//this can be done in Single Line also like :
// Date d = new Date();



But in your code you are not required to create an object to call function of Date and TempratureRange. As both of the Classes contain Static Function , you cannot call the thoes function by creating object.

Date.date(date,month,year);   // this is enough to call those static function 


Have clear concept on Object and Static functions. Click me

Linux command to list all available commands and aliases

Try this script:

#!/bin/bash
echo $PATH  | tr : '\n' | 
while read e; do 
    for i in $e/*; do
        if [[ -x "$i" && -f "$i" ]]; then     
            echo $i
        fi
    done
done

Gitignore not working

The files/folder in your version control will not just delete themselves just because you added them to the .gitignore. They are already in the repository and you have to remove them. You can just do that with this:

Remember to commit everything you've changed before you do this!

git rm -rf --cached .
git add .

This removes all files from the repository and adds them back (this time respecting the rules in your .gitignore).

How to enable named/bind/DNS full logging?

I usually expand each log out into it's own channel and then to a separate log file, certainly makes things easier when you are trying to debug specific issues. So my logging section looks like the following:

logging {
    channel default_file {
        file "/var/log/named/default.log" versions 3 size 5m;
        severity dynamic;
        print-time yes;
    };
    channel general_file {
        file "/var/log/named/general.log" versions 3 size 5m;
        severity dynamic;
        print-time yes;
    };
    channel database_file {
        file "/var/log/named/database.log" versions 3 size 5m;
        severity dynamic;
        print-time yes;
    };
    channel security_file {
        file "/var/log/named/security.log" versions 3 size 5m;
        severity dynamic;
        print-time yes;
    };
    channel config_file {
        file "/var/log/named/config.log" versions 3 size 5m;
        severity dynamic;
        print-time yes;
    };
    channel resolver_file {
        file "/var/log/named/resolver.log" versions 3 size 5m;
        severity dynamic;
        print-time yes;
    };
    channel xfer-in_file {
        file "/var/log/named/xfer-in.log" versions 3 size 5m;
        severity dynamic;
        print-time yes;
    };
    channel xfer-out_file {
        file "/var/log/named/xfer-out.log" versions 3 size 5m;
        severity dynamic;
        print-time yes;
    };
    channel notify_file {
        file "/var/log/named/notify.log" versions 3 size 5m;
        severity dynamic;
        print-time yes;
    };
    channel client_file {
        file "/var/log/named/client.log" versions 3 size 5m;
        severity dynamic;
        print-time yes;
    };
    channel unmatched_file {
        file "/var/log/named/unmatched.log" versions 3 size 5m;
        severity dynamic;
        print-time yes;
    };
    channel queries_file {
        file "/var/log/named/queries.log" versions 3 size 5m;
        severity dynamic;
        print-time yes;
    };
    channel network_file {
        file "/var/log/named/network.log" versions 3 size 5m;
        severity dynamic;
        print-time yes;
    };
    channel update_file {
        file "/var/log/named/update.log" versions 3 size 5m;
        severity dynamic;
        print-time yes;
    };
    channel dispatch_file {
        file "/var/log/named/dispatch.log" versions 3 size 5m;
        severity dynamic;
        print-time yes;
    };
    channel dnssec_file {
        file "/var/log/named/dnssec.log" versions 3 size 5m;
        severity dynamic;
        print-time yes;
    };
    channel lame-servers_file {
        file "/var/log/named/lame-servers.log" versions 3 size 5m;
        severity dynamic;
        print-time yes;
    };

    category default { default_file; };
    category general { general_file; };
    category database { database_file; };
    category security { security_file; };
    category config { config_file; };
    category resolver { resolver_file; };
    category xfer-in { xfer-in_file; };
    category xfer-out { xfer-out_file; };
    category notify { notify_file; };
    category client { client_file; };
    category unmatched { unmatched_file; };
    category queries { queries_file; };
    category network { network_file; };
    category update { update_file; };
    category dispatch { dispatch_file; };
    category dnssec { dnssec_file; };
    category lame-servers { lame-servers_file; };
};

Hope this helps.

php - How do I fix this illegal offset type error

Illegal offset type errors occur when you attempt to access an array index using an object or an array as the index key.

Example:

$x = new stdClass();
$arr = array();
echo $arr[$x];
//illegal offset type

Your $xml array contains an object or array at $xml->entry[$i]->source for some value of $i, and when you try to use that as an index key for $s, you get that warning. You'll have to make sure $xml contains what you want it to and that you're accessing it correctly.

Conditional Binding: if let error – Initializer for conditional binding must have Optional type

if let/if var optional binding only works when the result of the right side of the expression is an optional. If the result of the right side is not an optional, you can not use this optional binding. The point of this optional binding is to check for nil and only use the variable if it's non-nil.

In your case, the tableView parameter is declared as the non-optional type UITableView. It is guaranteed to never be nil. So optional binding here is unnecessary.

func tableView(tableView: UITableView, commitEditingStyle editingStyle:UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
    if editingStyle == .Delete {
        // Delete the row from the data source
        myData.removeAtIndex(indexPath.row)
        tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)

All we have to do is get rid of the if let and change any occurrences of tv within it to just tableView.

Python3 project remove __pycache__ folders and .pyc files

I found the answer myself when I mistyped pyclean as pycclean:

    No command 'pycclean' found, did you mean:
     Command 'py3clean' from package 'python3-minimal' (main)
     Command 'pyclean' from package 'python-minimal' (main)
    pycclean: command not found

Running py3clean . cleaned it up very nicely.

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

I ran this bad boy:

launchctl setenv STUDIO_JDK /Library/Java/JavaVirtualMachines/jdk1.7.0_71.jdk/

What is the difference between an int and an Integer in Java and C#?

One more thing that I don't see in previous answers: In Java the primitive wrappers classes like Integer, Double, Float, Boolean... and String are suposed to be invariant, so that when you pass an instance of those classes the invoked method couldn't alter your data in any way, in opositión with most of other classes, which internal data could be altered by its public methods. So that this classes only has 'getter' methods, no 'setters', besides the constructor.

In a java program String literals are stored in a separate portion of heap memory, only a instance for literal, to save memory reusing those instances

Dynamically load a function from a DLL

This is not exactly a hot topic, but I have a factory class that allows a dll to create an instance and return it as a DLL. It is what I came looking for but couldn't find exactly.

It is called like,

IHTTP_Server *server = SN::SN_Factory<IHTTP_Server>::CreateObject();
IHTTP_Server *server2 =
      SN::SN_Factory<IHTTP_Server>::CreateObject(IHTTP_Server_special_entry);

where IHTTP_Server is the pure virtual interface for a class created either in another DLL, or the same one.

DEFINE_INTERFACE is used to give a class id an interface. Place inside interface;

An interface class looks like,

class IMyInterface
{
    DEFINE_INTERFACE(IMyInterface);

public:
    virtual ~IMyInterface() {};

    virtual void MyMethod1() = 0;
    ...
};

The header file is like this

#if !defined(SN_FACTORY_H_INCLUDED)
#define SN_FACTORY_H_INCLUDED

#pragma once

The libraries are listed in this macro definition. One line per library/executable. It would be cool if we could call into another executable.

#define SN_APPLY_LIBRARIES(L, A)                          \
    L(A, sn, "sn.dll")                                    \
    L(A, http_server_lib, "http_server_lib.dll")          \
    L(A, http_server, "")

Then for each dll/exe you define a macro and list its implementations. Def means that it is the default implementation for the interface. If it is not the default, you give a name for the interface used to identify it. Ie, special, and the name will be IHTTP_Server_special_entry.

#define SN_APPLY_ENTRYPOINTS_sn(M)                                     \
    M(IHTTP_Handler, SNI::SNI_HTTP_Handler, sn, def)                   \
    M(IHTTP_Handler, SNI::SNI_HTTP_Handler, sn, special)

#define SN_APPLY_ENTRYPOINTS_http_server_lib(M)                        \
    M(IHTTP_Server, HTTP::server::server, http_server_lib, def)

#define SN_APPLY_ENTRYPOINTS_http_server(M)

With the libraries all setup, the header file uses the macro definitions to define the needful.

#define APPLY_ENTRY(A, N, L) \
    SN_APPLY_ENTRYPOINTS_##N(A)

#define DEFINE_INTERFACE(I) \
    public: \
        static const long Id = SN::I##_def_entry; \
    private:

namespace SN
{
    #define DEFINE_LIBRARY_ENUM(A, N, L) \
        N##_library,

This creates an enum for the libraries.

    enum LibraryValues
    {
        SN_APPLY_LIBRARIES(DEFINE_LIBRARY_ENUM, "")
        LastLibrary
    };

    #define DEFINE_ENTRY_ENUM(I, C, L, D) \
        I##_##D##_entry,

This creates an enum for interface implementations.

    enum EntryValues
    {
        SN_APPLY_LIBRARIES(APPLY_ENTRY, DEFINE_ENTRY_ENUM)
        LastEntry
    };

    long CallEntryPoint(long id, long interfaceId);

This defines the factory class. Not much to it here.

    template <class I>
    class SN_Factory
    {
    public:
        SN_Factory()
        {
        }

        static I *CreateObject(long id = I::Id )
        {
            return (I *)CallEntryPoint(id, I::Id);
        }
    };
}

#endif //SN_FACTORY_H_INCLUDED

Then the CPP is,

#include "sn_factory.h"

#include <windows.h>

Create the external entry point. You can check that it exists using depends.exe.

extern "C"
{
    __declspec(dllexport) long entrypoint(long id)
    {
        #define CREATE_OBJECT(I, C, L, D) \
            case SN::I##_##D##_entry: return (int) new C();

        switch (id)
        {
            SN_APPLY_CURRENT_LIBRARY(APPLY_ENTRY, CREATE_OBJECT)
        case -1:
        default:
            return 0;
        }
    }
}

The macros set up all the data needed.

namespace SN
{
    bool loaded = false;

    char * libraryPathArray[SN::LastLibrary];
    #define DEFINE_LIBRARY_PATH(A, N, L) \
        libraryPathArray[N##_library] = L;

    static void LoadLibraryPaths()
    {
        SN_APPLY_LIBRARIES(DEFINE_LIBRARY_PATH, "")
    }

    typedef long(*f_entrypoint)(long id);

    f_entrypoint libraryFunctionArray[LastLibrary - 1];
    void InitlibraryFunctionArray()
    {
        for (long j = 0; j < LastLibrary; j++)
        {
            libraryFunctionArray[j] = 0;
        }

        #define DEFAULT_LIBRARY_ENTRY(A, N, L) \
            libraryFunctionArray[N##_library] = &entrypoint;

        SN_APPLY_CURRENT_LIBRARY(DEFAULT_LIBRARY_ENTRY, "")
    }

    enum SN::LibraryValues libraryForEntryPointArray[SN::LastEntry];
    #define DEFINE_ENTRY_POINT_LIBRARY(I, C, L, D) \
            libraryForEntryPointArray[I##_##D##_entry] = L##_library;
    void LoadLibraryForEntryPointArray()
    {
        SN_APPLY_LIBRARIES(APPLY_ENTRY, DEFINE_ENTRY_POINT_LIBRARY)
    }

    enum SN::EntryValues defaultEntryArray[SN::LastEntry];
        #define DEFINE_ENTRY_DEFAULT(I, C, L, D) \
            defaultEntryArray[I##_##D##_entry] = I##_def_entry;

    void LoadDefaultEntries()
    {
        SN_APPLY_LIBRARIES(APPLY_ENTRY, DEFINE_ENTRY_DEFAULT)
    }

    void Initialize()
    {
        if (!loaded)
        {
            loaded = true;
            LoadLibraryPaths();
            InitlibraryFunctionArray();
            LoadLibraryForEntryPointArray();
            LoadDefaultEntries();
        }
    }

    long CallEntryPoint(long id, long interfaceId)
    {
        Initialize();

        // assert(defaultEntryArray[id] == interfaceId, "Request to create an object for the wrong interface.")
        enum SN::LibraryValues l = libraryForEntryPointArray[id];

        f_entrypoint f = libraryFunctionArray[l];
        if (!f)
        {
            HINSTANCE hGetProcIDDLL = LoadLibraryA(libraryPathArray[l]);

            if (!hGetProcIDDLL) {
                return NULL;
            }

            // resolve function address here
            f = (f_entrypoint)GetProcAddress(hGetProcIDDLL, "entrypoint");
            if (!f) {
                return NULL;
            }
            libraryFunctionArray[l] = f;
        }
        return f(id);
    }
}

Each library includes this "cpp" with a stub cpp for each library/executable. Any specific compiled header stuff.

#include "sn_pch.h"

Setup this library.

#define SN_APPLY_CURRENT_LIBRARY(L, A) \
    L(A, sn, "sn.dll")

An include for the main cpp. I guess this cpp could be a .h. But there are different ways you could do this. This approach worked for me.

#include "../inc/sn_factory.cpp"

Mongoose: Find, modify, save

findOne, modify fields & save

User.findOne({username: oldUsername})
  .then(user => {
    user.username = newUser.username;
    user.password = newUser.password;
    user.rights = newUser.rights;

    user.markModified('username');
    user.markModified('password');
    user.markModified('rights');

    user.save(err => console.log(err));
});

OR findOneAndUpdate

User.findOneAndUpdate({username: oldUsername}, {$set: { username: newUser.username, user: newUser.password, user:newUser.rights;}}, {new: true}, (err, doc) => {
    if (err) {
        console.log("Something wrong when updating data!");
    }
    console.log(doc);
});

Also see updateOne

How can I force a long string without any blank to be wrapped?

Here are some very useful answers:

How to prevent long words from breaking my div?

to save you time, this can be solved with css:

white-space: -moz-pre-wrap; /* Mozilla */
white-space: -hp-pre-wrap; /* HP printers */
white-space: -o-pre-wrap; /* Opera 7 */
white-space: -pre-wrap; /* Opera 4-6 */
white-space: pre-wrap; /* CSS 2.1 */
white-space: pre-line; /* CSS 3 (and 2.1 as well, actually) */
word-wrap: break-word; /* IE */
word-break: break-all;

Json.NET serialize object with root name

You can easily create your own serializer

var car = new Car() { Name = "Ford", Owner = "John Smith" };
string json = Serialize(car);

string Serialize<T>(T o)
{
    var attr = o.GetType().GetCustomAttribute(typeof(JsonObjectAttribute)) as JsonObjectAttribute;

    var jv = JValue.FromObject(o);

    return new JObject(new JProperty(attr.Title, jv)).ToString();
}

Best way to update an element in a generic List

AllDogs.First(d => d.Id == "2").Name = "some value";

However, a safer version of that might be this:

var dog = AllDogs.FirstOrDefault(d => d.Id == "2");
if (dog != null) { dog.Name = "some value"; }

Convert string to float?

Use Float.valueOf(String) to do the conversion.

The difference between valueOf() and parseFloat() is only the return. Use the former if you want a Float (object) and the latter if you want the float number.

How to create and add users to a group in Jenkins for authentication?

According to this posting by the lead Jenkins developer, Kohsuke Kawaguchi, in 2009, there is no group support for the built-in Jenkins user database. Group support is only usable when integrating Jenkins with LDAP or Active Directory. This appears to be the same in 2012.

However, as Vadim wrote in his answer, you don't need group support for the built-in Jenkins user database, thanks to the Role strategy plug-in.

java.lang.NoClassDefFoundError: org/apache/http/client/HttpClient

This problem occurs if there are different jar versions. Especially versions of httpcore and httpclient. Use same versions of httpcore and httpclient.

How do I set up curl to permanently use a proxy?

Many UNIX programs respect the http_proxy environment variable, curl included. The format curl accepts is [protocol://]<host>[:port].

In your shell configuration:

export http_proxy http://proxy.server.com:3128

For proxying HTTPS requests, set https_proxy as well.

Curl also allows you to set this in your .curlrc file (_curlrc on Windows), which you might consider more permanent:

http_proxy=http://proxy.server.com:3128

Assigning default values to shell variables with a single command in bash

Very close to what you posted, actually.

To get the assigned value, or default if it's missing:

FOO="${VARIABLE:-default}"  # If variable not set or null, use default.

Or to assign default to VARIABLE at the same time:

FOO="${VARIABLE:=default}"  # If variable not set or null, set it to default.

Pass array to MySQL stored routine

You can pass a string with your list and use a prepared statements to run a query, e.g. -

DELIMITER $$

CREATE PROCEDURE GetFruits(IN fruitArray VARCHAR(255))
BEGIN

  SET @sql = CONCAT('SELECT * FROM Fruits WHERE Name IN (', fruitArray, ')');
  PREPARE stmt FROM @sql;
  EXECUTE stmt;
  DEALLOCATE PREPARE stmt;

END
$$

DELIMITER ;

How to use:

SET @fruitArray = '\'apple\',\'banana\'';
CALL GetFruits(@fruitArray);

SQL : BETWEEN vs <= and >=

They are the same.

One thing to be careful of, is if you are using this against a DATETIME, the match for the end date will be the beginning of the day:

<= 20/10/2009

is not the same as:

<= 20/10/2009 23:59:59

(it would match against <= 20/10/2009 00:00:00.000)

How to force maven update?

This is one of the most annoying things about Maven. For me the following happens: If I add a dependency requesting more dependencies and more and more but have a slow connection, it seams to stop while downloading and timing out. While timing out all dependencies not yet fetched are marked with place holders in the .m2 cache and Maven will not (never) pick it up unless I remove the place holder entry from the cache (as other stated) by removing it.

So as far as I see it, Maven or more precise the Eclipse Maven plugin has a bug regarding this. Someone should report this.

How to check if a String contains another String in a case insensitive manner in Java?

Yes, contains is case sensitive. You can use java.util.regex.Pattern with the CASE_INSENSITIVE flag for case insensitive matching:

Pattern.compile(Pattern.quote(wantedStr), Pattern.CASE_INSENSITIVE).matcher(source).find();

EDIT: If s2 contains regex special characters (of which there are many) it's important to quote it first. I've corrected my answer since it is the first one people will see, but vote up Matt Quail's since he pointed this out.

Doing a cleanup action just before Node.js exits

The script below allows having a single handler for all exit conditions. It uses an app specific callback function to perform custom cleanup code.

cleanup.js

// Object to capture process exits and call app specific cleanup function

function noOp() {};

exports.Cleanup = function Cleanup(callback) {

  // attach user callback to the process event emitter
  // if no callback, it will still exit gracefully on Ctrl-C
  callback = callback || noOp;
  process.on('cleanup',callback);

  // do app specific cleaning before exiting
  process.on('exit', function () {
    process.emit('cleanup');
  });

  // catch ctrl+c event and exit normally
  process.on('SIGINT', function () {
    console.log('Ctrl-C...');
    process.exit(2);
  });

  //catch uncaught exceptions, trace, then exit normally
  process.on('uncaughtException', function(e) {
    console.log('Uncaught Exception...');
    console.log(e.stack);
    process.exit(99);
  });
};

This code intercepts uncaught exceptions, Ctrl+C and normal exit events. It then calls a single optional user cleanup callback function before exiting, handling all exit conditions with a single object.

The module simply extends the process object instead of defining another event emitter. Without an app specific callback the cleanup defaults to a no op function. This was sufficient for my use where child processes were left running when exiting by Ctrl+C.

You can easily add other exit events such as SIGHUP as desired. Note: per NodeJS manual, SIGKILL cannot have a listener. The test code below demonstrates various ways of using cleanup.js

// test cleanup.js on version 0.10.21

// loads module and registers app specific cleanup callback...
var cleanup = require('./cleanup').Cleanup(myCleanup);
//var cleanup = require('./cleanup').Cleanup(); // will call noOp

// defines app specific callback...
function myCleanup() {
  console.log('App specific cleanup code...');
};

// All of the following code is only needed for test demo

// Prevents the program from closing instantly
process.stdin.resume();

// Emits an uncaught exception when called because module does not exist
function error() {
  console.log('error');
  var x = require('');
};

// Try each of the following one at a time:

// Uncomment the next line to test exiting on an uncaught exception
//setTimeout(error,2000);

// Uncomment the next line to test exiting normally
//setTimeout(function(){process.exit(3)}, 2000);

// Type Ctrl-C to test forced exit 

Strip all non-numeric characters from string in JavaScript

Use a regular expression, if your script implementation supports them. Something like:

myString.replace(/[^0-9]/g, '');

How to check if matching text is found in a string in Lua?

There are 2 options to find matching text; string.match or string.find.

Both of these perform a regex search on the string to find matches.


string.find()

string.find(subject string, pattern string, optional start position, optional plain flag)

Returns the startIndex & endIndex of the substring found.

The plain flag allows for the pattern to be ignored and intead be interpreted as a literal. Rather than (tiger) being interpreted as a regex capture group matching for tiger, it instead looks for (tiger) within a string.

Going the other way, if you want to regex match but still want literal special characters (such as .()[]+- etc.), you can escape them with a percentage; %(tiger%).

You will likely use this in combination with string.sub

Example

str = "This is some text containing the word tiger."
if string.find(str, "tiger") then
  print ("The word tiger was found.")
else
  print ("The word tiger was not found.")
end

string.match()

string.match(s, pattern, optional index)

Returns the capture groups found.

Example

str = "This is some text containing the word tiger."
if string.match(str, "tiger") then
  print ("The word tiger was found.")
else
  print ("The word tiger was not found.")
end

Datagrid binding in WPF

Without seeing said object list, I believe you should be binding to the DataGrid's ItemsSource property, not its DataContext.

<DataGrid x:Name="Imported" VerticalAlignment="Top" ItemsSource="{Binding Source=list}"  AutoGenerateColumns="False" CanUserResizeColumns="True">
    <DataGrid.Columns>                
        <DataGridTextColumn Header="ID" Binding="{Binding ID}"/>
        <DataGridTextColumn Header="Date" Binding="{Binding Date}"/>
   </DataGrid.Columns>
</DataGrid>

(This assumes that the element [UserControl, etc.] that contains the DataGrid has its DataContext bound to an object that contains the list collection. The DataGrid is derived from ItemsControl, which relies on its ItemsSource property to define the collection it binds its rows to. Hence, if list isn't a property of an object bound to your control's DataContext, you might need to set both DataContext={Binding list} and ItemsSource={Binding list} on the DataGrid...)

jquery 3.0 url.indexOf error

@choz answer is the correct way. If you have many usages and want to make sure it works everywhere without changes you can add these small migration-snippet:

/* Migration jQuery from 1.8 to 3.x */
jQuery.fn.load = function (callback) {
    var el = $(this);

    el.on('load', callback);

    return el;
};

In this case you got no erros on other nodes e.g. on $image like in @Korsmakolnikov answer!

const $image = $('img.image').load(function() {
  $(this).doSomething();
});

$image.doSomethingElseWithTheImage();

Exclude Blank and NA in R

Don't know exactly what kind of dataset you have, so I provide general answer.

x <- c(1,2,NA,3,4,5)
y <- c(1,2,3,NA,6,8)
my.data <- data.frame(x, y)
> my.data
   x  y
1  1  1
2  2  2
3 NA  3
4  3 NA
5  4  6
6  5  8
# Exclude rows with NA values
my.data[complete.cases(my.data),]
  x y
1 1 1
2 2 2
5 4 6
6 5 8

How do I convert from a money datatype in SQL server?

It seems despite the intrinsic limitations of the money datatype, if you're already using it (or have inherited it as I have) the answer to your question is, use DECIMAL.

Best way to incorporate Volley (or other library) into Android Studio project

As pointed out by others as well, Volley is officially available on Github:

Add this line to your gradle dependencies for volley:

compile 'com.android.volley:volley:1.0.0'


To install volley from source read below:

I like to keep the official volley repository in my app. That way I get it from the official source and can get updates without depending on anyone else and mitigating concerns expressed by other people.

Added volley as a submodule alongside app.

git submodule add -b master https://github.com/google/volley.git volley

In my settings.gradle, added the following line to add volley as a module.

include ':volley'

In my app/build.gradle, I added a compile dependency for the volley project

compile project(':volley')

That's all! Volley can now be used in my project.

Everytime I want to sync the volley module with Google's repo, i run this.

git submodule foreach git pull

Lint: How to ignore "<key> is not translated in <language>" errors?

Another approach is to indicate the languages you intend to support and filter out the rest using the 'resConfigs' option with Gradle.

Check out this other answer for details

This is better, I think, because you don't have to completely ignore legitimate translation mistakes for languages you actually want to support

How to execute a .sql script from bash

You simply need to start mysql and feed it with the content of db.sql:

mysql -u user -p < db.sql

Change div width live with jQuery

There are two ways to do this:

CSS: Use width as %, like 75%, so the width of the div will change automatically when user resizes the browser.

Javascipt: Use resize event

$(window).bind('resize', function()
{
    if($(window).width() > 500)
        $('#divID').css('width', '300px');
    else
        $('divID').css('width', '200px');
});

Hope this will help you :)

What's the difference between an id and a class?

A CLASS should be used for multiple elements that you want the same styling for. An ID should be for a unique element. See this tutorial.

You should refer to the W3C standards if you want to be a strict conformist, or if you want your pages to be validated to the standards.

Update elements in a JSONObject

Hello I can suggest you universal method. use recursion.

    public static JSONObject function(JSONObject obj, String keyMain,String valueMain, String newValue) throws Exception {
    // We need to know keys of Jsonobject
    JSONObject json = new JSONObject()
    Iterator iterator = obj.keys();
    String key = null;
    while (iterator.hasNext()) {
        key = (String) iterator.next();
        // if object is just string we change value in key
        if ((obj.optJSONArray(key)==null) && (obj.optJSONObject(key)==null)) {
            if ((key.equals(keyMain)) && (obj.get(key).toString().equals(valueMain))) {
                // put new value
                obj.put(key, newValue);
                return obj;
            }
        }

        // if it's jsonobject
        if (obj.optJSONObject(key) != null) {
            function(obj.getJSONObject(key), keyMain, valueMain, newValue);
        }

        // if it's jsonarray
        if (obj.optJSONArray(key) != null) {
            JSONArray jArray = obj.getJSONArray(key);
            for (int i=0;i<jArray.length();i++) {
                    function(jArray.getJSONObject(i), keyMain, valueMain, newValue);
            }
        }
    }
    return obj;
}

It should work. If you have questions, go ahead.. I'm ready.

How do I get currency exchange rates via an API such as Google Finance?

Here are some exchange APIs with PHP example.

[ Open Exchange Rates API ]

Provides 1,000 requests per month free. You must register and grab the App ID. The base currency USD for free account. Check the supported currencies and documentation.

// open exchange URL // valid app_id * REQUIRED *
$exchange_url = 'https://openexchangerates.org/api/latest.json';
$params = array(
    'app_id' => 'YOUR_APP_ID'
);

// make cURL request // parse JSON
$curl = curl_init();
curl_setopt_array($curl, array(
    CURLOPT_URL => $exchange_url . '?' . http_build_query($params),
    CURLOPT_RETURNTRANSFER => true
));
$response = json_decode(curl_exec($curl));
curl_close($curl);

if (!empty($response->rates)) {
    // convert 150 USD to JPY ( Japanese Yen )
    echo $response->rates->JPY * 150;
}

150 USD = 18039.09015 JPY

[ Currency Layer API ]

Provides 1,000 requests per month free. You must register and grab the Access KEY. Custom base currency is not supported in free account. Check the documentation.

$exchange_url = 'http://apilayer.net/api/live';
$params = array(
    'access_key' => 'YOUR_ACCESS_KEY',
    'source' => 'USD',
    'currencies' => 'JPY',
    'format' => 1 // 1 = JSON
);

// make cURL request // parse JSON
$curl = curl_init();
curl_setopt_array($curl, array(
    CURLOPT_URL => $exchange_url . '?' . http_build_query($params),
    CURLOPT_RETURNTRANSFER => true
));
$response = json_decode(curl_exec($curl));
curl_close($curl);

if (!empty($response->quotes)) {
    // convert 150 USD to JPY ( Japanese Yen )
    echo '150 USD = ' . $response->quotes->USDJPY * 150 . ' JPY';
}

150 USD = 18036.75045 JPY

How can I throw CHECKED exceptions from inside Java 8 streams?

I think this approach is the right one:

public List<Class> getClasses() throws ClassNotFoundException {
    List<Class> classes;
    try {
        classes = Stream.of("java.lang.Object", "java.lang.Integer", "java.lang.String").map(className -> {
            try {
                return Class.forName(className);
            } catch (ClassNotFoundException e) {
                throw new UndeclaredThrowableException(e);
            }
        }).collect(Collectors.toList());
    } catch (UndeclaredThrowableException e) {
        if (e.getCause() instanceof ClassNotFoundException) {
            throw (ClassNotFoundException) e.getCause();
        } else {
            // this should never happen
            throw new IllegalStateException(e.getMessage(), e);
        }
    }
    return classes;
}

Wrapping the checked exception inside the Callable in a UndeclaredThrowableException (that’s the use case for this exception) and unwrapping it outside.

Yes, I find it ugly, and I would advise against using lambdas in this case and just fall back to a good old loop, unless you are working with a parallel stream and paralellization brings an objective benefit that justifies the unreadability of the code.

As many others have pointed out, there are solutions to this situation, and I hope one of them will make it into a future version of Java.

Can you use CSS to mirror/flip text?

There's also the rotateY for a real mirror one:

transform: rotateY(180deg);

Which, perhaps, is even more clear and understandable.

EDIT: Doesn't seem to work on Opera though… sadly. But it works fine on Firefox. I guess it might required to implicitly say that we are doing some kind of translate3d perhaps? Or something like that.

Remove all items from a FormArray in Angular

While loop will take long time to delete all items if array has 100's of items. You can empty both controls and value properties of FormArray like below.

clearFormArray = (formArray: FormArray) => { formArray.controls = []; formArray.setValue([]); }

How to convert a hex string to hex number

Use int function with second parameter 16, to convert a hex string to an integer. Finally, use hex function to convert it back to a hexadecimal number.

print hex(int("0xAD4", 16) + int("0x200", 16)) # 0xcd4

Instead you could directly do

print hex(int("0xAD4", 16) + 0x200) # 0xcd4

Looping over a list in Python

You may as well use for x in values rather than for x in values[:]; the latter makes an unnecessary copy. Also, of course that code checks for a length of 2 rather than of 3...

The code only prints one item per value of x - and x is iterating over the elements of values, which are the sublists. So it will only print each sublist once.

How to restore the menu bar in Visual Studio Code

Some changes to this coming in v1.54, see https://github.com/microsoft/vscode-docs/blob/vnext/release-notes/v1_54.md#updated-application-menu-settings

Updated Application Menu Settings

The window.menuBarVisibility setting for the application menu visibility has been updated to better reflect the options. Two primary changes have been made.

First, the default option for the setting has been renamed to classic.

Second, the Show Menu Bar entry in the the application menu bar now toggles between the classic and compact options. To hide it completely, you can update the setting, or use the context menu of the Activity Bar when in compact mode.

What is a Y-combinator?

A fixed point combinator (or fixed-point operator) is a higher-order function that computes a fixed point of other functions. This operation is relevant in programming language theory because it allows the implementation of recursion in the form of a rewrite rule, without explicit support from the language's runtime engine. (src Wikipedia)

How to go from Blob to ArrayBuffer

This is an async method which first checks for the availability of arrayBuffer method. This function is backward compatible and future proof.

async function blobToArrayBuffer(blob) {
    if ('arrayBuffer' in blob) return await blob.arrayBuffer();
    
    return new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.onload = () => resolve(reader.result);
        reader.onerror = () => reject;
        reader.readAsArrayBuffer(blob);
    });
}

Oracle SQL: Use sequence in insert with Select Statement

I tested and the script run ok!

INSERT INTO HISTORICAL_CAR_STATS (HISTORICAL_CAR_STATS_ID, YEAR,MONTH,MAKE,MODEL,REGION,AVG_MSRP,COUNT) 
WITH DATA AS
(
    SELECT '2010' YEAR,'12' MONTH ,'ALL' MAKE,'ALL' MODEL,REGION,sum(AVG_MSRP*COUNT)/sum(COUNT) AVG_MSRP,sum(Count) COUNT
    FROM HISTORICAL_CAR_STATS
    WHERE YEAR = '2010' AND MONTH = '12'
    AND MAKE != 'ALL' GROUP BY REGION
)
SELECT MY_SEQ.NEXTVAL, YEAR,MONTH,MAKE,MODEL,REGION,AVG_MSRP,COUNT
FROM DATA;

you can read this article to understand more! http://www.orafaq.com/wiki/ORA-02287

How to generate xsd from wsdl

(WHEN .wsdl is referring to .xsd/schemas using import) If you're using the WMB Tooklit (v8.0.0.4 WMB) then you can find .xsd using following steps :

Create library (optional) > Right Click , New Message Model File > Select SOAP XML > Choose Option 'I already have WSDL for my data' > 'Select file outside workspace' > 'Select the WSDL bindings to Import' (if there are multiple) > Finish.

This will give you the .xsd and .wsdl files in your Workspace (Application Perspective).

Singleton: How should it be used

If you are the one who created the singleton and who uses it, dont make it as singleton (it doesn't have sense because you can control the singularity of the object without making it singleton) but it makes sense when you a developer of a library and you want to supply only one object to your users (in this case you are the who created the singleton, but you aren't the user).

Singletons are objects so use them as objects, many people accesses to singletons directly through calling the method which returns it, but this is harmful because you are making your code knows that object is singleton, I prefer to use singletons as objects, I pass them through the constructor and I use them as ordinary objects, by that way, your code doesn't know if these objects are singletons or not and that makes the dependencies more clear and it helps a little for refactoring ...

Change action bar color in android

onclick buttons c2 to fetch and change the color of action bar and notification bar according to button's background, hope this helps

int color = c2.getBackground()).getColor();
int colorlighter = -color * 40 / 100 + color;
getWindow().setNavigationBarColor(colorlighter);
getWindow().setStatusBarColor(colorlighter);
ActionBar bar = getSupportActionBar();
bar.setBackgroundDrawable(new ColorDrawable(color));

colorlighter is used to set color of notification bar a little lighter than action bar
color is the background color of button c2, according to which we change our color.

Can jQuery check whether input content has changed?

function checkChange($this){
    var value = $this.val();      
    var sv=$this.data("stored");            
        if(value!=sv)
            $this.trigger("simpleChange");    
}

$(document).ready(function(){
    $(this).data("stored",$(this).val());   
        $("input").bind("keyup",function(e){  
        checkChange($(this));
    });        
    $("input").bind("simpleChange",function(e){
        alert("the value is chaneged");
    });        
});

here is the fiddle http://jsfiddle.net/Q9PqT/1/

getResourceAsStream returns null

Don't use absolute paths, make them relative to the 'resources' directory in your project. Quick and dirty code that displays the contents of MyTest.txt from the directory 'resources'.

@Test
public void testDefaultResource() {
    // can we see default resources
    BufferedInputStream result = (BufferedInputStream) 
         Config.class.getClassLoader().getResourceAsStream("MyTest.txt");
    byte [] b = new byte[256];
    int val = 0;
    String txt = null;
    do {
        try {
            val = result.read(b);
            if (val > 0) {
                txt += new String(b, 0, val);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } 
    } while (val > -1);
    System.out.println(txt);
}

pyplot scatter plot marker size

Because other answers here claim that s denotes the area of the marker, I'm adding this answer to clearify that this is not necessarily the case.

Size in points^2

The argument s in plt.scatter denotes the markersize**2. As the documentation says

s : scalar or array_like, shape (n, ), optional
size in points^2. Default is rcParams['lines.markersize'] ** 2.

This can be taken literally. In order to obtain a marker which is x points large, you need to square that number and give it to the s argument.

So the relationship between the markersize of a line plot and the scatter size argument is the square. In order to produce a scatter marker of the same size as a plot marker of size 10 points you would hence call scatter( .., s=100).

enter image description here

import matplotlib.pyplot as plt

fig,ax = plt.subplots()

ax.plot([0],[0], marker="o",  markersize=10)
ax.plot([0.07,0.93],[0,0],    linewidth=10)
ax.scatter([1],[0],           s=100)

ax.plot([0],[1], marker="o",  markersize=22)
ax.plot([0.14,0.86],[1,1],    linewidth=22)
ax.scatter([1],[1],           s=22**2)

plt.show()

Connection to "area"

So why do other answers and even the documentation speak about "area" when it comes to the s parameter?

Of course the units of points**2 are area units.

  • For the special case of a square marker, marker="s", the area of the marker is indeed directly the value of the s parameter.
  • For a circle, the area of the circle is area = pi/4*s.
  • For other markers there may not even be any obvious relation to the area of the marker.

enter image description here

In all cases however the area of the marker is proportional to the s parameter. This is the motivation to call it "area" even though in most cases it isn't really.

Specifying the size of the scatter markers in terms of some quantity which is proportional to the area of the marker makes in thus far sense as it is the area of the marker that is perceived when comparing different patches rather than its side length or diameter. I.e. doubling the underlying quantity should double the area of the marker.

enter image description here

What are points?

So far the answer to what the size of a scatter marker means is given in units of points. Points are often used in typography, where fonts are specified in points. Also linewidths is often specified in points. The standard size of points in matplotlib is 72 points per inch (ppi) - 1 point is hence 1/72 inches.

It might be useful to be able to specify sizes in pixels instead of points. If the figure dpi is 72 as well, one point is one pixel. If the figure dpi is different (matplotlib default is fig.dpi=100),

1 point == fig.dpi/72. pixels

While the scatter marker's size in points would hence look different for different figure dpi, one could produce a 10 by 10 pixels^2 marker, which would always have the same number of pixels covered:

enter image description here enter image description here enter image description here

import matplotlib.pyplot as plt

for dpi in [72,100,144]:

    fig,ax = plt.subplots(figsize=(1.5,2), dpi=dpi)
    ax.set_title("fig.dpi={}".format(dpi))

    ax.set_ylim(-3,3)
    ax.set_xlim(-2,2)

    ax.scatter([0],[1], s=10**2, 
               marker="s", linewidth=0, label="100 points^2")
    ax.scatter([1],[1], s=(10*72./fig.dpi)**2, 
               marker="s", linewidth=0, label="100 pixels^2")

    ax.legend(loc=8,framealpha=1, fontsize=8)

    fig.savefig("fig{}.png".format(dpi), bbox_inches="tight")

plt.show() 

If you are interested in a scatter in data units, check this answer.

Use ffmpeg to add text subtitles

This is the reason why mkv is such a good container, especially now that it's mature:

mkvmerge -o output.mkv video.mp4 subtitle.srt

System not declared in scope?

You need to add:

 #include <cstdlib>

in order for the compiler to see the prototype for system().

UPDATE multiple tables in MySQL using LEFT JOIN

Table A 
+--------+-----------+
| A-num  | text      | 
|    1   |           |
|    2   |           |
|    3   |           |
|    4   |           |
|    5   |           |
+--------+-----------+

Table B
+------+------+--------------+
| B-num|  date        |  A-num | 
|  22  |  01.08.2003  |     2  |
|  23  |  02.08.2003  |     2  | 
|  24  |  03.08.2003  |     1  |
|  25  |  04.08.2003  |     4  |
|  26  |  05.03.2003  |     4  |

I will update field text in table A with

UPDATE `Table A`,`Table B`
SET `Table A`.`text`=concat_ws('',`Table A`.`text`,`Table B`.`B-num`," from                                           
",`Table B`.`date`,'/')
WHERE `Table A`.`A-num` = `Table B`.`A-num`

and come to this result:

Table A 
+--------+------------------------+
| A-num  | text                   | 
|    1   |  24 from 03 08 2003 /  |
|    2   |  22 from 01 08 2003 /  |       
|    3   |                        |
|    4   |  25 from 04 08 2003 /  |
|    5   |                        |
--------+-------------------------+

where only one field from Table B is accepted, but I will come to this result:

Table A 
+--------+--------------------------------------------+
| A-num  | text                                       | 
|    1   |  24 from 03 08 2003                        |
|    2   |  22 from 01 08 2003 / 23 from 02 08 2003 / |       
|    3   |                                            |
|    4   |  25 from 04 08 2003 / 26 from 05 03 2003 / |
|    5   |                                            |
+--------+--------------------------------------------+

Is a DIV inside a TD a bad idea?

After checking the XHTML DTD I discovered that a <TD>-element is allowed to contain block elements like headings, lists and also <DIV>-elements. Thus, using a <DIV>-element inside a <TD>-element does not violate the XHTML standard. I'm pretty sure that other modern variations of HTML have an equivalent content model for the <TD>-element.

Here are the relevant DTD rules:

<!ELEMENT td %Flow;>
<!-- %Flow; mixes block and inline and is used for list items etc. -->
<!ENTITY %Flow "(#PCDATA | %block; | form | %inline; | %misc;>
<!ENTITY %block "p | %heading; | div | %lists; | %blocktext; | fieldset | table">

How do you post to an iframe?

An iframe is used to embed another document inside a html page.

If the form is to be submitted to an iframe within the form page, then it can be easily acheived using the target attribute of the tag.

Set the target attribute of the form to the name of the iframe tag.

<form action="action" method="post" target="output_frame">
    <!-- input elements here --> 
</form>
<iframe name="output_frame" src="" id="output_frame" width="XX" height="YY">
</iframe>           

Advanced iframe target use
This property can also be used to produce an ajax like experience, especially in cases like file upload, in which case where it becomes mandatory to submit the form, in order to upload the files

The iframe can be set to a width and height of 0, and the form can be submitted with the target set to the iframe, and a loading dialog opened before submitting the form. So, it mocks a ajax control as the control still remains on the input form jsp, with the loading dialog open.

Exmaple

<script>
$( "#uploadDialog" ).dialog({ autoOpen: false, modal: true, closeOnEscape: false,                 
            open: function(event, ui) { jQuery('.ui-dialog-titlebar-close').hide(); } });

function startUpload()
{            
    $("#uploadDialog").dialog("open");
}

function stopUpload()
{            
    $("#uploadDialog").dialog("close");
}
</script>

<div id="uploadDialog" title="Please Wait!!!">
            <center>
            <img src="/imagePath/loading.gif" width="100" height="100"/>
            <br/>
            Loading Details...
            </center>
 </div>

<FORM  ENCTYPE="multipart/form-data" ACTION="Action" METHOD="POST" target="upload_target" onsubmit="startUpload()"> 
<!-- input file elements here--> 
</FORM>

<iframe id="upload_target" name="upload_target" src="#" style="width:0;height:0;border:0px solid #fff;" onload="stopUpload()">   
        </iframe>

When is the init() function run?

Something to add to this (which I would've added as a comment but the time of writing this post I'd not yet enough reputation)

Having multiple inits in the same package I've not yet found any guaranteed way to know what order in which they will be run. For example I have:

package config
    - config.go
    - router.go

Both config.go and router.go contain init() functions, but when running router.go's function ran first (which caused my app to panic).

If you're in a situation where you have multiple files, each with its own init() function be very aware that you aren't guaranteed to get one before the other. It is better to use a variable assignment as OneToOne shows in his example. Best part is: This variable declaration will happen before ALL init() functions in the package.

For example

config.go:

var ConfigSuccess = configureApplication()

func init() {
    doSomething()
}

func configureApplication() bool {
    l4g.Info("Configuring application...")
    if valid := loadCommandLineFlags(); !valid {
        l4g.Critical("Failed to load Command Line Flags")
        return false
    }
    return true
}

router.go:

func init() {
    var (
        rwd string
        tmp string
        ok  bool
    )
    if metapath, ok := Config["fs"]["metapath"].(string); ok {
        var err error
        Conn, err = services.NewConnection(metapath + "/metadata.db")
        if err != nil {
            panic(err)
        }
    }
}

regardless of whether var ConfigSuccess = configureApplication() exists in router.go or config.go, it will be run before EITHER init() is run.

How can I check if given int exists in array?

You can use std::find for this:

#include <algorithm> // for std::find
#include <iterator> // for std::begin, std::end

int main () 
{
  int a[] = {3, 6, 8, 33};
  int x = 8;
  bool exists = std::find(std::begin(a), std::end(a), x) != std::end(a);
}

std::find returns an iterator to the first occurrence of x, or an iterator to one-past the end of the range if x is not found.

What is the precise meaning of "ours" and "theirs" in git?

The 'ours' in Git is referring to the original working branch which has authoritative/canonical part of git history.

The 'theirs' refers to the version that holds the work in order to be rebased (changes to be replayed onto the current branch).

This may appear to be swapped to people who are not aware that doing rebasing (e.g. git rebase) is actually taking your work on hold (which is theirs) in order to replay onto the canonical/main history which is ours, because we're rebasing our changes as third-party work.

The documentation for git-checkout was further clarified in Git >=2.5.1 as per f303016 commit:

--ours --theirs

When checking out paths from the index, check out stage #2 ('ours') or #3 ('theirs') for unmerged paths.

Note that during git rebase and git pull --rebase, 'ours' and 'theirs' may appear swapped; --ours gives the version from the branch the changes are rebased onto, while --theirs gives the version from the branch that holds your work that is being rebased.

This is because rebase is used in a workflow that treats the history at the remote as the shared canonical one, and treats the work done on the branch you are rebasing as the third-party work to be integrated, and you are temporarily assuming the role of the keeper of the canonical history during the rebase. As the keeper of the canonical history, you need to view the history from the remote as ours (i.e. "our shared canonical history"), while what you did on your side branch as theirs (i.e. "one contributor's work on top of it").

For git-merge it's explain in the following way:

ours

This option forces conflicting hunks to be auto-resolved cleanly by favoring our version. Changes from the other tree that do not conflict with our side are reflected to the merge result. For a binary file, the entire contents are taken from our side.

This should not be confused with the ours merge strategy, which does not even look at what the other tree contains at all. It discards everything the other tree did, declaring our history contains all that happened in it.

theirs

This is the opposite of ours.

Further more, here is explained how to use them:

The merge mechanism (git merge and git pull commands) allows the backend merge strategies to be chosen with -s option. Some strategies can also take their own options, which can be passed by giving -X<option> arguments to git merge and/or git pull.


So sometimes it can be confusing, for example:

  • git pull origin master where -Xours is our local, -Xtheirs is theirs (remote) branch
  • git pull origin master -r where -Xours is theirs (remote), -Xtheirs is ours

So the 2nd example is opposite to the 1st one, because we're rebasing our branch on top of the remote one, so our starting point is remote one, and our changes are treated as external.

Similar for git merge strategies (-X ours and -X theirs).

Append String in Swift

let string2 = " there"
var instruction = "look over"

choice 1 :

 instruction += string2;

  println(instruction)

choice 2:

 var Str = instruction + string2;

 println(Str)

ref this

How to split data into training/testing sets using sample function

Assuming df is your data frame, and that you want to create 75% train and 25% test

all <- 1:nrow(df)
train_i <- sort(sample(all, round(nrow(df)*0.75,digits = 0),replace=FALSE))
test_i <- all[-train_i]

Then to create a train and test data frames

df_train <- df[train_i,]
df_test <- df[test_i,]

Is it possible to have empty RequestParam values use the defaultValue?

You can keep primitive type by setting default value, in the your case just add "required = false" property:

@RequestParam(value = "i", required = false, defaultValue = "10") int i

P.S. This page from Spring documentation might be useful: Annotation Type RequestParam

Can't perform a React state update on an unmounted component

If above solutions dont work, try this and it works for me:

componentWillUnmount() {
    // fix Warning: Can't perform a React state update on an unmounted component
    this.setState = (state,callback)=>{
        return;
    };
}

Create a basic matrix in C (input by user !)

need a

for(i=0;i<2;i++)
{
  for(j=0;j<2;j++)
  {
     printf("%d",mat[i][j]);
  }
  printf("\n");
}

Using Rsync include and exclude options to include directory and file by pattern

rsync include exclude pattern examples:

"*"         means everything
"dir1"      transfers empty directory [dir1]
"dir*"      transfers empty directories like: "dir1", "dir2", "dir3", etc...
"file*"     transfers files whose names start with [file]
"dir**"     transfers every path that starts with [dir] like "dir1/file.txt", "dir2/bar/ffaa.html", etc...
"dir***"    same as above
"dir1/*"    does nothing
"dir1/**"   does nothing
"dir1/***"  transfers [dir1] directory and all its contents like "dir1/file.txt", "dir1/fooo.sh", "dir1/fold/baar.py", etc...

And final note is that simply dont rely on asterisks that are used in the beginning for evaluating paths; like "**dir" (its ok to use them for single folders or files but not paths) and note that more than two asterisks dont work for file names.

Why doesn't GCC optimize a*a*a*a*a*a to (a*a*a)*(a*a*a)?

There are already a few good answers to this question, but for the sake of completeness I wanted to point out that the applicable section of the C standard is 5.1.2.2.3/15 (which is the same as section 1.9/9 in the C++11 standard). This section states that operators can only be regrouped if they are really associative or commutative.

nginx- duplicate default server error

Execute this at the terminal to see conflicting configurations listening to the same port:

grep -R default_server /etc/nginx

select the TOP N rows from a table

Assuming your page size is 20 record, and you wanna get page number 2, here is how you would do it:

SQL Server, Oracle:

SELECT *   -- <-- pick any columns here from your table, if you wanna exclude the RowNumber
FROM (SELECT ROW_NUMBER OVER(ORDER BY ID DESC) RowNumber, * 
      FROM Reflow  
      WHERE ReflowProcessID = somenumber) t
WHERE RowNumber >= 20 AND RowNumber <= 40    

MySQL:

SELECT * 
FROM Reflow  
WHERE ReflowProcessID = somenumber
ORDER BY ID DESC
LIMIT 20 OFFSET 20

Getting results between two dates in PostgreSQL

You have to use the date part fetching method:

SELECT * FROM testbed WHERE start_date  ::date >= to_date('2012-09-08' ,'YYYY-MM-DD') and date::date <= to_date('2012-10-09' ,'YYYY-MM-DD')

Running .sh scripts in Git Bash

Once you're in the directory, just run it as ./myScript.sh

What is the difference between Select and Project Operations

selection opertion is used to select a subset of tuple from the relation that satisfied selection condition It filter out those tuple that satisfied the condition .Selection opertion can be visualized as horizontal partition into two set of tuple - those tuple satisfied the condition are selected and those tuple do not select the condition are discarded sigma (R) projection opertion is used to select a attribute from the relation that satisfied selection condition . It filter out only those tuple that satisfied the condition . The projection opertion can be visualized as a vertically partition into two part -are those satisfied the condition are selected other discarded ?(R) attribute list is a num of attribute

Binding ItemsSource of a ComboBoxColumn in WPF DataGrid

RookieRick is right, using DataGridTemplateColumn instead of DataGridComboBoxColumn gives a much simpler XAML.

Moreover, putting the CompanyItem list directly accessible from the GridItem allows you to get rid of the RelativeSource.

IMHO, this give you a very clean solution.

XAML:

<DataGrid AutoGenerateColumns="False" ItemsSource="{Binding GridItems}" >
    <DataGrid.Resources>
        <DataTemplate x:Key="CompanyDisplayTemplate" DataType="vm:GridItem">
            <TextBlock Text="{Binding Company}" />
        </DataTemplate>
        <DataTemplate x:Key="CompanyEditingTemplate" DataType="vm:GridItem">
            <ComboBox SelectedItem="{Binding Company}" ItemsSource="{Binding CompanyList}" />
        </DataTemplate>
    </DataGrid.Resources>
    <DataGrid.Columns>
        <DataGridTextColumn Binding="{Binding Name}" />
        <DataGridTemplateColumn CellTemplate="{StaticResource CompanyDisplayTemplate}"
                                CellEditingTemplate="{StaticResource CompanyEditingTemplate}" />
    </DataGrid.Columns>
</DataGrid>

View model:

public class GridItem
{
    public string Name { get; set; }
    public CompanyItem Company { get; set; }
    public IEnumerable<CompanyItem> CompanyList { get; set; }
}

public class CompanyItem
{
    public int ID { get; set; }
    public string Name { get; set; }

    public override string ToString() { return Name; }
}

public class ViewModel
{
    readonly ObservableCollection<CompanyItem> companies;

    public ViewModel()
    {
        companies = new ObservableCollection<CompanyItem>{
            new CompanyItem { ID = 1, Name = "Company 1" },
            new CompanyItem { ID = 2, Name = "Company 2" }
        };

        GridItems = new ObservableCollection<GridItem> {
            new GridItem { Name = "Jim", Company = companies[0], CompanyList = companies}
        };
    }

    public ObservableCollection<GridItem> GridItems { get; set; }
}

How can I determine the direction of a jQuery scroll event?

In case you just want to know if you scroll up or down using a pointer device (mouse or track pad) you can use the deltaY property of the wheel event.

_x000D_
_x000D_
$('.container').on('wheel', function(event) {_x000D_
  if (event.originalEvent.deltaY > 0) {_x000D_
    $('.result').append('Scrolled down!<br>');_x000D_
  } else {_x000D_
    $('.result').append('Scrolled up!<br>');_x000D_
  }_x000D_
});
_x000D_
.container {_x000D_
  height: 200px;_x000D_
  width: 400px;_x000D_
  margin: 20px;_x000D_
  border: 1px solid black;_x000D_
  overflow-y: auto;_x000D_
}_x000D_
.content {_x000D_
  height: 300px;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
<div class="container">_x000D_
  <div class="content">_x000D_
    Scroll me!_x000D_
  </div>_x000D_
</div>_x000D_
_x000D_
<div class="result">_x000D_
  <p>Action:</p>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How do you change the size of figures drawn with matplotlib?

Try commenting out the fig = ... line

%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt

N = 50
x = np.random.rand(N)
y = np.random.rand(N)
area = np.pi * (15 * np.random.rand(N))**2

fig = plt.figure(figsize=(18, 18))
plt.scatter(x, y, s=area, alpha=0.5)
plt.show()

Memory address of an object in C#

This works for me...

#region AddressOf

    /// <summary>
    /// Provides the current address of the given object.
    /// </summary>
    /// <param name="obj"></param>
    /// <returns></returns>
    [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]
    public static System.IntPtr AddressOf(object obj)
    {
        if (obj == null) return System.IntPtr.Zero;

        System.TypedReference reference = __makeref(obj);

        System.TypedReference* pRef = &reference;

        return (System.IntPtr)pRef; //(&pRef)
    }

    /// <summary>
    /// Provides the current address of the given element
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="t"></param>
    /// <returns></returns>
    [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]
    public static System.IntPtr AddressOf<T>(T t)
        //refember ReferenceTypes are references to the CLRHeader
        //where TOriginal : struct
    {
        System.TypedReference reference = __makeref(t);

        return *(System.IntPtr*)(&reference);
    }

    [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]
    static System.IntPtr AddressOfRef<T>(ref T t)
    //refember ReferenceTypes are references to the CLRHeader
    //where TOriginal : struct
    {
        System.TypedReference reference = __makeref(t);

        System.TypedReference* pRef = &reference;

        return (System.IntPtr)pRef; //(&pRef)
    }

    /// <summary>
    /// Returns the unmanaged address of the given array.
    /// </summary>
    /// <param name="array"></param>
    /// <returns><see cref="IntPtr.Zero"/> if null, otherwise the address of the array</returns>
    [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]
    public static System.IntPtr AddressOfByteArray(byte[] array)
    {
        if (array == null) return System.IntPtr.Zero;

        fixed (byte* ptr = array)
            return (System.IntPtr)(ptr - 2 * sizeof(void*)); //Todo staticaly determine size of void?
    }

    #endregion

Package signatures do not match the previously installed version

You need to uninstall it because you are using a different signature than the original. If it is not working it might be because it is still installed for another user on the device. To completely uninstall, go to Settings -> Apps -> HAgnostic News -> Options (the three dots on top right) -> Uninstall for all users

Google maps API V3 method fitBounds()

This happens because LatLngBounds() does not take two arbitrary points as parameters, but SW and NE points

use the .extend() method on an empty bounds object

var bounds = new google.maps.LatLngBounds();
bounds.extend(myPlace);
bounds.extend(Item_1);
map.fitBounds(bounds);

Demo at http://jsfiddle.net/gaby/22qte/

How to switch position of two items in a Python list?

for i in range(len(arr)):
    if l[-1] > l[i]:
        l[-1], l[i] = l[i], l[-1]
        break

as a result of this if last element is greater than element at position i then they both get swapped .

event.returnValue is deprecated. Please use the standard event.preventDefault() instead

I saw this warning on many websites. Also, I saw that YUI 3 library also gives the same warning. It's a warning generated from the library (whether is it jQuery or YUI).

How can I set an SQL Server connection string?

They are a number of things to worry about when connecting to SQL Server on another machine.

  • Host/IP address of the machine
  • Initial catalog (database name)
  • Valid username/password

Very often SQL Server may be running as a default instance which means you can simply specify the hostname/IP address, but you may encounter a scenario where it is running as a named instance (SQL Server Express Edition for instance). In this scenario you'll have to specify the hostname/instance name.

iOS app 'The application could not be verified' only on one device

To others not using RubyMotion and don't think that deleting the app is acceptable (as in, you want to do upgrade testing). Check out the bottom of these docs from Apple:

https://developer.apple.com/library/ios/technotes/tn2319/_index.html

It looks like they changed something in 8.1.3 to check for this new rule.

The Fix

"[Add] the installed application’s application-identifier value, as logged in the second parentheses, to the previous-application-identifiers entitlement’s array value for the app being installed (by resigning it or re-building it) and requesting new special provisioning profiles as shown below."

<key>previous-application-identifiers</key>
<array>
    <string>{Your Old App ID Prefix}.YourApp.Bundle.ID</string>
</array>

EDIT:

In order to do this, you need special provisioning profiles. You can request these from Apple: "To enable signing with the previous-application-identifiers entitlement new special provisioning profiles are required that can be obtained by going to the Contact US page and requesting them." (from the docs linked above).

WARNING: UNPROTECTED PRIVATE KEY FILE! when trying to SSH into Amazon EC2 Instance

Just a note for anyone who stumbles upon this:

If you are trying to SSH with a key that has been shared with you, for example:

ssh -i /path/to/keyfile.pem user@some-host

Where keyfile.pem is the private/public key shared with you and you're using it to connect, make sure you save it into ~/.ssh/ and chmod 777.

Trying to use the file when it was saved elsewhere on my machine was giving the OP's error. Not sure if it is directly related.

Add a summary row with totals

Try to use union all as below

SELECT [Type], [Total Sales] From Before
union all
SELECT 'Total', Sum([Total Sales]) From Before

if you have problem with ordering, as i-one suggested try this:

select [Type], [Total Sales] 
from (SELECT [Type], [Total Sales], 0 [Key] 
      From Before 
      union all 
      SELECT 'Total', Sum([Total Sales]), 1 From Before) sq 
order by [Key], Type

No module named 'pymysql'

I ran into the same problem earlier, but solved it in a way slightly different from what we have here. So, I thought I'd add my way as well. Hopefully, it will help someone!

sudo apt-get install mysql-client didn't work for me. However, I have Homebrew already installed. So, instead, I tried:

brew install mysql-client

Now, I don't get the error any more.

Good luck!

Convert HashBytes to VarChar

With personal experience of using the following code within a Stored Procedure which Hashed a SP Variable I can confirm, although undocumented, this combination works 100% as per my example:

@var=SUBSTRING(master.dbo.fn_varbintohexstr(HashBytes('SHA2_512', @SPvar)), 3, 128)

Javascript ajax call on page onload

It's even easier to do without a library

window.onload = function() {
    // code
};

Sqlite convert string to date

convert a string into date little issue think with indexing mmm 3,3 but works added a month on to the date string

SELECT substr('12Jan20',1,2) as dday,
date(substr('12Jan20',6,7) ||'00-' || case substr('12Jan20',3,3) when 'Jan' then '01'
when 'Feb' then '02'
when 'Mar' then '03'
when 'Apr' then '04'
when 'May' then '05' 
when 'Jun' then '06'
when 'Jul' then '07'
when 'Aug' then '08'
when 'Sep' then '09'
when 'Oct' then '10'
when 'Nov' then '11'
when 'Dec' then '12' end  || '-'||substr('12Jan20',1,2), '+1 month') as tt

Android - How to decode and decompile any APK file?

To decompile APK Use APKTool.
You can learn how APKTool works on http://www.decompileandroid.com/ or by reading the documentation.

IF statement: how to leave cell blank if condition is false ("" does not work)

The formula in C1

=IF(A1=1,B1,"")

is either giving an answer of "" (which isn't treated as blank) or the contents of B1.

If you want the formula in D1 to show TRUE if C1 is "" and FALSE if C1 has something else in then use the formula

=IF(C2="",TRUE,FALSE)

instead of ISBLANK

How does true/false work in PHP?

PHP uses weak typing (which it calls 'type juggling'), which is a bad idea (though that's a conversation for another time). When you try to use a variable in a context that requires a boolean, it will convert whatever your variable is into a boolean, according to some mostly arbitrary rules available here: http://www.php.net/manual/en/language.types.boolean.php#language.types.boolean.casting

Scroll to bottom of div?

Using jQuery, scrollTop is used to set the vertical position of scollbar for any given element. there is also a nice jquery scrollTo plugin used to scroll with animation and different options (demos)

var myDiv = $("#div_id").get(0);
myDiv.scrollTop = myDiv.scrollHeight;

if you want to use jQuery's animate method to add animation while scrolling down, check the following snippet:

var myDiv = $("#div_id").get(0);
myDiv.animate({
    scrollTop: myDiv.scrollHeight
  }, 500);

Brackets.io: Is there a way to auto indent / format <html>

I've been playing around with the preferences and added the following to my brackets.json file (access in Menu Bar: Debug: "Open Preferences File").

"closeTags": { "dontCloseTags": ["br", "hr", "img", "input", "link", "meta", "area", "base", "col", "command", "embed", "keygen", "param", "source", "track", "wbr"], "indentTags": ["ul", "ol", "div", "section", "table", "tr"], }

  • dontCloseTags are tags such as <br> which shouldn't be closed.
  • indentTags are tags that you want to automatically create a new indented line - add more as needed!
  • (any tags that aren't in above arrays will self-close on the same line)

How to compile a static library in Linux?

Here a full makefile example:

makefile

TARGET = prog

$(TARGET): main.o lib.a
    gcc $^ -o $@

main.o: main.c
    gcc -c $< -o $@

lib.a: lib1.o lib2.o
    ar rcs $@ $^

lib1.o: lib1.c lib1.h
    gcc -c -o $@ $<

lib2.o: lib2.c lib2.h
    gcc -c -o $@ $<

clean:
    rm -f *.o *.a $(TARGET)

explaining the makefile:

  • target: prerequisites - the rule head
  • $@ - means the target
  • $^ - means all prerequisites
  • $< - means just the first prerequisite
  • ar - a Linux tool to create, modify, and extract from archives see the man pages for further information. The options in this case mean:
    • r - replace files existing inside the archive
    • c - create a archive if not already existent
    • s - create an object-file index into the archive

To conclude: The static library under Linux is nothing more than a archive of object files.

main.c using the lib

#include <stdio.h>

#include "lib.h"

int main ( void )
{
    fun1(10);
    fun2(10);
    return 0;
}

lib.h the libs main header

#ifndef LIB_H_INCLUDED
#define LIB_H_INCLUDED

#include "lib1.h"
#include "lib2.h"

#endif

lib1.c first lib source

#include "lib1.h"

#include <stdio.h>

void fun1 ( int x )
{
    printf("%i\n",x);
}

lib1.h the corresponding header

#ifndef LIB1_H_INCLUDED
#define LIB1_H_INCLUDED

#ifdef __cplusplus
   extern “C” {
#endif

void fun1 ( int x );

#ifdef __cplusplus
   }
#endif

#endif /* LIB1_H_INCLUDED */

lib2.c second lib source

#include "lib2.h"

#include <stdio.h>

void fun2 ( int x )
{
    printf("%i\n",2*x);
}

lib2.h the corresponding header

#ifndef LIB2_H_INCLUDED
#define LIB2_H_INCLUDED

#ifdef __cplusplus
   extern “C” {
#endif

void fun2 ( int x );

#ifdef __cplusplus
   }
#endif

#endif /* LIB2_H_INCLUDED */

How to find out which package version is loaded in R?

To check the version of R execute : R --version

Or after you are in the R shell print the contents of version$version.string

EDIT

To check the version of installed packages do the following.

After loading the library, you can execute sessionInfo ()

But to know the list of all installed packages:

packinfo <- installed.packages(fields = c("Package", "Version"))
packinfo[,c("Package", "Version")]

OR to extract a specific library version, once you have extracted the information using the installed.package function as above just use the name of the package in the first dimension of the matrix.

packinfo["RANN",c("Package", "Version")]
packinfo["graphics",c("Package", "Version")]

The above will print the versions of the RANN library and the graphics library.

Cluster analysis in R: determine the optimal number of clusters

A simple solution is the library factoextra. You can change the clustering method and the method for calculate the best number of groups. For example if you want to know the best number of clusters for a k- means:

Data: mtcars

library(factoextra)   
fviz_nbclust(mtcars, kmeans, method = "wss") +
      geom_vline(xintercept = 3, linetype = 2)+
      labs(subtitle = "Elbow method")

Finally, we get a graph like:

enter image description here

How do I supply an initial value to a text field?

I've seen many ways of doing this on here. However I think this is a little more efficient or at least concise than the other answers.

TextField(
   controller: TextEditingController(text: "Initial Text here"),
)

in angularjs how to access the element that triggered the event?

if you wanna ng-model value, if you can write like this in the triggered event: $scope.searchText

java.security.InvalidAlgorithmParameterException: the trustAnchors parameter must be non-empty on Linux, or why is the default truststore empty

Make sure that you have valid cacerts in the JRE/security, otherwise you will not bypass the invalid empty trustAnchors error.

In my Amazon EC2 Opensuse12 installation, the problem was that the file pointed by the cacerts in the JRE security directory was invalid:

$ java -version
java version "1.7.0_09"
OpenJDK Runtime Environment (IcedTea7 2.3.4) (suse-3.20.1-x86_64)
OpenJDK 64-Bit Server VM (build 23.2-b09, mixed mode)

$ ls -l /var/lib/ca-certificates/
-rw-r--r-- 1 root    363 Feb 28 14:17 ca-bundle.pem

$ ls -l /usr/lib64/jvm/jre/lib/security/
lrwxrwxrwx 1 root    37 Mar 21 00:16 cacerts -> /var/lib/ca-certificates/java-cacerts
-rw-r--r-- 1 root  2254 Jan 18 16:50 java.policy
-rw-r--r-- 1 root 15374 Jan 18 16:50 java.security
-rw-r--r-- 1 root    88 Jan 18 17:34 nss.cfg

So I solved installing an old Opensuse 11 valid certificates. (sorry about that!!)

$ ll
total 616
-rw-r--r-- 1 root 220065 Jan 31 15:48 ca-bundle.pem
-rw-r--r-- 1 root    363 Feb 28 14:17 ca-bundle.pem.old
-rw-r--r-- 1 root 161555 Jan 31 15:48 java-cacerts

I understood that you could use the keytool to generate a new one (http://mail.openjdk.java.net/pipermail/distro-pkg-dev/2010-April/008961.html). I'll probably have to that soon.

regards lellis

' << ' operator in verilog

1 << ADDR_WIDTH means 1 will be shifted 8 bits to the left and will be assigned as the value for RAM_DEPTH.

In addition, 1 << ADDR_WIDTH also means 2^ADDR_WIDTH.

Given ADDR_WIDTH = 8, then 2^8 = 256 and that will be the value for RAM_DEPTH

how to get a list of dates between two dates in java

Streams

Edit: Joda-Time is now deprecated, changed the answer to use Java 8 instead.

Here is the Java 8 way, using streams.

List<LocalDate> daysRange = Stream.iterate(startDate, date -> date.plusDays(1)).limit(numOfDays).collect(Collectors.toList());

How to know installed Oracle Client is 32 bit or 64 bit?

For Unix

grep "ARCHITECTURE" $ORACLE_HOME/inventory/ContentsXML/oraclehomeproperties.xml

And the output is:

<PROPERTY NAME="ARCHITECTURE" VAL="64"/> 

For Windows

findstr "ARCHITECTURE" %ORACLE_HOME%\inventory\ContentsXML\oraclehomeproperties.xml

And the output can be:

<PROPERTY NAME="ARCHITECTURE" VAL="64"/>

MySQL Multiple Left Joins

You're missing a GROUP BY clause:

SELECT news.id, users.username, news.title, news.date, news.body, COUNT(comments.id)
FROM news
LEFT JOIN users
ON news.user_id = users.id
LEFT JOIN comments
ON comments.news_id = news.id
GROUP BY news.id

The left join is correct. If you used an INNER or RIGHT JOIN then you wouldn't get news items that didn't have comments.

Getting values from query string in an url using AngularJS $location

First make the URL format correct for getting the query string use #?q=string that works for me

http://localhost/codeschool/index.php#?foo=abcd

Inject $location service into the controller

app.controller('MyController', [ '$location', function($location) { 

    var searchObject = $location.search();

    // $location.search(); reutrn object 
    // searchObject = { foo = 'abcd' };

    alert( searchObject.foo );

} ]);

So the out put should be abcd

Switch between two frames in tkinter

One way is to stack the frames on top of each other, then you can simply raise one above the other in the stacking order. The one on top will be the one that is visible. This works best if all the frames are the same size, but with a little work you can get it to work with any sized frames.

Note: for this to work, all of the widgets for a page must have that page (ie: self) or a descendant as a parent (or master, depending on the terminology you prefer).

Here's a bit of a contrived example to show you the general concept:

try:
    import tkinter as tk                # python 3
    from tkinter import font as tkfont  # python 3
except ImportError:
    import Tkinter as tk     # python 2
    import tkFont as tkfont  # python 2

class SampleApp(tk.Tk):

    def __init__(self, *args, **kwargs):
        tk.Tk.__init__(self, *args, **kwargs)

        self.title_font = tkfont.Font(family='Helvetica', size=18, weight="bold", slant="italic")

        # the container is where we'll stack a bunch of frames
        # on top of each other, then the one we want visible
        # will be raised above the others
        container = tk.Frame(self)
        container.pack(side="top", fill="both", expand=True)
        container.grid_rowconfigure(0, weight=1)
        container.grid_columnconfigure(0, weight=1)

        self.frames = {}
        for F in (StartPage, PageOne, PageTwo):
            page_name = F.__name__
            frame = F(parent=container, controller=self)
            self.frames[page_name] = frame

            # put all of the pages in the same location;
            # the one on the top of the stacking order
            # will be the one that is visible.
            frame.grid(row=0, column=0, sticky="nsew")

        self.show_frame("StartPage")

    def show_frame(self, page_name):
        '''Show a frame for the given page name'''
        frame = self.frames[page_name]
        frame.tkraise()


class StartPage(tk.Frame):

    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        self.controller = controller
        label = tk.Label(self, text="This is the start page", font=controller.title_font)
        label.pack(side="top", fill="x", pady=10)

        button1 = tk.Button(self, text="Go to Page One",
                            command=lambda: controller.show_frame("PageOne"))
        button2 = tk.Button(self, text="Go to Page Two",
                            command=lambda: controller.show_frame("PageTwo"))
        button1.pack()
        button2.pack()


class PageOne(tk.Frame):

    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        self.controller = controller
        label = tk.Label(self, text="This is page 1", font=controller.title_font)
        label.pack(side="top", fill="x", pady=10)
        button = tk.Button(self, text="Go to the start page",
                           command=lambda: controller.show_frame("StartPage"))
        button.pack()


class PageTwo(tk.Frame):

    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        self.controller = controller
        label = tk.Label(self, text="This is page 2", font=controller.title_font)
        label.pack(side="top", fill="x", pady=10)
        button = tk.Button(self, text="Go to the start page",
                           command=lambda: controller.show_frame("StartPage"))
        button.pack()


if __name__ == "__main__":
    app = SampleApp()
    app.mainloop()

start page page 1 page 2

If you find the concept of creating instance in a class confusing, or if different pages need different arguments during construction, you can explicitly call each class separately. The loop serves mainly to illustrate the point that each class is identical.

For example, to create the classes individually you can remove the loop (for F in (StartPage, ...) with this:

self.frames["StartPage"] = StartPage(parent=container, controller=self)
self.frames["PageOne"] = PageOne(parent=container, controller=self)
self.frames["PageTwo"] = PageTwo(parent=container, controller=self)

self.frames["StartPage"].grid(row=0, column=0, sticky="nsew")
self.frames["PageOne"].grid(row=0, column=0, sticky="nsew")
self.frames["PageTwo"].grid(row=0, column=0, sticky="nsew")

Over time people have asked other questions using this code (or an online tutorial that copied this code) as a starting point. You might want to read the answers to these questions:

Best way to deploy Visual Studio application that can run without installing

It is possible and is deceptively easy:

  1. "Publish" the application (to, say, some folder on drive C), either from menu Build or from the project's properties ? Publish. This will create an installer for a ClickOnce application.
  2. But instead of using the produced installer, find the produced files (the EXE file and the .config, .manifest, and .application files, along with any DLL files, etc.) - they are all in the same folder and typically in the bin\Debug folder below the project file (.csproj).
  3. Zip that folder (leave out any *.vhost.* files and the app.publish folder (they are not needed), and the .pdb files unless you foresee debugging directly on your user's system (for example, by remote control)), and provide it to the users.

An added advantage is that, as a ClickOnce application, it does not require administrative privileges to run (if your application follows the normal guidelines for which folders to use for application data, etc.).

As for .NET, you can check for the minimum required version of .NET being installed (or at all) in the application (most users will already have it installed) and present a dialog with a link to the download page on the Microsoft website (or point to one of your pages that could redirect to the Microsoft page - this makes it more robust if the Microsoft URL change). As it is a small utility, you could target .NET 2.0 to reduce the probability of a user to have to install .NET.

It works. We use this method during development and test to avoid having to constantly uninstall and install the application and still being quite close to how the final application will run.

What is the correct way to create a single-instance WPF application?

Look at the folllowing code. It is a great and simple solution to prevent multiple instances of a WPF application.

private void Application_Startup(object sender, StartupEventArgs e)
{
    Process thisProc = Process.GetCurrentProcess();
    if (Process.GetProcessesByName(thisProc.ProcessName).Length > 1)
    {
        MessageBox.Show("Application running");
        Application.Current.Shutdown();
        return;
    }

    var wLogin = new LoginWindow();

    if (wLogin.ShowDialog() == true)
    {
        var wMain = new Main();
        wMain.WindowState = WindowState.Maximized;
        wMain.Show();
    }
    else
    {
        Application.Current.Shutdown();
    }
}

Datatable to html Table

Just in case anyone arrives here and was hoping for VB (I did, and I didn't enter c# as a search term), here's the basics of the first response..

Public Shared Function ConvertDataTableToHTML(dt As DataTable) As String
    Dim html As String = "<table>"
    html += "<tr>"
    For i As Integer = 0 To dt.Columns.Count - 1
        html += "<td>" + System.Web.HttpUtility.HtmlEncode(dt.Columns(i).ColumnName) + "</td>"
    Next
    html += "</tr>"
    For i As Integer = 0 To dt.Rows.Count - 1
        html += "<tr>"
        For j As Integer = 0 To dt.Columns.Count - 1
            html += "<td>" + System.Web.HttpUtility.HtmlEncode(dt.Rows(i)(j).ToString()) + "</td>"
        Next
        html += "</tr>"
    Next
    html += "</table>"
    Return html
End Function

How to disable scrolling the document body?

add this css

body.disable-scroll {
    overflow: hidden;
}

and when to disable run this code

$("body").addClass("disable-scroll");

and when to enabled run this code

$("body").removeClass("disable-scroll")

jQuery Mobile: Stick footer to bottom of page

I thought I'd share my CSS only solution here. This way you can avoid the extra overhead of using JS for this.

This isn't a fixed position footer. The footer will be offscreen if the page content is taller than the screen. I think it looks better this way.

The body and .ui-page min-height and height are necessary to prevent the footer from jumping up and down during transitions.

Works with the latest JQM version as of now, 1.4.0

body,
.ui-page {
    min-height:100% !important;
    height:auto !important;
}

.ui-content {
    margin-bottom:42px; /* HEIGHT OF YOUR FOOTER */
}

.ui-footer {
    position:absolute !important;
    width:100%;
    bottom:0;
}

How to delete Tkinter widgets from a window?

You can use forget method on the widget

from tkinter import *

root = Tk()

b = Button(root, text="Delete me", command=b.forget)
b.pack()

b['command'] = b.forget

root.mainloop()

Absolute vs relative URLs

Assume we are creating a subsite whose files are in the folder http://site.ru/shop.

1. Absolute URL

Link to home page
href="http://sites.ru/shop/"

Link to the product page
href="http://sites.ru/shop/t-shirts/t-shirt-life-is-good/"

2. Relative URL

Link from home page to product page
href="t-shirts/t-shirt-life-is-good/"

Link from product page to home page
href="../../"

Although relative URL look shorter than absolute one, but the absolute URLs are more preferable, since a link can be used unchanged on any page of site.

Intermediate cases

We have considered two extreme cases: "absolutely" absolute and "absolutely" relative URLs. But everything is relative in this world. This also applies to URLs. Every time you say about absolute URL, you should always specify relative to what.

3. Protocol-relative URL

Link to home page
href="//sites.ru/shop/"

Link to product page
href="//sites.ru/shop/t-shirts/t-shirt-life-is-good/"

Google recommends such URL. Now, however, it is generally considered that http:// and https:// are different sites.

4. Root-relative URL

I.e. relative to the root folder of the domain.

Link to home page
href="/shop/"

Link to product page
href="/shop/t-shirts/t-shirt-life-is-good/"

It is a good choice if all pages are within the same domain. When you move your site to another domain, you don't have to do a mass replacements of the domain name in the URLs.

5. Base-relative URL (home-page-relative)

The tag <base> specifies the base URL, which is automatically added to all relative links and anchors. The base tag does not affect absolute links. As a base URL we'll specify the home page: <base href="http://sites.ru/shop/">.

Link to home page
href=""

Link to product page
href="t-shirts/t-shirt-life-is-good/"

Now you can move your site not only to any domain, but in any subfolder. Just keep in mind that, although URLs look like relative, in fact they are absolute. Especially pay attention to anchors. To navigate within the current page we have to write href="t-shirts/t-shirt-life-is-good/#comments" not href="#comments". The latter will throw on home page.

Conclusion

For internal links I use base-relative URLs (5). For external links and newsletters I use absolute URLs (1).

How to import image (.svg, .png ) in a React Component

You can also try:

...
var imageName = require('relative_path_of_image_from_component_file');
...
...

class XYZ extends Component {
    render(){
        return(
            ...
            <img src={imageName.default} alt="something"/>
            ...
        )
    }
}
...

Note: Make sure Image is not outside the project root folder.

Xcode 6: Keyboard does not show up in simulator

In the new simulator Hardware option is removed,

If you want to find a Keyboard option manually, Then click on the I/O section,

I/O -> Keyboard ->Toggle Software Keyboard(?K)

enter image description here

Android error while retrieving information from server 'RPC:s-5:AEC-0' in Google Play?

  1. Enter into SETTING
  2. Choose"Apps" & All
  3. Select Google Services Framework
  4. Clear data
  5. Force stop
  6. Go to Apps and download without error

iloc giving 'IndexError: single positional indexer is out-of-bounds'

This happens when you index a row/column with a number that is larger than the dimensions of your dataframe. For instance, getting the eleventh column when you have only three.

import pandas as pd

df = pd.DataFrame({'Name': ['Mark', 'Laura', 'Adam', 'Roger', 'Anna'],
                   'City': ['Lisbon', 'Montreal', 'Lisbon', 'Berlin', 'Glasgow'],
                   'Car': ['Tesla', 'Audi', 'Porsche', 'Ford', 'Honda']})

You have 5 rows and three columns:

    Name      City      Car
0   Mark    Lisbon    Tesla
1  Laura  Montreal     Audi
2   Adam    Lisbon  Porsche
3  Roger    Berlin     Ford
4   Anna   Glasgow    Honda

Let's try to index the eleventh column (it doesn't exist):

df.iloc[:, 10] # there is obviously no 11th column

IndexError: single positional indexer is out-of-bounds

If you are a beginner with Python, remember that df.iloc[:, 10] would refer to the eleventh column.

JSON.stringify doesn't work with normal Javascript array

Json has to have key-value pairs. Tho you can still have an array as the value part. Thus add a "key" of your chousing:

var json = JSON.stringify({whatver: test});

document.getElementById(id).focus() is not working for firefox or chrome

Place this source above your modal :

<script>
$('body').on('shown.bs.modal', '#IdYourModal', function () {
    document.getElementById('mobileno').focus();
})
</script>

How do I increase the RAM and set up host-only networking in Vagrant?

To increase the memory or CPU count when using Vagrant 2, add this to your Vagrantfile

Vagrant.configure("2") do |config|
    # usual vagrant config here

    config.vm.provider "virtualbox" do |v|
        v.memory = 1024
        v.cpus = 2
    end
end

"git checkout <commit id>" is changing branch to "no branch"

This worked best for me when I wanted to check out the code, given the commit ID <commit_id_SHA1>

git fetch origin <commit_id_SHA1>
git checkout -b new_branch FETCH_HEAD

Angular ForEach in Angular4/Typescript?

in angular4 foreach like that. try this.

 selectChildren(data, $event) {
      let parentChecked = data.checked;
       this.hierarchicalData.forEach(obj => {
          obj.forEach(childObj=> {
            value.checked = parentChecked;
         });
      });
    }

Capture close event on Bootstrap Modal

Though is answered in another stack overflow question Bind a function to Twitter Bootstrap Modal Close but for visual feel here is more detailed answer.

Source: http://getbootstrap.com/javascript/#modals-events