Programs & Examples On #Tournament

Can't install nuget package because of "Failed to initialize the PowerShell host"

I had the same problem with vs2013 and changing execution policy did not fix it. The only working solution I found was uninstalling Nuget from VS and installing it again. Steps are here: https://stackoverflow.com/a/32619961/3853238

How to unpublish an app in Google Play Developer Console

FYI, they've updated the Google Play developer page again. Now, at the far right, click the vertical ellipsis (like a colon with an extra dot in it). That now has the 'Unpublish App' option.

Remove redundant paths from $PATH variable

If you're using Bash, you can also do the following if, let's say, you want to remove the directory /home/wrong/dir/ from your PATH variable:

PATH=`echo $PATH | sed -e 's/:\/home\/wrong\/dir\/$//'`

How to generate random number with the specific length in python

To get a random 3-digit number:

from random import randint
randint(100, 999)  # randint is inclusive at both ends

(assuming you really meant three digits, rather than "up to three digits".)

To use an arbitrary number of digits:

from random import randint

def random_with_N_digits(n):
    range_start = 10**(n-1)
    range_end = (10**n)-1
    return randint(range_start, range_end)

print random_with_N_digits(2)
print random_with_N_digits(3)
print random_with_N_digits(4)

Output:

33
124
5127

jQuery date/time picker

Take a look at the following JavaScript plugin.

Javascript Calendar with date and time

I've made it to be simple as possible. but it still in its early days. Let me know the feedback so I could improve it.

Create an array with same element repeated multiple times

Use this function:

function repeatElement(element, count) {
    return Array(count).fill(element)
}
>>> repeatElement('#', 5).join('')
"#####"

Or for a more compact version:

const repeatElement = (element, count) =>
    Array(count).fill(element)
>>> repeatElement('#', 5).join('')
"#####"

Or for a curry-able version:

const repeatElement = element => count =>
    Array(count).fill(element)
>>> repeatElement('#')(5).join('')
"#####"

You can use this function with a list:

const repeatElement = (element, count) =>
    Array(count).fill(element)

>>> ['a', 'b', ...repeatElement('c', 5)]
['a', 'b', 'c', 'c', 'c', 'c', 'c']

How do I remove diacritics (accents) from a string in .NET?

I've not used this method, but Michael Kaplan describes a method for doing so in his blog post (with a confusing title) that talks about stripping diacritics: Stripping is an interesting job (aka On the meaning of meaningless, aka All Mn characters are non-spacing, but some are more non-spacing than others)

static string RemoveDiacritics(string text) 
{
    var normalizedString = text.Normalize(NormalizationForm.FormD);
    var stringBuilder = new StringBuilder();

    foreach (var c in normalizedString)
    {
        var unicodeCategory = CharUnicodeInfo.GetUnicodeCategory(c);
        if (unicodeCategory != UnicodeCategory.NonSpacingMark)
        {
            stringBuilder.Append(c);
        }
    }

    return stringBuilder.ToString().Normalize(NormalizationForm.FormC);
}

Note that this is a followup to his earlier post: Stripping diacritics....

The approach uses String.Normalize to split the input string into constituent glyphs (basically separating the "base" characters from the diacritics) and then scans the result and retains only the base characters. It's just a little complicated, but really you're looking at a complicated problem.

Of course, if you're limiting yourself to French, you could probably get away with the simple table-based approach in How to remove accents and tilde in a C++ std::string, as recommended by @David Dibben.

How to test valid UUID/GUID?

I think a better way is using the static method fromString to avoid those regular expressions.

    id = UUID.randomUUID();
    UUID uuid = UUID.fromString(id.toString());
    Assert.assertEquals(id.toString(), uuid.toString());

On the other hand

   UUID uuidFalse = UUID.fromString("x");

throws java.lang.IllegalArgumentException: Invalid UUID string: x

Powershell: convert string to number

Simply divide the Variable containing Numbers as a string by 1. PowerShell automatically convert the result to an integer.

$a = 15; $b = 2; $a + $b --> 152

But if you divide it before:

$a/1 + $b/1 --> 17

Passing data between different controller action methods

If you need to pass data from one controller to another you must pass data by route values.Because both are different request.if you send data from one page to another then you have to user query string(same as route values).

But you can do one trick :

In your calling action call the called action as a simple method :

public class ServerController : Controller
{
 [HttpPost]
 public ActionResult ApplicationPoolsUpdate(ServiceViewModel viewModel)
 {
      XDocument updatedResultsDocument = myService.UpdateApplicationPools();
      ApplicationPoolController pool=new ApplicationPoolController(); //make an object of ApplicationPoolController class.

      return pool.UpdateConfirmation(updatedResultsDocument); // call the ActionMethod you want as a simple method and pass the model as an argument.
      // Redirect to ApplicationPool controller and pass
      // updatedResultsDocument to be used in UpdateConfirmation action method
 }
}

Fixed point vs Floating point number

From my understanding, fixed-point arithmetic is done using integers. where the decimal part is stored in a fixed amount of bits, or the number is multiplied by how many digits of decimal precision is needed.

For example, If the number 12.34 needs to be stored and we only need two digits of precision after the decimal point, the number is multiplied by 100 to get 1234. When performing math on this number, we'd use this rule set. Adding 5620 or 56.20 to this number would yield 6854 in data or 68.54.

If we want to calculate the decimal part of a fixed-point number, we use the modulo (%) operand.

12.34 (pseudocode):

v1 = 1234 / 100 // get the whole number
v2 = 1234 % 100 // get the decimal number (100ths of a whole).
print v1 + "." + v2 // "12.34"

Floating point numbers are a completely different story in programming. The current standard for floating point numbers use something like 23 bits for the data of the number, 8 bits for the exponent, and 1 but for sign. See this Wikipedia link for more information on this.

How to recover deleted rows from SQL server table?

I think thats impossible, sorry.

Thats why whenever running a delete or update you should always use BEGIN TRANSACTION, then COMMIT if successful or ROLLBACK if not.

3-dimensional array in numpy

You have a truncated array representation. Let's look at a full example:

>>> a = np.zeros((2, 3, 4))
>>> a
array([[[ 0.,  0.,  0.,  0.],
        [ 0.,  0.,  0.,  0.],
        [ 0.,  0.,  0.,  0.]],

       [[ 0.,  0.,  0.,  0.],
        [ 0.,  0.,  0.,  0.],
        [ 0.,  0.,  0.,  0.]]])

Arrays in NumPy are printed as the word array followed by structure, similar to embedded Python lists. Let's create a similar list:

>>> l = [[[ 0.,  0.,  0.,  0.],
          [ 0.,  0.,  0.,  0.],
          [ 0.,  0.,  0.,  0.]],

          [[ 0.,  0.,  0.,  0.],
          [ 0.,  0.,  0.,  0.],
          [ 0.,  0.,  0.,  0.]]]

>>> l
[[[0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0]], 
 [[0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0]]]

The first level of this compound list l has exactly 2 elements, just as the first dimension of the array a (# of rows). Each of these elements is itself a list with 3 elements, which is equal to the second dimension of a (# of columns). Finally, the most nested lists have 4 elements each, same as the third dimension of a (depth/# of colors).

So you've got exactly the same structure (in terms of dimensions) as in Matlab, just printed in another way.

Some caveats:

  1. Matlab stores data column by column ("Fortran order"), while NumPy by default stores them row by row ("C order"). This doesn't affect indexing, but may affect performance. For example, in Matlab efficient loop will be over columns (e.g. for n = 1:10 a(:, n) end), while in NumPy it's preferable to iterate over rows (e.g. for n in range(10): a[n, :] -- note n in the first position, not the last).

  2. If you work with colored images in OpenCV, remember that:

    2.1. It stores images in BGR format and not RGB, like most Python libraries do.

    2.2. Most functions work on image coordinates (x, y), which are opposite to matrix coordinates (i, j).

Getting the first index of an object

I had the same problem yesterday. I solved it like this:

var obj = {
        foo:{},
        bar:{},
        baz:{}
    },
   first = null,
   key = null;
for (var key in obj) {
    first = obj[key];
    if(typeof(first) !== 'function') {
        break;
    }
}
// first is the first enumerated property, and key it's corresponding key.

Not the most elegant solution, and I am pretty sure that it may yield different results in different browsers (i.e. the specs says that enumeration is not required to enumerate the properties in the same order as they were defined). However, I only had a single property in my object so that was a non-issue. I just needed the first key.

How to disable Python warnings?

This is an old question but there is some newer guidance in PEP 565 that to turn off all warnings if you're writing a python application you should use:

import sys
import warnings

if not sys.warnoptions:
    warnings.simplefilter("ignore")

The reason this is recommended is that it turns off all warnings by default but crucially allows them to be switched back on via python -W on the command line or PYTHONWARNINGS.

Hibernate: How to fix "identifier of an instance altered from X to Y"?

I was facing this issue, too.

The target table is a relation table, wiring two IDs from different tables. I have a UNIQUE constraint on the value combination, replacing the PK. When updating one of the values of a tuple, this error occured.

This is how the table looks like (MySQL):

CREATE TABLE my_relation_table (
  mrt_left_id BIGINT NOT NULL,
  mrt_right_id BIGINT NOT NULL,
  UNIQUE KEY uix_my_relation_table (mrt_left_id, mrt_right_id),
  FOREIGN KEY (mrt_left_id)
    REFERENCES left_table(lef_id),
  FOREIGN KEY (mrt_right_id)
    REFERENCES right_table(rig_id)
);

The Entity class for the RelationWithUnique entity looks basically like this:

@Entity
@IdClass(RelationWithUnique.class)
@Table(name = "my_relation_table")
public class RelationWithUnique implements Serializable {

  ...

  @Id
  @ManyToOne
  @JoinColumn(name = "mrt_left_id", referencedColumnName = "left_table.lef_id")
  private LeftTableEntity leftId;

  @Id
  @ManyToOne
  @JoinColumn(name = "mrt_right_id", referencedColumnName = "right_table.rig_id")
  private RightTableEntity rightId;

  ...

I fixed it by

// usually, we need to detach the object as we are updating the PK
// (rightId being part of the UNIQUE constraint) => PK
// but this would produce a duplicate entry, 
// therefore, we simply delete the old tuple and add the new one
final RelationWithUnique newRelation = new RelationWithUnique();
newRelation.setLeftId(oldRelation.getLeftId());
newRelation.setRightId(rightId);  // here, the value is updated actually
entityManager.remove(oldRelation);
entityManager.persist(newRelation);

Thanks a lot for the hint of the PK, I just missed it.

What is the proper use of an EventEmitter?

Yes, go ahead and use it.

EventEmitter is a public, documented type in the final Angular Core API. Whether or not it is based on Observable is irrelevant; if its documented emit and subscribe methods suit what you need, then go ahead and use it.

As also stated in the docs:

Uses Rx.Observable but provides an adapter to make it work as specified here: https://github.com/jhusain/observable-spec

Once a reference implementation of the spec is available, switch to it.

So they wanted an Observable like object that behaved in a certain way, they implemented it, and made it public. If it were merely an internal Angular abstraction that shouldn't be used, they wouldn't have made it public.

There are plenty of times when it's useful to have an emitter which sends events of a specific type. If that's your use case, go for it. If/when a reference implementation of the spec they link to is available, it should be a drop-in replacement, just as with any other polyfill.

Just be sure that the generator you pass to the subscribe() function follows the linked spec. The returned object is guaranteed to have an unsubscribe method which should be called to free any references to the generator (this is currently an RxJs Subscription object but that is indeed an implementation detail which should not be depended on).

export class MyServiceEvent {
    message: string;
    eventId: number;
}

export class MyService {
    public onChange: EventEmitter<MyServiceEvent> = new EventEmitter<MyServiceEvent>();

    public doSomething(message: string) {
        // do something, then...
        this.onChange.emit({message: message, eventId: 42});
    }
}

export class MyConsumer {
    private _serviceSubscription;

    constructor(private service: MyService) {
        this._serviceSubscription = this.service.onChange.subscribe({
            next: (event: MyServiceEvent) => {
                console.log(`Received message #${event.eventId}: ${event.message}`);
            }
        })
    }

    public consume() {
        // do some stuff, then later...

        this.cleanup();
    }

    private cleanup() {
        this._serviceSubscription.unsubscribe();
    }
}

All of the strongly-worded doom and gloom predictions seem to stem from a single Stack Overflow comment from a single developer on a pre-release version of Angular 2.

When to use a View instead of a Table?

Views are acceptable when you need to ensure that complex logic is followed every time. For instance, we have a view that creates the raw data needed for all financial reporting. By having all reports use this view, everyone is working from the same data set, rather than one report using one set of joins and another forgetting to use one which gives different results.

Views are acceptable when you want to restrict users to a particular subset of data. For instance, if you do not delete records but only mark the current one as active and the older versions as inactive, you want a view to use to select only the active records. This prevents people from forgetting to put the where clause in the query and getting bad results.

Views can be used to ensure that users only have access to a set of records - for instance, a view of the tables for a particular client and no security rights on the tables can mean that the users for that client can only ever see the data for that client.

Views are very helpful when refactoring databases.

Views are not acceptable when you use views to call views which can result in horrible performance (at least in SQL Server). We almost lost a multimillion dollar client because someone chose to abstract the database that way and performance was horrendous and timeouts frequent. We had to pay for the fix too, not the client, as the performance issue was completely our fault. When views call views, they have to completely generate the underlying view. I have seen this where the view called a view which called a view and so many millions of records were generated in order to see the three the user ultimately needed. I remember one of these views took 8 minutes to do a simple count(*) of the records. Views calling views are an extremely poor idea.

Views are often a bad idea to use to update records as usually you can only update fields from the same table (again this is SQL Server, other databases may vary). If that's the case, it makes more sense to directly update the tables anyway so that you know which fields are available.

Jackson JSON custom serialization for certain fields

You can implement a custom serializer as follows:

public class Person {
    public String name;
    public int age;
    @JsonSerialize(using = IntToStringSerializer.class, as=String.class)
    public int favoriteNumber:
}


public class IntToStringSerializer extends JsonSerializer<Integer> {

    @Override
    public void serialize(Integer tmpInt, 
                          JsonGenerator jsonGenerator, 
                          SerializerProvider serializerProvider) 
                          throws IOException, JsonProcessingException {
        jsonGenerator.writeObject(tmpInt.toString());
    }
}

Java should handle the autoboxing from int to Integer for you.

what does mysql_real_escape_string() really do?

Say you want to save the string I'm a "foobar" in the database.
Your query will look something like INSERT INTO foos (text) VALUES ("$text").
With the $text variable replaced, this will look like this:

INSERT INTO foos (text) VALUES ("I'm a "foobar"")

Now, where exactly does the string end? You may know, an SQL parser doesn't. Not only will this simply break this query, it can also be abused to inject SQL commands you didn't intend.

mysql_real_escape_string makes sure such ambiguities do not occur by escaping characters which have special meaning to an SQL parser:

mysql_real_escape_string($text)  =>  I\'m a \"foobar\"

This becomes:

INSERT INTO foos (text) VALUES ("I\'m a \"foobar\"")

This makes the statement unambiguous and safe. The \ signals that the following character is not to be taken by its special meaning as string terminator. There are a few such characters that mysql_real_escape_string takes care of.

Escaping is a pretty universal thing in programming languages BTW, all along the same lines. If you want to type the above sentence literally in PHP, you need to escape it as well for the same reasons:

$text = 'I\'m a "foobar"';
// or
$text = "I'm a \"foobar\"";

2 column div layout: right column with fixed width, left fluid

Hey, What you can do is apply a fixed width to both the containers and then use another div class where clear:both, like

div#left {

width: 600px;
float: left;
}

div#right {

width: 240px;
float: right;

}

div.clear {

clear:both;

}

place a the clear div under left and right container.

jQuery jump or scroll to certain position, div or target on the page from button onclick

I would style a link to look like a button, because that way there is a no-js fallback.


So this is how you could animate the jump using jquery. No-js fallback is a normal jump without animation.

Original example:

jsfiddle

_x000D_
_x000D_
$(document).ready(function() {_x000D_
  $(".jumper").on("click", function( e ) {_x000D_
_x000D_
    e.preventDefault();_x000D_
_x000D_
    $("body, html").animate({ _x000D_
      scrollTop: $( $(this).attr('href') ).offset().top _x000D_
    }, 600);_x000D_
_x000D_
  });_x000D_
});
_x000D_
#long {_x000D_
  height: 500px;_x000D_
  background-color: blue;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<!-- Links that trigger the jumping -->_x000D_
<a class="jumper" href="#pliip">Pliip</a>_x000D_
<a class="jumper" href="#ploop">Ploop</a>_x000D_
<div id="long">...</div>_x000D_
<!-- Landing elements -->_x000D_
<div id="pliip">pliip</div>_x000D_
<div id="ploop">ploop</div>
_x000D_
_x000D_
_x000D_


New example with actual button styles for the links, just to prove a point.

Everything is essentially the same, except that I changed the class .jumper to .button and I added css styling to make the links look like buttons.

Button styles example

regex pattern to match the end of a string

Use the $ metacharacter to match the end of a string.

In Perl, this looks like:

my $str = 'red/white/blue';
my($last_match) = $str =~ m/.*\/(.*)$/;

Written in JavaScript, this looks like:

var str = 'red/white/blue'.match(/.*\/(.*)$/);

SQL Server Management Studio, how to get execution time down to milliseconds

Turn on Client Statistics by doing one of the following:

  • Menu: Query > Include client Statistics
  • Toolbar: Click the button (next to Include Actual Execution Time)
  • Keyboard: Shift-Alt-S

Then you get a new tab which records the timings, IO data and rowcounts etc for (up to) the last 10 exections (plus averages!):

enter image description here

standard_init_linux.go:190: exec user process caused "no such file or directory" - Docker

Suppose you face this issue while running your go binary with in alpine container. Export the following variable before building your bin

# CGO has to be disabled for alpine
export CGO_ENABLED=0

Then go build

Change New Google Recaptcha (v2) Width

A bit late but I've got an easy workaround:

Just add this code to your "g-recaptcha" class:

width: desired_width;

border-radius: 4px;
border-right: 1px solid #d8d8d8;
overflow: hidden;

How to JSON serialize sets?

Only dictionaries, Lists and primitive object types (int, string, bool) are available in JSON.

get jquery `$(this)` id

Do you mean that for a select element with an id of "next" you need to perform some specific script?

$("#next").change(function(){
    //enter code here
});

jQuery ajax error function

From jquery.com:

The jqXHR.success(), jqXHR.error(), and jqXHR.complete()
callback methods introduced injQuery 1.5 are deprecated
as of jQuery 1.8. To prepare your code for their eventual 
removal, use jqXHR.done(), jqXHR.fail(), and jqXHR.always() instead.

If you want global handlers you can use:

.ajaxStart(), .ajaxStop(),
.ajaxComplete(), .ajaxError(),
.ajaxSuccess(), .ajaxSend()

Why does an image captured using camera intent gets rotated on some devices on Android?

this worked for me

ImageView display_image = findViewById(R.id.image);
this.display_image.setRotation(90);

Database design for a survey

Given the proper index your second solution is normalized and good for a traditional relational database system.

I don't know how huge is huge but it should hold without problem a couple million answers.

OpenCV TypeError: Expected cv::UMat for argument 'src' - What is this?

Is canny your own function? Do you use Canny from OpenCV inside it? If yes check if you feed suitable argument for Canny - first Canny argument should meet following criteria:

  • type: <type 'numpy.ndarray'>
  • dtype: dtype('uint8')
  • being single channel or simplyfing: grayscale, that is 2D array, i.e. its shape should be 2-tuple of ints (tuple containing exactly 2 integers)

You can check it by printing respectively

type(variable_name)
variable_name.dtype
variable_name.shape

Replace variable_name with name of variable you feed as first argument to Canny.

When is std::weak_ptr useful?

I see a lot of interesting answers that explain reference counting etc., but I am missing a simple example that demonstrates how you prevent memory leak using weak_ptr. In first example I use shared_ptr in cyclically referenced classes. When the classes go out of scope they are NOT destroyed.

#include<iostream>
#include<memory>
using namespace std;

class B;

class A
{
public:
    shared_ptr<B>bptr;
    A() {
        cout << "A created" << endl;
    }
    ~A() {
        cout << "A destroyed" << endl;
    }
};

class B
{
public:
    shared_ptr<A>aptr;
    B() {
        cout << "B created" << endl;
    }
    ~B() {
        cout << "B destroyed" << endl;
    }
};

int main()
{
    {
        shared_ptr<A> a = make_shared<A>();
        shared_ptr<B> b = make_shared<B>();
        a->bptr = b;
        b->aptr = a;
    }
  // put breakpoint here
}

If you run the code snippet you will see as classes are created, but not destroyed:

A created
B created

Now we change shared_ptr's to weak_ptr:

class B;
class A
{
public:
    weak_ptr<B>bptr;

    A() {
        cout << "A created" << endl;
    }
    ~A() {
        cout << "A destroyed" << endl;
    }
};

class B
{
public:
    weak_ptr<A>aptr;

    B() {
        cout << "B created" << endl;
    }
    ~B() {
        cout << "B destroyed" << endl;
    }
};

    int main()
    {
        {
            shared_ptr<A> a = make_shared<A>();
            shared_ptr<B> b = make_shared<B>();
            a->bptr = b;
            b->aptr = a;
        }
      // put breakpoint here
    }

This time, when using weak_ptr we see proper class destruction:

A created
B created
B destroyed
A destroyed

Float and double datatype in Java

In regular programming calculations, we don’t use float. If we ensure that the result range is within the range of float data type then we can choose a float data type for saving memory. Generally, we use double because of two reasons:-

  • If we want to use the floating-point number as float data type then method caller must explicitly suffix F or f, because by default every floating-point number is treated as double. It increases the burden to the programmer. If we use a floating-point number as double data type then we don’t need to add any suffix.
  • Float is a single-precision data type means it occupies 4 bytes. Hence in large computations, we will not get a complete result. If we choose double data type, it occupies 8 bytes and we will get complete results.

Both float and double data types were designed especially for scientific calculations, where approximation errors are acceptable. If accuracy is the most prior concern then, it is recommended to use BigDecimal class instead of float or double data types. Source:- Float and double datatypes in Java

can you host a private repository for your organization to use with npm?

Verdaccio is what I was looking for and it deserves it's own answer ;) It is an actively maintained fork of Sinopia (highly upvoted answer here). It is a npm registry as a npm package, and can be found

here: https://github.com/verdaccio/verdaccio,
here: https://www.verdaccio.org,
and on port number: 4873

Run using PM2

npm i -g verdaccio pm2
pm2 start --name verdaccio `which verdaccio`
pm2 save

Run using docker

docker run -it --rm --detach --name verdaccio -p 4873:4873 verdaccio/verdaccio

Run using Helm

helm repo add verdaccio https://charts.verdaccio.org
helm repo update
helm install verdaccio/verdaccio

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

CultureInfo us = new CultureInfo("en-US");
TotalAmount.ToString("N", us)

Is string in array?

Arrays are, in general, a poor data structure to use if you want to ask if a particular object is in the collection or not.

If you'll be running this search frequently, it might be worth it to use a Dictionary<string, something> rather than an array. Lookups in a Dictionary are O(1) (constant-time), while searching through the array is O(N) (takes time proportional to the length of the array).

Even if the array is only 200 items at most, if you do a lot of these searches, the Dictionary will likely be faster.

Is it possible to have multiple styles inside a TextView?

If you don't feel like using html, you could just create a styles.xml and use it like this:

TextView tv = (TextView) findViewById(R.id.textview);
SpannableString text = new SpannableString(myString);

text.setSpan(new TextAppearanceSpan(getContext(), R.style.myStyle), 0, 5, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
text.setSpan(new TextAppearanceSpan(getContext(), R.style.myNextStyle), 6, 10, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

tv.setText(text, TextView.BufferType.SPANNABLE);

Negation in Python

Python prefers English keywords to punctuation. Use not x, i.e. not os.path.exists(...). The same thing goes for && and || which are and and or in Python.

How many characters can you store with 1 byte?

2^8 = 256 Characters. A character in binary is a series of 8 ( 0 or 1).

   |----------------------------------------------------------|
   |                                                          |
   | Type    | Storage |  Minimum Value    | Maximum Value    |
   |         | (Bytes) | (Signed/Unsigned) | (Signed/Unsigned)|
   |         |         |                   |                  |
   |---------|---------|-------------------|------------------|
   |         |         |                   |                  |
   |         |         |                   |                  |
   | TINYINT |  1      |      -128 - 0     |  127 - 255       |
   |         |         |                   |                  |
   |----------------------------------------------------------|

Forbidden: You don't have permission to access / on this server, WAMP Error

Adding Allow from All didn't worked for me. Then I tried this and it worked.

OS: Windows 8.1
Wamp : 2.5

I added this in the file C:\wamp\bin\apache\apache2.4.9\conf\extra\httpd-vhosts.conf

<VirtualHost *:80>
    ServerAdmin [email protected]
    DocumentRoot "c:/wamp/www/"
    ServerName localhost
    ServerAlias localhost
    ErrorLog "logs/localhost-error.log"
    CustomLog "logs/localhost-access.log" common
</VirtualHost>

Is it possible to disable floating headers in UITableView with UITableViewStylePlain?

**Swift 5.3 | Programmatically **

private func buildTableView() -> UITableView {
    let tableView = UITableView()
    tableView.translatesAutoresizingMaskIntoConstraints = false
    tableView.rowHeight = UITableView.automaticDimension
    tableView.showsVerticalScrollIndicator = false
    tableView.separatorStyle = .none
    let dummyViewHeight: CGFloat = 80
    tableView.tableFooterView = UIView(
        frame: CGRect(x: .zero,
                      y: .zero,
                      width: tableView.bounds.size.width,
                      height: dummyViewHeight))

    tableView.contentInset = UIEdgeInsets(top: .zero, left: .zero, bottom: -dummyViewHeight, right: .zero)
    return tableView
}

What is the difference between a static method and a non-static method?

Static methods are useful if you have only one instance (situation, circumstance) where you're going to use the method, and you don't need multiple copies (objects). For example, if you're writing a method that logs onto one and only one web site, downloads the weather data, and then returns the values, you could write it as static because you can hard code all the necessary data within the method and you're not going to have multiple instances or copies. You can then access the method statically using one of the following:

MyClass.myMethod();
this.myMethod();
myMethod();

Non-static methods are used if you're going to use your method to create multiple copies. For example, if you want to download the weather data from Boston, Miami, and Los Angeles, and if you can do so from within your method without having to individually customize the code for each separate location, you then access the method non-statically:

MyClass boston = new MyClassConstructor(); 
boston.myMethod("bostonURL");

MyClass miami = new MyClassConstructor(); 
miami.myMethod("miamiURL");

MyClass losAngeles = new MyClassConstructor();
losAngeles.myMethod("losAngelesURL");

In the above example, Java creates three separate objects and memory locations from the same method that you can individually access with the "boston", "miami", or "losAngeles" reference. You can't access any of the above statically, because MyClass.myMethod(); is a generic reference to the method, not to the individual objects that the non-static reference created.

If you run into a situation where the way you access each location, or the way the data is returned, is sufficiently different that you can't write a "one size fits all" method without jumping through a lot of hoops, you can better accomplish your goal by writing three separate static methods, one for each location.

What does "exited with code 9009" mean during this build?

Error Code 9009 means error file not found. All the underlying reasons posted in the answers here are good inspiration to figure out why, but the error itself simply means a bad path.

Check if textbox has empty value

The check can be done like this:

if (!!inp.val()) {

}

and even shorter:

if (inp.val()) {

}

c# open a new form then close the current form?

You weren't specific, but it looks like you were trying to do what I do in my Win Forms apps: start with a Login form, then after successful login, close that form and put focus on a Main form. Here's how I do it:

  1. make frmMain the startup form; this is what my Program.cs looks like:

    [STAThread]
    static void Main()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.Run(new frmMain());
    }
    
  2. in my frmLogin, create a public property that gets initialized to false and set to true only if a successful login occurs:

    public bool IsLoggedIn { get; set; }
    
  3. my frmMain looks like this:

    private void frmMain_Load(object sender, EventArgs e)
    {
        frmLogin frm = new frmLogin();
        frm.IsLoggedIn = false;
        frm.ShowDialog();
    
        if (!frm.IsLoggedIn)
        {
            this.Close();
            Application.Exit();
            return;
        }
    

No successful login? Exit the application. Otherwise, carry on with frmMain. Since it's the startup form, when it closes, the application ends.

Plotting two variables as lines using ggplot2 on the same graph

For a small number of variables, you can build the plot manually yourself:

ggplot(test_data, aes(date)) + 
  geom_line(aes(y = var0, colour = "var0")) + 
  geom_line(aes(y = var1, colour = "var1"))

How to set caret(cursor) position in contenteditable element (div)?

I think it's not simple to set caret to some position in contenteditable element. I wrote my own code for this. It bypasses the node tree calcing how many characters left and sets caret in needed element. I didn't test this code much.

//Set offset in current contenteditable field (for start by default or for with forEnd=true)
function setCurSelectionOffset(offset, forEnd = false) {
    const sel = window.getSelection();
    if (sel.rangeCount !== 1 || !document.activeElement) return;

    const firstRange = sel.getRangeAt(0);

    if (offset > 0) {
        bypassChildNodes(document.activeElement, offset);
    }else{
        if (forEnd)
            firstRange.setEnd(document.activeElement, 0);
        else
            firstRange.setStart(document.activeElement, 0);
    }



    //Bypass in depth
    function bypassChildNodes(el, leftOffset) {
        const childNodes = el.childNodes;

        for (let i = 0; i < childNodes.length && leftOffset; i++) {
            const childNode = childNodes[i];

            if (childNode.nodeType === 3) {
                const curLen = childNode.textContent.length;

                if (curLen >= leftOffset) {
                    if (forEnd)
                        firstRange.setEnd(childNode, leftOffset);
                    else
                        firstRange.setStart(childNode, leftOffset);
                    return 0;
                }else{
                    leftOffset -= curLen;
                }
            }else
            if (childNode.nodeType === 1) {
                leftOffset = bypassChildNodes(childNode, leftOffset);
            }
        }

        return leftOffset;
    }
}

I also wrote code to get current caret position (didn't test):

//Get offset in current contenteditable field (start offset by default or end offset with calcEnd=true)
function getCurSelectionOffset(calcEnd = false) {
    const sel = window.getSelection();
    if (sel.rangeCount !== 1 || !document.activeElement) return 0;

    const firstRange     = sel.getRangeAt(0),
          startContainer = calcEnd ? firstRange.endContainer : firstRange.startContainer,
          startOffset    = calcEnd ? firstRange.endOffset    : firstRange.startOffset;
    let needStop = false;

    return bypassChildNodes(document.activeElement);



    //Bypass in depth
    function bypassChildNodes(el) {
        const childNodes = el.childNodes;
        let ans = 0;

        if (el === startContainer) {
            if (startContainer.nodeType === 3) {
                ans = startOffset;
            }else
            if (startContainer.nodeType === 1) {
                for (let i = 0; i < startOffset; i++) {
                    const childNode = childNodes[i];

                    ans += childNode.nodeType === 3 ? childNode.textContent.length :
                           childNode.nodeType === 1 ? childNode.innerText.length :
                           0;
                }
            }

            needStop = true;
        }else{
            for (let i = 0; i < childNodes.length && !needStop; i++) {
                const childNode = childNodes[i];
                ans += bypassChildNodes(childNode);
            }
        }

        return ans;
    }
}

You also need to be aware of range.startOffset and range.endOffset contain character offset for text nodes (nodeType === 3) and child node offset for element nodes (nodeType === 1). range.startContainer and range.endContainer may refer to any element node of any level in the tree (of course they also can refer to text nodes).

Convert an image (selected by path) to base64 string

Since most of us like oneliners:

Convert.ToBase64String(File.ReadAllBytes(imageFilepath));

If you need it as Base64 byte array:

Encoding.ASCII.GetBytes(Convert.ToBase64String(File.ReadAllBytes(imageFilepath)));

How to get an absolute file path in Python

Update for Python 3.4+ pathlib that actually answers the question:

from pathlib import Path

relative = Path("mydir/myfile.txt")
absolute = relative.absolute()  # absolute is a Path object

If you only need a temporary string, keep in mind that you can use Path objects with all the relevant functions in os.path, including of course abspath:

from os.path import abspath

absolute = abspath(relative)  # absolute is a str object

inline if statement java, why is not working

Syntax is Shown below:

"your condition"? "step if true":"step if condition fails"

Suppress/ print without b' prefix for bytes in Python 3

I am a little late but for Python 3.9.1 this worked for me and removed the -b prefix:

print(outputCode.decode())

Slicing of a NumPy 2d array, or how do I extract an mxm submatrix from an nxn array (n>m)?

If you want to skip every other row and every other column, then you can do it with basic slicing:

In [49]: x=np.arange(16).reshape((4,4))
In [50]: x[1:4:2,1:4:2]
Out[50]: 
array([[ 5,  7],
       [13, 15]])

This returns a view, not a copy of your array.

In [51]: y=x[1:4:2,1:4:2]

In [52]: y[0,0]=100

In [53]: x   # <---- Notice x[1,1] has changed
Out[53]: 
array([[  0,   1,   2,   3],
       [  4, 100,   6,   7],
       [  8,   9,  10,  11],
       [ 12,  13,  14,  15]])

while z=x[(1,3),:][:,(1,3)] uses advanced indexing and thus returns a copy:

In [58]: x=np.arange(16).reshape((4,4))
In [59]: z=x[(1,3),:][:,(1,3)]

In [60]: z
Out[60]: 
array([[ 5,  7],
       [13, 15]])

In [61]: z[0,0]=0

Note that x is unchanged:

In [62]: x
Out[62]: 
array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11],
       [12, 13, 14, 15]])

If you wish to select arbitrary rows and columns, then you can't use basic slicing. You'll have to use advanced indexing, using something like x[rows,:][:,columns], where rows and columns are sequences. This of course is going to give you a copy, not a view, of your original array. This is as one should expect, since a numpy array uses contiguous memory (with constant strides), and there would be no way to generate a view with arbitrary rows and columns (since that would require non-constant strides).

Pointers in Python?

>> id(1)
1923344848  # identity of the location in memory where 1 is stored
>> id(1)
1923344848  # always the same
>> a = 1
>> b = a  # or equivalently b = 1, because 1 is immutable
>> id(a)
1923344848
>> id(b)  # equal to id(a)
1923344848

As you can see a and b are just two different names that reference to the same immutable object (int) 1. If later you write a = 2, you reassign the name a to a different object (int) 2, but the b continues referencing to 1:

>> id(2)
1923344880
>> a = 2
>> id(a)
1923344880  # equal to id(2)
>> b
1           # b hasn't changed
>> id(b)
1923344848  # equal to id(1)

What would happen if you had a mutable object instead, such as a list [1]?

>> id([1])
328817608
>> id([1])
328664968  # different from the previous id, because each time a new list is created
>> a = [1]
>> id(a)
328817800
>> id(a)
328817800 # now same as before
>> b = a
>> id(b)
328817800  # same as id(a)

Again, we are referencing to the same object (list) [1] by two different names a and b. However now we can mutate this list while it remains the same object, and a, b will both continue referencing to it

>> a[0] = 2
>> a
[2]
>> b
[2]
>> id(a)
328817800  # same as before
>> id(b)
328817800  # same as before

Private pages for a private Github repo

This GitHub app: https://github.com/apps/priv-page allows users to have private pages for their private repositories.

When to use malloc for char pointers

Use malloc() when you don't know the amount of memory needed during compile time. In case if you have read-only strings then you can use const char* str = "something"; . Note that the string is most probably be stored in a read-only memory location and you'll not be able to modify it. On the other hand if you know the string during compiler time then you can do something like: char str[10]; strcpy(str, "Something"); Here the memory is allocated from stack and you will be able to modify the str. Third case is allocating using malloc. Lets say you don'r know the length of the string during compile time. Then you can do char* str = malloc(requiredMem); strcpy(str, "Something"); free(str);

dereferencing pointer to incomplete type

I saw a question the other day where someone inadvertently used an incomplete type by specifying something like

struct a {
    int q; 
}; 
struct A *x; 
x->q = 3;

The compiler knew that struct A was a struct, despite A being totally undefined, by virtue of the struct keyword.

That was in C++, where such usage of struct is atypical (and, it turns out, can lead to foot-shooting). In C if you do

typedef struct a {
    ...
} a;

then you can use a as the typename and omit the struct later. This will lead the compiler to give you an undefined identifier error later, rather than incomplete type, if you mistype the name or forget a header.

How to generate the JPA entity Metamodel?

Please take a look at jpa-metamodels-with-maven-example.

Hibernate

  • We need org.hibernate.org:hibernate-jpamodelgen.
  • The processor class is org.hibernate.jpamodelgen.JPAMetaModelEntityProcessor.

Hibernate as a dependency

    <dependency>
      <groupId>org.hibernate.orm</groupId>
      <artifactId>hibernate-jpamodelgen</artifactId>
      <version>${version.hibernate-jpamodelgen}</version>
      <scope>provided</scope>
    </dependency>

Hibernate as a processor

      <plugin>
        <groupId>org.bsc.maven</groupId>
        <artifactId>maven-processor-plugin</artifactId>
        <executions>
          <execution>
            <goals>
              <goal>process</goal>
            </goals>
            <phase>generate-sources</phase>
            <configuration>
              <compilerArguments>-AaddGeneratedAnnotation=false</compilerArguments> <!-- suppress java.annotation -->
              <processors>
                <processor>org.hibernate.jpamodelgen.JPAMetaModelEntityProcessor</processor>
              </processors>
            </configuration>
          </execution>
        </executions>
        <dependencies>
          <dependency>
            <groupId>org.hibernate.orm</groupId>
            <artifactId>hibernate-jpamodelgen</artifactId>
            <version>${version.hibernate-jpamodelgen}</version>
          </dependency>
        </dependencies>
      </plugin>

OpenJPA

  • We need org.apache.openjpa:openjpa.
  • The processor class is org.apache.openjpa.persistence.meta.AnnotationProcessor6.
  • OpenJPA seems require additional element <openjpa.metamodel>true<openjpa.metamodel>.

OpenJPA as a dependency

  <dependencies>
    <dependency>
      <groupId>org.apache.openjpa</groupId>
      <artifactId>openjpa</artifactId>
      <scope>provided</scope>
    </dependency>
  </dependencies>
  <build>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <configuration>
          <compilerArgs>
            <arg>-Aopenjpa.metamodel=true</arg>
          </compilerArgs>
        </configuration>
      </plugin>
    </plugins>
  </build>

OpenJPA as a processor

      <plugin>
        <groupId>org.bsc.maven</groupId>
        <artifactId>maven-processor-plugin</artifactId>
        <executions>
          <execution>
            <id>process</id>
            <goals>
              <goal>process</goal>
            </goals>
            <phase>generate-sources</phase>
            <configuration>
              <processors>
                <processor>org.apache.openjpa.persistence.meta.AnnotationProcessor6</processor>
              </processors>
              <optionMap>
                <openjpa.metamodel>true</openjpa.metamodel>
              </optionMap>
            </configuration>
          </execution>
        </executions>
        <dependencies>
          <dependency>
            <groupId>org.apache.openjpa</groupId>
            <artifactId>openjpa</artifactId>
            <version>${version.openjpa}</version>
          </dependency>
        </dependencies>
      </plugin>

EclipseLink

  • We need org.eclipse.persistence:org.eclipse.persistence.jpa.modelgen.processor.
  • The processor class is org.eclipse.persistence.internal.jpa.modelgen.CanonicalModelProcessor.
  • EclipseLink requires persistence.xml.

EclipseLink as a dependency

  <dependencies>
    <dependency>
      <groupId>org.eclipse.persistence</groupId>
      <artifactId>org.eclipse.persistence.jpa.modelgen.processor</artifactId>
      <scope>provided</scope>
    </dependency>

EclipseLink as a processor

    <plugins>
      <plugin>
        <groupId>org.bsc.maven</groupId>
        <artifactId>maven-processor-plugin</artifactId>
        <executions>
          <execution>
            <goals>
              <goal>process</goal>
            </goals>
            <phase>generate-sources</phase>
            <configuration>
              <processors>
                <processor>org.eclipse.persistence.internal.jpa.modelgen.CanonicalModelProcessor</processor>
              </processors>
              <compilerArguments>-Aeclipselink.persistencexml=src/main/resources-${environment.id}/META-INF/persistence.xml</compilerArguments>
            </configuration>
          </execution>
        </executions>
        <dependencies>
          <dependency>
            <groupId>org.eclipse.persistence</groupId>
            <artifactId>org.eclipse.persistence.jpa.modelgen.processor</artifactId>
            <version>${version.eclipselink}</version>
          </dependency>
        </dependencies>
      </plugin>

DataNucleus

  • We need org.datanucleus:datanucleus-jpa-query.
  • The processor class is org.datanucleus.jpa.query.JPACriteriaProcessor.

DataNucleus as a dependency

  <dependencies>
    <dependency>
      <groupId>org.datanucleus</groupId>
      <artifactId>datanucleus-jpa-query</artifactId>
      <scope>provided</scope>
    </dependency>
  </dependencies>

DataNucleus as a processor

      <plugin>
        <groupId>org.bsc.maven</groupId>
        <artifactId>maven-processor-plugin</artifactId>
        <executions>
          <execution>
            <id>process</id>
            <goals>
              <goal>process</goal>
            </goals>
            <phase>generate-sources</phase>
            <configuration>
              <processors>
                <processor>org.datanucleus.jpa.query.JPACriteriaProcessor</processor>
              </processors>
            </configuration>
          </execution>
        </executions>
        <dependencies>
          <dependency>
            <groupId>org.datanucleus</groupId>
            <artifactId>datanucleus-jpa-query</artifactId>
            <version>${version.datanucleus}</version>
          </dependency>
        </dependencies>
      </plugin>

Install specific branch from github using Npm

Another approach would be to add the following line to package.json dependencies:

"package-name": "user/repo#branch"

For example:

"dependencies": {
    ... other dependencies ...

    "react-native": "facebook/react-native#master"
}

And then do npm install or yarn install

<input type="file"> limit selectable files by extensions

NOTE: This answer is from 2011. It was a really good answer back then, but as of 2015, native HTML properties are supported by most browsers, so there's (usually) no need to implement such custom logic in JS. See Edi's answer and the docs.


Before the file is uploaded, you can check the file's extension using Javascript, and prevent the form being submitted if it doesn't match. The name of the file to be uploaded is stored in the "value" field of the form element.

Here's a simple example that only allows files that end in ".gif" to be uploaded:

<script type="text/javascript">
    function checkFile() {
        var fileElement = document.getElementById("uploadFile");
        var fileExtension = "";
        if (fileElement.value.lastIndexOf(".") > 0) {
            fileExtension = fileElement.value.substring(fileElement.value.lastIndexOf(".") + 1, fileElement.value.length);
        }
        if (fileExtension.toLowerCase() == "gif") {
            return true;
        }
        else {
            alert("You must select a GIF file for upload");
            return false;
        }
    }
</script>

<form action="upload.aspx" enctype="multipart/form-data" onsubmit="return checkFile();">
    <input name="uploadFile" id="uploadFile" type="file" />

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

However, this method is not foolproof. Sean Haddy is correct that you always want to check on the server side, because users can defeat your Javascript checking by turning off javascript, or editing your code after it arrives in their browser. Definitely check server-side in addition to the client-side check. Also I recommend checking for size server-side too, so that users don't crash your server with a 2 GB file (there's no way that I know of to check file size on the client side without using Flash or a Java applet or something).

However, checking client side before hand using the method I've given here is still useful, because it can prevent mistakes and is a minor deterrent to non-serious mischief.

Insert line break inside placeholder attribute of a textarea?

Based on a combination of three different tricks I saw this seems to work in all browsers I've tested it in.

HTML:

<textarea placeholder="Line One&#10;Line Two&#10;&#10;Line Four"></textarea>

JS At bottom of HTML file:

<script>
    
    var textAreas = document.getElementsByTagName('textarea');

    Array.prototype.forEach.call(textAreas, function(elem) {
        elem.placeholder = elem.placeholder.replace(/\u000A/g, 
        '                                                     \
                                                              \
                                                              \
        \n\u2063');
    });

</script>

Note, the extra spaces will cause a clean wrap around but there has to be enough spaces that it will fill the width of the textarea, I placed enough that it's sufficient for my projects but you could be robust and generate them by observing the textarea.width and calculating the proper cardinality.

What are callee and caller saved registers?

Callee vs caller saved is a convention for who is responsible for saving and restoring the value in a register across a call. ALL registers are "global" in that any code anywhere can see (or modify) a register and those modifications will be seen by any later code anywhere. The point of register saving conventions is that code is not supposed to modify certain registers, as other code assumes that the value is not modified.

In your example code, NONE of the registers are callee save, as it makes no attempt to save or restore the register values. However, it would seem to not be an entire procedure, as it contains a branch to an undefined label (l$loop). So it might be a fragment of code from the middle of a procedure that treats some registers as callee save; you're just missing the save/restore instructions.

How can I hide the Adobe Reader toolbar when displaying a PDF in the .NET WebBrowser control?

It appears the default setting for Adobe Reader X is for the toolbars not to be shown by default unless they are explicitly turned on by the user. And even when I turn them back on during a session, they don't show up automatically next time. As such, I suspect you have a preference set contrary to the default.

The state you desire, with the top and left toolbars not shown, is called "Read Mode". If you right-click on the document itself, and then click "Page Display Preferences" in the context menu that is shown, you'll be presented with the Adobe Reader Preferences dialog. (This is the same dialog you can access by opening the Adobe Reader application, and selecting "Preferences" from the "Edit" menu.) In the list shown in the left-hand column of the Preferences dialog, select "Internet". Finally, on the right, ensure that you have the "Display in Read Mode by default" box checked:

   Adobe Reader Preferences dialog

You can also turn off the toolbars temporarily by clicking the button at the right of the top toolbar that depicts arrows pointing to opposing corners:

   Adobe Reader Read Mode toolbar button

Finally, if you have "Display in Read Mode by default" turned off, but want to instruct the page you're loading not to display the toolbars (i.e., override the user's current preferences), you can append the following to the URL:

#toolbar=0&navpanes=0

So, for example, the following code will disable both the top toolbar (called "toolbar") and the left-hand toolbar (called "navpane"). However, if the user knows the keyboard combination (F8, and perhaps other methods as well), they will still be able to turn them back on.

string url = @"http://www.domain.com/file.pdf#toolbar=0&navpanes=0";
this._WebBrowser.Navigate(url);

You can read more about the parameters that are available for customizing the way PDF files open here on Adobe's developer website.

Pass values of checkBox to controller action in asp.net mvc4

try using form collection

<input id="responsable" value="True" name="checkResp" type="checkbox" /> 

[HttpPost]
public ActionResult Index(FormCollection collection)
{
     if(!string.IsNullOrEmpty(collection["checkResp"])
     {
        string checkResp=collection["checkResp"];
        bool checkRespB=Convert.ToBoolean(checkResp);
     }

}

Cast a Double Variable to Decimal

You can cast a double to a decimal like this, without needing the M literal suffix:

double dbl = 1.2345D;
decimal dec = (decimal) dbl;

You should use the M when declaring a new literal decimal value:

decimal dec = 123.45M;

(Without the M, 123.45 is treated as a double and will not compile.)

Python - Locating the position of a regex match in a string?

I don't think this question has been completely answered yet because all of the answers only give single match examples. The OP's question demonstrates the nuances of having 2 matches as well as a substring match which should not be reported because it is not a word/token.

To match multiple occurrences, one might do something like this:

iter = re.finditer(r"\bis\b", String)
indices = [m.start(0) for m in iter]

This would return a list of the two indices for the original string.

How to import local packages in go?

If you are using Go 1.5 above, you can try to use vendoring feature. It allows you to put your local package under vendor folder and import it with shorter path. In your case, you can put your common and routers folder inside vendor folder so it would be like

myapp/
--vendor/
----common/
----routers/
------middleware/
--main.go

and import it like this

import (
    "common"
    "routers"
    "routers/middleware"
)

This will work because Go will try to lookup your package starting at your project’s vendor directory (if it has at least one .go file) instead of $GOPATH/src.

FYI: You can do more with vendor, because this feature allows you to put "all your dependency’s code" for a package inside your own project's directory so it will be able to always get the same dependencies versions for all builds. It's like npm or pip in python, but you need to manually copy your dependencies to you project, or if you want to make it easy, try to look govendor by Daniel Theophanes

For more learning about this feature, try to look up here

Understanding and Using Vendor Folder by Daniel Theophanes

Understanding Go Dependency Management by Lucas Fernandes da Costa

I hope you or someone else find it helpfully

Send Email Intent

Try:

intent.setType("message/rfc822");

Conversion failed when converting from a character string to uniqueidentifier - Two GUIDs

You have to check unique identifier column and you have to give a diff value to that particular field if you give the same value it will not work. It enforces uniqueness of the key.

Here is the code:

Insert into production.product 
(Name,ProductNumber,MakeFlag,FinishedGoodsFlag,Color,SafetyStockLevel,ReorderPoint,StandardCost,ListPrice,Size
,SizeUnitMeasureCode,WeightUnitMeasureCode,Weight,DaysToManufacture,
    ProductLine, 
    Class, 
    Style ,
    ProductSubcategoryID 
    ,ProductModelID 
    ,SellStartDate 
,SellEndDate 
    ,DiscontinuedDate 
    ,rowguid
    ,ModifiedDate 
  )
  values ('LL lemon' ,'BC-1234',0,0,'blue',400,960,0.00,100.00,Null,Null,Null,null,1,null,null,null,null,null,'1998-06-01 00:00:00.000',null,null,'C4244F0C-ABCE-451B-A895-83C0E6D1F468','2004-03-11 10:01:36.827')

how to pass value from one php page to another using session

Use something like this:

page1.php

<?php
session_start();
$_SESSION['myValue']=3; // You can set the value however you like.
?>

Any other PHP page:

<?php
session_start();
echo $_SESSION['myValue'];
?>

A few notes to keep in mind though: You need to call session_start() BEFORE any output, HTML, echos - even whitespace.

You can keep changing the value in the session - but it will only be able to be used after the first page - meaning if you set it in page 1, you will not be able to use it until you get to another page or refresh the page.

The setting of the variable itself can be done in one of a number of ways:

$_SESSION['myValue']=1;
$_SESSION['myValue']=$var;
$_SESSION['myValue']=$_GET['YourFormElement'];

And if you want to check if the variable is set before getting a potential error, use something like this:

if(!empty($_SESSION['myValue'])
{
    echo $_SESSION['myValue'];
}
else
{
    echo "Session not set yet.";
}

String index out of range: 4

You are using the wrong iteration counter, replace inp.charAt(i) with inp.charAt(j).

How can I create my own comparator for a map?

std::map takes up to four template type arguments, the third one being a comparator. E.g.:

struct cmpByStringLength {
    bool operator()(const std::string& a, const std::string& b) const {
        return a.length() < b.length();
    }
};

// ...
std::map<std::string, std::string, cmpByStringLength> myMap;

Alternatively you could also pass a comparator to maps constructor.

Note however that when comparing by length you can only have one string of each length in the map as a key.

Angularjs how to upload multipart form data and a file?

This is pretty must just a copy of that projects demo page and shows uploading a single file on form submit with upload progress.

(function (angular) {
'use strict';

angular.module('uploadModule', [])
    .controller('uploadCtrl', [
        '$scope',
        '$upload',
        function ($scope, $upload) {
            $scope.model = {};
            $scope.selectedFile = [];
            $scope.uploadProgress = 0;

            $scope.uploadFile = function () {
                var file = $scope.selectedFile[0];
                $scope.upload = $upload.upload({
                    url: 'api/upload',
                    method: 'POST',
                    data: angular.toJson($scope.model),
                    file: file
                }).progress(function (evt) {
                    $scope.uploadProgress = parseInt(100.0 * evt.loaded / evt.total, 10);
                }).success(function (data) {
                    //do something
                });
            };

            $scope.onFileSelect = function ($files) {
                $scope.uploadProgress = 0;
                $scope.selectedFile = $files;
            };
        }
    ])
    .directive('progressBar', [
        function () {
            return {
                link: function ($scope, el, attrs) {
                    $scope.$watch(attrs.progressBar, function (newValue) {
                        el.css('width', newValue.toString() + '%');
                    });
                }
            };
        }
    ]);
 }(angular));

HTML

<form ng-submit="uploadFile()">
   <div class="row">
         <div class="col-md-12">
                  <input type="text" ng-model="model.fileDescription" />
                  <input type="number" ng-model="model.rating" />
                  <input type="checkbox" ng-model="model.isAGoodFile" />
                  <input type="file" ng-file-select="onFileSelect($files)">
                  <div class="progress" style="margin-top: 20px;">
                    <div class="progress-bar" progress-bar="uploadProgress" role="progressbar">
                      <span ng-bind="uploadProgress"></span>
                      <span>%</span>
                    </div>
                  </div>

                  <button button type="submit" class="btn btn-default btn-lg">
                    <i class="fa fa-cloud-upload"></i>
                    &nbsp;
                    <span>Upload File</span>
                  </button>
                </div>
              </div>
            </form>

EDIT: Added passing a model up to the server in the file post.

The form data in the input elements would be sent in the data property of the post and be available as normal form values.

How to find NSDocumentDirectory in Swift?

Swift 3.0 and 4.0

Directly getting first element from an array will potentially cause exception if the path is not found. So calling first and then unwrap is the better solution

if let documentsPathString = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first {
    //This gives you the string formed path
}

if let documentsPathURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first {
    //This gives you the URL of the path
}

Could not find a base address that matches scheme https for the endpoint with binding WebHttpBinding. Registered base address schemes are [http]

You would need to enable https binding on server side. IISExpress in this case. Select Properties on website project in solution explorer (not double click). In the properties pane then you need to enable SSL.

Function is not defined - uncaught referenceerror

Your issue here is that you're not understanding the scope that you're setting.

You are passing the ready function a function itself. Within this function, you're creating another function called codeAddress. This one exists within the scope that created it and not within the window object (where everything and its uncle could call it).

For example:

var myfunction = function(){
    var myVar = 12345;
};

console.log(myVar); // 'undefined' - since it is within 
                    // the scope of the function only.

Have a look here for a bit more on anonymous functions: http://www.adequatelygood.com/2010/3/JavaScript-Module-Pattern-In-Depth

Another thing is that I notice you're using jQuery on that page. This makes setting click handlers much easier and you don't need to go into the hassle of setting the 'onclick' attribute in the HTML. You also don't need to make the codeAddress method available to all:

$(function(){
    $("#imgid").click(function(){
        var address = $("#formatedAddress").value;
        geocoder.geocode( { 'address': address}, function(results, status) {
           if (status == google.maps.GeocoderStatus.OK) {
             map.setCenter(results[0].geometry.location);
           }
        });
    });  
});

(You should remove the existing onclick and add an ID to the image element that you want to handle)

Note that I've replaced $(document).ready() with its shortcut of just $() (http://api.jquery.com/ready/). Then the click method is used to assign a click handler to the element. I've also replaced your document.getElementById with the jQuery object.

Maven command to determine which settings.xml file Maven is using

Your comment to cletus' (correct) answer implies that there are multiple Maven settings files involved.

Maven always uses either one or two settings files. The global settings defined in (${M2_HOME}/conf/settings.xml) is always required. The user settings file (defined in ${user.home}/.m2/settings.xml) is optional. Any settings defined in the user settings take precedence over the corresponding global settings.

You can override the location of the global and user settings from the command line, the following example will set the global settings to c:\global\settings.xml and the user settings to c:\user\settings.xml:

mvn install --settings c:\user\settings.xml 
    --global-settings c:\global\settings.xml

Currently there is no property or means to establish what user and global settings files were used from with Maven. To access these values, you would have to modify MavenCli and/or DefaultMavenSettingsBuilder to inject the file locations into the resolved Settings object.

What are the new features in C++17?

Language features:

Templates and Generic Code

Lambda

Attributes

Syntax cleanup

Cleaner multi-return and flow control

  • Structured bindings

    • Basically, first-class std::tie with auto
    • Example:
      • const auto [it, inserted] = map.insert( {"foo", bar} );
      • Creates variables it and inserted with deduced type from the pair that map::insert returns.
    • Works with tuple/pair-likes & std::arrays and relatively flat structs
    • Actually named structured bindings in standard
  • if (init; condition) and switch (init; condition)

    • if (const auto [it, inserted] = map.insert( {"foo", bar} ); inserted)
    • Extends the if(decl) to cases where decl isn't convertible-to-bool sensibly.
  • Generalizing range-based for loops

    • Appears to be mostly support for sentinels, or end iterators that are not the same type as begin iterators, which helps with null-terminated loops and the like.
  • if constexpr

    • Much requested feature to simplify almost-generic code.

Misc

Library additions:

Data types

Invoke stuff

File System TS v1

New algorithms

  • for_each_n

  • reduce

  • transform_reduce

  • exclusive_scan

  • inclusive_scan

  • transform_exclusive_scan

  • transform_inclusive_scan

  • Added for threading purposes, exposed even if you aren't using them threaded

Threading

(parts of) Library Fundamentals TS v1 not covered above or below

Container Improvements

Smart pointer changes

Other std datatype improvements:

Misc

Traits

Deprecated

Isocpp.org has has an independent list of changes since C++14; it has been partly pillaged.

Naturally TS work continues in parallel, so there are some TS that are not-quite-ripe that will have to wait for the next iteration. The target for the next iteration is C++20 as previously planned, not C++19 as some rumors implied. C++1O has been avoided.

Initial list taken from this reddit post and this reddit post, with links added via googling or from the above isocpp.org page.

Additional entries pillaged from SD-6 feature-test list.

clang's feature list and library feature list are next to be pillaged. This doesn't seem to be reliable, as it is C++1z, not C++17.

these slides had some features missing elsewhere.

While "what was removed" was not asked, here is a short list of a few things ((mostly?) previous deprecated) that are removed in C++17 from C++:

Removed:

There were rewordings. I am unsure if these have any impact on code, or if they are just cleanups in the standard:

Papers not yet integrated into above:

  • P0505R0 (constexpr chrono)

  • P0418R2 (atomic tweaks)

  • P0512R0 (template argument deduction tweaks)

  • P0490R0 (structured binding tweaks)

  • P0513R0 (changes to std::hash)

  • P0502R0 (parallel exceptions)

  • P0509R1 (updating restrictions on exception handling)

  • P0012R1 (make exception specifications be part of the type system)

  • P0510R0 (restrictions on variants)

  • P0504R0 (tags for optional/variant/any)

  • P0497R0 (shared ptr tweaks)

  • P0508R0 (structured bindings node handles)

  • P0521R0 (shared pointer use count and unique changes?)

Spec changes:

Further reference:

In c++ what does a tilde "~" before a function name signify?

It's the destructor. This method is called when the instance of your class is destroyed:

Stack<int> *stack= new Stack<int>;
//do something
delete stack; //<- destructor is called here;

Is it possible to pass a flag to Gulp to have it run tasks in different ways?

And if you are using typescript (gulpfile.ts) then do this for yargs (building on @Caio Cunha's excellent answer https://stackoverflow.com/a/23038290/1019307 and other comments above):

Install

npm install --save-dev yargs

typings install dt~yargs --global --save

.ts files

Add this to the .ts files:

import { argv } from 'yargs';

...

  let debug: boolean = argv.debug;

This has to be done in each .ts file individually (even the tools/tasks/project files that are imported into the gulpfile.ts/js).

Run

gulp build.dev --debug

Or under npm pass the arg through to gulp:

npm run build.dev -- --debug

Setting a property by reflection with a string value

You're probably looking for the Convert.ChangeType method. For example:

Ship ship = new Ship();
string value = "5.5";
PropertyInfo propertyInfo = ship.GetType().GetProperty("Latitude");
propertyInfo.SetValue(ship, Convert.ChangeType(value, propertyInfo.PropertyType), null);

Real-world examples of recursion

Phone and cable companies maintain a model of their wiring topology, which in effect is a large network or graph. Recursion is one way to traverse this model when you want to find all parent or all child elements.

Since recursion is expensive from a processing and memory perspective, this step is commonly only performed when the topology is changed and the result is stored in a modified pre-ordered list format.

How can I do DNS lookups in Python, including referring to /etc/hosts?

This code works well for returning all of the IP addresses that might belong to a particular URI. Since many systems are now in a hosted environment (AWS/Akamai/etc.), systems may return several IP addresses. The lambda was "borrowed" from @Peter Silva.

def get_ips_by_dns_lookup(target, port=None):
    '''
        this function takes the passed target and optional port and does a dns
        lookup. it returns the ips that it finds to the caller.

        :param target:  the URI that you'd like to get the ip address(es) for
        :type target:   string
        :param port:    which port do you want to do the lookup against?
        :type port:     integer
        :returns ips:   all of the discovered ips for the target
        :rtype ips:     list of strings

    '''
    import socket

    if not port:
        port = 443

    return list(map(lambda x: x[4][0], socket.getaddrinfo('{}.'.format(target),port,type=socket.SOCK_STREAM)))

ips = get_ips_by_dns_lookup(target='google.com')

Bootstrap Columns Not Working

Try this:

DEMO

<div class="container-fluid"> <!-- If Needed Left and Right Padding in 'md' and 'lg' screen means use container class -->
            <div class="row">
                <div class="col-xs-4 col-sm-4 col-md-4 col-lg-4">
                    <a href="#">About</a>
                </div>
                <div class="col-xs-4 col-sm-4 col-md-4 col-lg-4">
                    <img src="image.png" />
                </div>
                <div class="col-xs-4 col-sm-4 col-md-4 col-lg-4">
                    <a href="#myModal1" data-toggle="modal">SHARE</a>
                </div>
            </div>
        </div>

Find a value in DataTable

this question asked in 2009 but i want to share my codes:

    Public Function RowSearch(ByVal dttable As DataTable, ByVal searchcolumns As String()) As DataTable

    Dim x As Integer
    Dim y As Integer

    Dim bln As Boolean

    Dim dttable2 As New DataTable
    For x = 0 To dttable.Columns.Count - 1
        dttable2.Columns.Add(dttable.Columns(x).ColumnName)
    Next

    For x = 0 To dttable.Rows.Count - 1
        For y = 0 To searchcolumns.Length - 1
            If String.IsNullOrEmpty(searchcolumns(y)) = False Then
                If searchcolumns(y) = CStr(dttable.Rows(x)(y + 1) & "") & "" Then
                    bln = True
                Else
                    bln = False
                    Exit For
                End If
            End If
        Next
        If bln = True Then
            dttable2.Rows.Add(dttable.Rows(x).ItemArray)
        End If
    Next

    Return dttable2


End Function

What is a Data Transfer Object (DTO)?

With MVC data transfer objects are often used to map domain models to simpler objects that will ultimately get displayed by the view.

From Wikipedia:

Data transfer object (DTO), formerly known as value objects or VO, is a design pattern used to transfer data between software application subsystems. DTOs are often used in conjunction with data access objects to retrieve data from a database.

Simple regular expression for a decimal with a precision of 2

This will allow decimal with exponentiation and upto 2 digits ,

^[+-]?\d+(\.\d{2}([eE](-[1-9]([0-9]*)?|[+]?\d+))?)?$

Demo

Python: Importing urllib.quote

If you need to handle both Python 2.x and 3.x you can catch the exception and load the alternative.

try:
    from urllib import quote  # Python 2.X
except ImportError:
    from urllib.parse import quote  # Python 3+

You could also use the python compatibility wrapper six to handle this.

from six.moves.urllib.parse import quote

Remove all unused resources from an android project

The Gradle build system for Android supports "resource shrinking": the automatic removal of resources that are unused, at build time, in the packaged app. In addition to removing resources in your project that are not actually needed at runtime, this also removes resources from libraries you are depending on if they are not actually needed by your application.

To enable this add the line shrinkResources true in your gradle file.

   android {
        ...

        buildTypes {
            release {
                minifyEnabled true //Important step
                shrinkResources true
            }
   }
}

Check the official documentation here,

http://tools.android.com/tech-docs/new-build-system/resource-shrinking

SQL Server Convert Varchar to Datetime

You could do it this way but it leaves it as a varchar

declare @s varchar(50)

set @s = '2011-09-28 18:01:00'

select convert(varchar, cast(@s as datetime), 105) + RIGHT(@s, 9)

or

select convert(varchar(20), @s, 105)

Is it possible to run CUDA on AMD GPUs?

I think it is going to be possible soon in AMD FirePro GPU's, see press release here but support is coming 2016 Q1 for the developing tools:

An early access program for the "Boltzmann Initiative" tools is planned for Q1 2016.

Multiple select in Visual Studio?

in visual 2019, Open Options to show all enter image description here

and multi select: keep Ctrl + Alt then click position you want or, keep Shift + Alt then click position to multi select multi line from start to end line clicked

Why is Ant giving me a Unsupported major.minor version error

Simply just check your run time by go to ant build configuration and change the jre against to jdk (if jdk 1.7 then jre should be 1.7) .

enter image description here

Windows batch command(s) to read first line from text file

uh? imo this is much simpler

  set /p texte=< file.txt  
  echo %texte%

Pick any kind of file via an Intent in Android

Turns out the Samsung file explorer uses a custom action. This is why I could see the Samsung file explorer when looking for a file from the samsung apps, but not from mine.

The action is "com.sec.android.app.myfiles.PICK_DATA"

I created a custom Activity Picker which displays activities filtering both intents.

Bootstrap 3 Flush footer to bottom. not fixed

Galen Gidman has posted a really good solution to the problem of a responsive sticky footer that does not have a fixed height. You can find his full solution on his blog: http://galengidman.com/2014/03/25/responsive-flexible-height-sticky-footers-in-css/

HTML

<header class="page-row">
  <h1>Site Title</h1>
</header>

<main class="page-row page-row-expanded">
  <p>Page content goes here.</p>
</main>

<footer class="page-row">
  <p>Copyright, blah blah blah.</p>
</footer>

CSS

html,
body { height: 100%; }

body {
  display: table;
  width: 100%;
}

.page-row {
  display: table-row;
  height: 1px;
}

.page-row-expanded { height: 100%; }

How to remove the Flutter debug banner?

MaterialApp( debugShowCheckedModeBanner: false, )

Why is there an unexplainable gap between these inline-block div elements?

Using inline-block allows for white-space in your HTML, This usually equates to .25em (or 4px).

You can either comment out the white-space or, a more commons solution, is to set the parent's font-size to 0 and the reset it back to the required size on the inline-block elements.

jQuery click events not working in iOS

There is an issue with iOS not registering click/touch events bound to elements added after DOM loads.

While PPK has this advice: http://www.quirksmode.org/blog/archives/2010/09/click_event_del.html

I've found this the easy fix, simply add this to the css:

cursor: pointer;

Merge development branch with master

If you are on Mac or Ubuntu, go to the working folder of the branch. In the terminal

suppose harisdev is the branchname.

git checkout master

if there are untracked or uncommitted files you will get an error and you have to commit or delete all the untracked or uncommitted files.

git merge harisdev 

git push origin master

One last command to delete the branch.

$ git branch -d harisdev

Keep CMD open after BAT file executes

I was also confused as to why we're adding a cmd at the beginning and I was wondering if I had to open the command prompt first. What you need to do is type the full command along with cmd /k. For example assume your batch file name is "my_command.bat" which runs the command javac my_code.java then the code in your batch file should be:

cmd /k javac my_code.java

So basically there is no need to open command prompt at the current folder and type the above command but you can save this code directly in your batch file and execute it directly.

Best way to encode Degree Celsius symbol into web page?

Try to replace it with &deg;, and also to set the charset to utf-8, as Martin suggests.

&deg;C will get you something like this:

Degrees Celsius

Inner join of DataTables in C#

this function will join 2 tables with a known join field, but this cannot allow 2 fields with the same name on both tables except the join field, a simple modification would be to save a dictionary with a counter and just add number to the same name filds.

public static DataTable JoinDataTable(DataTable dataTable1, DataTable dataTable2, string joinField)
{
    var dt = new DataTable();
    var joinTable = from t1 in dataTable1.AsEnumerable()
                            join t2 in dataTable2.AsEnumerable()
                                on t1[joinField] equals t2[joinField]
                            select new { t1, t2 };

    foreach (DataColumn col in dataTable1.Columns)
        dt.Columns.Add(col.ColumnName, typeof(string));

    dt.Columns.Remove(joinField);

    foreach (DataColumn col in dataTable2.Columns)
        dt.Columns.Add(col.ColumnName, typeof(string));

    foreach (var row in joinTable)
    {
        var newRow = dt.NewRow();
        newRow.ItemArray = row.t1.ItemArray.Union(row.t2.ItemArray).ToArray();
        dt.Rows.Add(newRow);
    }
    return dt;
}

how to display toolbox on the left side of window of Visual Studio Express for windows phone 7 development?

Ctrl-Alt-X is the keyboard shortcut I use, although that may because I have Resharper installed - otherwise Ctrl W, X.

From the menu: View -> Toolbox.

You can easily view/change key bindings using Tools -> Options Environment->Keyboard. It has a convenient UI where you can enter a word, and it shows you what key bindings include that word, including View.Toolbox.

You might want to browse through the online MSDN documentation on getting started with Visual Studio.

Is there a way to get the XPath in Google Chrome?

You can try using Chrome Web Extension TruePath which dynamically generates the relative XPath on right click on the web page and display all the XPath as menu items.

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

I found a simple way... I needed to tack a char on to a string that was being built on the fly. I needed a char list; because I was giving the user a choice and using that choice in a switch() statement.

I simply added another std::string Slist; and set the new string equal to the character, "list" - a, b, c or whatever the end user chooses like this:

char list;
std::string cmd, state[], Slist;
Slist = list; //set this string to the chosen char;
cmd = Slist + state[x] + "whatever";
system(cmd.c_str());

Complexity may be cool but simplicity is cooler. IMHO

How to get the SHA-1 fingerprint certificate in Android Studio for debug mode?

The easiest way to get the finger print is to switch from app to signed report by clicking the drop down and click build.

enter image description here

Then you will be able to see the sha1 fingerprint at the bottom pane where you see the debug report and stack trace. N.B remember to switch back to app when you want to run your app on a device or an emulator.

Check whether an input string contains a number in javascript

You can also try lodash:

const isNumeric = number => 
  _.isFinite(_.parseInt(number)) && !_.isNaN(_.parseInt(number))

Asynchronously load images with jQuery

AFAIK you would have to do a .load() function here as apposed to the .ajax(), but you could use jQuery setTimeout to keep it live (ish)

<script>
 $(document).ready(function() {
 $.ajaxSetup({
    cache: false
});
 $("#placeholder").load("PATH TO IMAGE");
   var refreshId = setInterval(function() {
      $("#placeholder").load("PATH TO IMAGE");
   }, 500);
});
</script>

Get value from text area

$('textarea').val();

textarea.value would be pure JavaScript, but here you're trying to use JavaScript as a not-valid jQuery method (.value).

What is the Windows version of cron?

Not exactly a Windows version, however you can use Cygwin's crontab. For install instructions, see here: here.

What is the difference between sed and awk?

sed is a stream editor. It works with streams of characters on a per-line basis. It has a primitive programming language that includes goto-style loops and simple conditionals (in addition to pattern matching and address matching). There are essentially only two "variables": pattern space and hold space. Readability of scripts can be difficult. Mathematical operations are extraordinarily awkward at best.

There are various versions of sed with different levels of support for command line options and language features.

awk is oriented toward delimited fields on a per-line basis. It has much more robust programming constructs including if/else, while, do/while and for (C-style and array iteration). There is complete support for variables and single-dimension associative arrays plus (IMO) kludgey multi-dimension arrays. Mathematical operations resemble those in C. It has printf and functions. The "K" in "AWK" stands for "Kernighan" as in "Kernighan and Ritchie" of the book "C Programming Language" fame (not to forget Aho and Weinberger). One could conceivably write a detector of academic plagiarism using awk.

GNU awk (gawk) has numerous extensions, including true multidimensional arrays in the latest version. There are other variations of awk including mawk and nawk.

Both programs use regular expressions for selecting and processing text.

I would tend to use sed where there are patterns in the text. For example, you could replace all the negative numbers in some text that are in the form "minus-sign followed by a sequence of digits" (e.g. "-231.45") with the "accountant's brackets" form (e.g. "(231.45)") using this (which has room for improvement):

sed 's/-\([0-9.]\+\)/(\1)/g' inputfile

I would use awk when the text looks more like rows and columns or, as awk refers to them "records" and "fields". If I was going to do a similar operation as above, but only on the third field in a simple comma delimited file I might do something like:

awk -F, 'BEGIN {OFS = ","} {gsub("-([0-9.]+)", "(" substr($3, 2) ")", $3); print}' inputfile

Of course those are just very simple examples that don't illustrate the full range of capabilities that each has to offer.

How to correct indentation in IntelliJ

You can also try out ctrl + alt + I even though you can also use l as well.

JavaScript private methods

Since everybody was posting here his own code, I'm gonna do that too...

I like Crockford because he introduced real object oriented patterns in Javascript. But he also came up with a new misunderstanding, the "that" one.

So why is he using "that = this"? It has nothing to do with private functions at all. It has to do with inner functions!

Because according to Crockford this is buggy code:

Function Foo( ) {
    this.bar = 0; 
    var foobar=function( ) {
        alert(this.bar);
    }
} 

So he suggested doing this:

Function Foo( ) {
    this.bar = 0;
    that = this; 
    var foobar=function( ) {
        alert(that.bar);
    }
}

So as I said, I'm quite sure that Crockford was wrong his explanation about that and this (but his code is certainly correct). Or was he just fooling the Javascript world, to know who is copying his code? I dunno...I'm no browser geek ;D

EDIT

Ah, that's what is all about: What does 'var that = this;' mean in JavaScript?

So Crockie was really wrong with his explanation....but right with his code, so he's still a great guy. :))

How to force Sequential Javascript Execution?

If you don't insist on using pure Javascript, you can build a sequential code in Livescript and it looks pretty good. You might want to take a look at this example:

# application
do
    i = 3
    console.log td!, "start"
    <- :lo(op) ->
        console.log td!, "hi #{i}"
        i--
        <- wait-for \something
        if i is 0
            return op! # break
        lo(op)
    <- sleep 1500ms
    <- :lo(op) ->
        console.log td!, "hello #{i}"
        i++
        if i is 3
            return op! # break
        <- sleep 1000ms
        lo(op)
    <- sleep 0
    console.log td!, "heyy"

do
    a = 8
    <- :lo(op) ->
        console.log td!, "this runs in parallel!", a
        a--
        go \something
        if a is 0
            return op! # break
        <- sleep 500ms
        lo(op)

Output:

0ms : start
2ms : hi 3
3ms : this runs in parallel! 8
3ms : hi 2
505ms : this runs in parallel! 7
505ms : hi 1
1007ms : this runs in parallel! 6
1508ms : this runs in parallel! 5
2009ms : this runs in parallel! 4
2509ms : hello 0
2509ms : this runs in parallel! 3
3010ms : this runs in parallel! 2
3509ms : hello 1
3510ms : this runs in parallel! 1
4511ms : hello 2
4511ms : heyy

What are the most useful Intellij IDEA keyboard shortcuts?

By far my favourite all purpose shortcut is Ctrl+Shift+A

It does a search as you type through all the commands in intellij. Not only that but when you find the command you want it also displays the corresponding shortcut key next to it!

Radio Buttons "Checked" Attribute Not Working

Hey I was also facing similar problem, in an ajax generated page.. I took generated source using Webdeveloper pluggin in FF, and checked all the inputs in the form and found out that there was another checkbox inside a hidden div(display:none) with same ID, Once I changed the id of second checkbox, it started working.. You can also try that.. and let me know the result.. cheers

Show tables, describe tables equivalent in redshift

Or simply:

\dt to show tables

\d+ <table name> to describe a table

Edit: Works using the psql command line client

How to specify in crontab by what user to run script?

EDIT: Note that this method won't work with crontab -e, but only works if you edit /etc/crontab directly. Otherwise, you may get an error like /bin/sh: www-data: command not found

Just before the program name:

*/1 * * * * www-data php5 /var/www/web/includes/crontab/queue_process.php >> /var/www/web/includes/crontab/queue.log 2>&1

PHP array printing using a loop

Foreach before foreach: :)

reset($array); 
while(list($key,$value) = each($array))
{
  // we used this back in php3 :)
}

DropdownList DataSource

protected void Page_Load(object sender, EventArgs e)
{
    if (!Page.IsPostBack)
    {
        drpCategory.DataSource = CategoryHelper.Categories;
        drpCategory.DataTextField = "Name";
        drpCategory.DataValueField = "Id";
        drpCategory.DataBind();
    }
}

Understanding the basics of Git and GitHub

  1. What is the difference between Git and GitHub?

    Git is a version control system; think of it as a series of snapshots (commits) of your code. You see a path of these snapshots, in which order they where created. You can make branches to experiment and come back to snapshots you took.

    GitHub, is a web-page on which you can publish your Git repositories and collaborate with other people.

  2. Is Git saving every repository locally (in the user's machine) and in GitHub?

    No, it's only local. You can decide to push (publish) some branches on GitHub.

  3. Can you use Git without GitHub? If yes, what would be the benefit for using GitHub?

    Yes, Git runs local if you don't use GitHub. An alternative to using GitHub could be running Git on files hosted on Dropbox, but GitHub is a more streamlined service as it was made especially for Git.

  4. How does Git compare to a backup system such as Time Machine?

    It's a different thing, Git lets you track changes and your development process. If you use Git with GitHub, it becomes effectively a backup. However usually you would not push all the time to GitHub, at which point you do not have a full backup if things go wrong. I use git in a folder that is synchronized with Dropbox.

  5. Is this a manual process, in other words if you don't commit you won't have a new version of the changes made?

    Yes, committing and pushing are both manual.

  6. If are not collaborating and you are already using a backup system why would you use Git?

    • If you encounter an error between commits you can use the command git diff to see the differences between the current code and the last working commit, helping you to locate your error.

    • You can also just go back to the last working commit.

    • If you want to try a change, but are not sure that it will work. You create a branch to test you code change. If it works fine, you merge it to the main branch. If it does not you just throw the branch away and go back to the main branch.

    • You did some debugging. Before you commit you always look at the changes from the last commit. You see your debug print statement that you forgot to delete.

Make sure you check gitimmersion.com.

File tree view in Notepad++

step-1) On Notepad++ Toolbar:

Plugins -> Plugin Manager -> Show Plugin Manager -> Available . Then select the Explorer. And click Install.

(Note: As in above comments some people like SherloXplorer. Pls, note that this requires .Net v2 )

step-2) Again on Notepad++ Toolbar:

Explorer->Explorer

Now you can view files with tree view.

Update: After adding Explorer, right click to edit a file in Notepad++ may stop working. To make it work again, restart Notepad++ afresh.

How to change text and background color?

You can also use PDCurses library. (http://pdcurses.sourceforge.net/)

Proper way to exit command line program?

Take a look at Job Control on UNIX systems

If you don't have control of your shell, simply hitting ctrl + C should stop the process. If that doesn't work, you can try ctrl + Z and using the jobs and kill -9 %<job #> to kill it. The '-9' is a type of signal. You can man kill to see a list of signals.

How do you make a div follow as you scroll?

the position:fixed; property should do the work, I used it on my Website and it worked fine. http://www.w3schools.com/css/css_positioning.asp

Difference in days between two dates in Java?

The diff / (24 * etc) does not take Timezone into account, so if your default timezone has a DST in it, it can throw the calculation off.

This link has a nice little implementation.

Here is the source of the above link in case the link goes down:

/** Using Calendar - THE CORRECT WAY**/  
public static long daysBetween(Calendar startDate, Calendar endDate) {  
  //assert: startDate must be before endDate  
  Calendar date = (Calendar) startDate.clone();  
  long daysBetween = 0;  
  while (date.before(endDate)) {  
    date.add(Calendar.DAY_OF_MONTH, 1);  
    daysBetween++;  
  }  
  return daysBetween;  
}  

and

/** Using Calendar - THE CORRECT (& Faster) WAY**/  
public static long daysBetween(final Calendar startDate, final Calendar endDate)
{
  //assert: startDate must be before endDate  
  int MILLIS_IN_DAY = 1000 * 60 * 60 * 24;  
  long endInstant = endDate.getTimeInMillis();  
  int presumedDays = 
    (int) ((endInstant - startDate.getTimeInMillis()) / MILLIS_IN_DAY);  
  Calendar cursor = (Calendar) startDate.clone();  
  cursor.add(Calendar.DAY_OF_YEAR, presumedDays);  
  long instant = cursor.getTimeInMillis();  
  if (instant == endInstant)  
    return presumedDays;

  final int step = instant < endInstant ? 1 : -1;  
  do {  
    cursor.add(Calendar.DAY_OF_MONTH, step);  
    presumedDays += step;  
  } while (cursor.getTimeInMillis() != endInstant);  
  return presumedDays;  
}

html text input onchange event

Well unless I misunderstand you can just use the onChange attribute:

<input type="text" onChange="return bar()">

Note: in FF 3 (at least) this is not called until some the user has confirmed they are changed either by clicking away from the element, clicking enter, or other.

Print debugging info from stored procedure in MySQL

Quick way to print something is:

select '** Place your mesage here' AS '** DEBUG:';

Failed to load ApplicationContext for JUnit test of Spring controller

As mentioned in duscusion: WEB-INF is not really a part of class path. If you use a common template such as maven, use src/main/resources or src/test/resources to place the app-context.xml into. Then you can use 'classpath:'.

Place your config file into src/main/resources/app-context.xml and use code

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:app-context.xml")
public class PersonControllerTest {
...
}

or you can make yout test context with different configuration of beans.

Place your config file into src/test/resources/test-app-context.xml and use code

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:test-app-context.xml")
public class PersonControllerTest {
...
}

Program to find largest and smallest among 5 numbers without using array

For example 5 consecutive numbers

int largestNumber;
int smallestNumber;
int number;
std::cin>>number;
largestNumber = number;
smallestNumber = number;
for (i=0 ; i<5; i++)
{
   std::cin>>number;
   if (number > largestNumber) 
   {
     largest = number;
   }
   if (numbers < smallestNumber) 
   {
     smallestNumber= number;
   }
}

Why do we have to normalize the input for an artificial neural network?

It's explained well here.

If the input variables are combined linearly, as in an MLP [multilayer perceptron], then it is rarely strictly necessary to standardize the inputs, at least in theory. The reason is that any rescaling of an input vector can be effectively undone by changing the corresponding weights and biases, leaving you with the exact same outputs as you had before. However, there are a variety of practical reasons why standardizing the inputs can make training faster and reduce the chances of getting stuck in local optima. Also, weight decay and Bayesian estimation can be done more conveniently with standardized inputs.

How to check if Thread finished execution

For a thread you have the myThread.IsAlive property. It is false if the thread method returned or the thread was aborted.

check if a std::vector contains a certain object?

If searching for an element is important, I'd recommend std::set instead of std::vector. Using this:

std::find(vec.begin(), vec.end(), x) runs in O(n) time, but std::set has its own find() member (ie. myset.find(x)) which runs in O(log n) time - that's much more efficient with large numbers of elements

std::set also guarantees all the added elements are unique, which saves you from having to do anything like if not contained then push_back()....

Login to Microsoft SQL Server Error: 18456

In my case multiple wrong attempts locked the account.To do that I had tried running the below query and it worked: ALTER LOGIN WITH PASSWORD= UNLOCK And make sure to set the option "Enforce Password Security" option for specific user to be unchecked by right click on Sql Server -> Properties.

Connect over ssh using a .pem file

You can connect to a AWS ec-2 instance using the following commands.

chmod 400 mykey.pem

ssh -i mykey.pem username@your-ip

by default the machine name usually be like ubuntu since usually ubuntu machine is used as a server so the following command will work in that case.

ssh -i mykey.pem ubuntu@your-ip

android get all contacts

Cursor contacts = getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
String aNameFromContacts[] = new String[contacts.getCount()];  
String aNumberFromContacts[] = new String[contacts.getCount()];  
int i = 0;

int nameFieldColumnIndex = contacts.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME);
int numberFieldColumnIndex = contacts.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);

while(contacts.moveToNext()) {

    String contactName = contacts.getString(nameFieldColumnIndex);
    aNameFromContacts[i] =    contactName ; 

    String number = contacts.getString(numberFieldColumnIndex);
    aNumberFromContacts[i] =    number ;
i++;
}

contacts.close();

The result will be aNameFromContacts array full of contacts. Also ensure that you have added

<uses-permission android:name="android.permission.READ_CONTACTS" />

in main.xml

Using Chrome's Element Inspector in Print Preview Mode?

With shortcuts available, the quickest way is to

  1. Open the Developer Tools

    • Windows: F12 or Ctrl+Shift+I
    • Mac: Cmd+Opt+I
  2. Open the Command Menu

    • Windows: Ctrl+Shift+P
    • Mac: Cmd+Shift+P
  3. Type print and select Emulate CSS print media type from the context menu

    Change Media Type Emulation Via Command Menu

Looking at the excellent and currently most-upvoted answer by lmeurs, I think this solution might also remain stable over time.

How can I give an imageview click effect like a button on Android?

Here is my code. The idea is that ImageView gets color filter when user touches it, and color filter is removed when user stops touching it.

Martin Booka Weser, András, Ah Lam, altosh, solution doesn't work when ImageView has also onClickEvent. worawee.s and kcoppock (with ImageButton) solution requires background, which has no sense when ImageView is not transparent.

This one is extension of AZ_ idea about color filter.

class PressedEffectStateListDrawable extends StateListDrawable {

    private int selectionColor;

    public PressedEffectStateListDrawable(Drawable drawable, int selectionColor) {
        super();
        this.selectionColor = selectionColor;
        addState(new int[] { android.R.attr.state_pressed }, drawable);
        addState(new int[] {}, drawable);
    }

    @Override
    protected boolean onStateChange(int[] states) {
        boolean isStatePressedInArray = false;
        for (int state : states) {
            if (state == android.R.attr.state_pressed) {
                isStatePressedInArray = true;
            }
        }
        if (isStatePressedInArray) {
            super.setColorFilter(selectionColor, PorterDuff.Mode.MULTIPLY);
        } else {
            super.clearColorFilter();
        }
        return super.onStateChange(states);
    }

    @Override
    public boolean isStateful() {
        return true;
    }
}

usage:

Drawable drawable = new FastBitmapDrawable(bm);
imageView.setImageDrawable(new PressedEffectStateListDrawable(drawable, 0xFF33b5e5));

SQL server query to get the list of columns in a table along with Data types, NOT NULL, and PRIMARY KEY constraints

To avoid duplicate rows for some columns, use user_type_id instead of system_type_id.

SELECT 
    c.name 'Column Name',
    t.Name 'Data type',
    c.max_length 'Max Length',
    c.precision ,
    c.scale ,
    c.is_nullable,
    ISNULL(i.is_primary_key, 0) 'Primary Key'
FROM    
    sys.columns c
INNER JOIN 
    sys.types t ON c.user_type_id = t.user_type_id
LEFT OUTER JOIN 
    sys.index_columns ic ON ic.object_id = c.object_id AND ic.column_id = c.column_id
LEFT OUTER JOIN 
    sys.indexes i ON ic.object_id = i.object_id AND ic.index_id = i.index_id
WHERE
    c.object_id = OBJECT_ID('YourTableName')

Just replace YourTableName with your actual table name - works for SQL Server 2005 and up.

In case you are using schemas, replace YourTableName by YourSchemaName.YourTableName where YourSchemaName is the actual schema name and YourTableName is the actual table name.

Having Django serve downloadable files

Another project to have a look at: http://readthedocs.org/docs/django-private-files/en/latest/usage.html Looks promissing, haven't tested it myself yet tho.

Basically the project abstracts the mod_xsendfile configuration and allows you to do things like:

from django.db import models
from django.contrib.auth.models import User
from private_files import PrivateFileField

def is_owner(request, instance):
    return (not request.user.is_anonymous()) and request.user.is_authenticated and
                   instance.owner.pk = request.user.pk

class FileSubmission(models.Model):
    description = models.CharField("description", max_length = 200)
        owner = models.ForeignKey(User)
    uploaded_file = PrivateFileField("file", upload_to = 'uploads', condition = is_owner)

Error in finding last used cell in Excel with VBA

Note: this answer was motivated by this comment. The purpose of UsedRange is different from what is mentioned in the answer above.

As to the correct way of finding the last used cell, one has first to decide what is considered used, and then select a suitable method. I conceive at least three meanings:

  1. Used = non-blank, i.e., having data.

  2. Used = "... in use, meaning the section that contains data or formatting." As per official documentation, this is the criterion used by Excel at the time of saving. See also this official documentation. If one is not aware of this, the criterion may produce unexpected results, but it may also be intentionally exploited (less often, surely), e.g., to highlight or print specific regions, which may eventually have no data. And, of course, it is desirable as a criterion for the range to use when saving a workbook, lest losing part of one's work.

  3. Used = "... in use, meaning the section that contains data or formatting" or conditional formatting. Same as 2., but also including cells that are the target for any Conditional Formatting rule.

How to find the last used cell depends on what you want (your criterion).

For criterion 1, I suggest reading this answer. Note that UsedRange is cited as unreliable. I think that is misleading (i.e., "unfair" to UsedRange), as UsedRange is simply not meant to report the last cell containing data. So it should not be used in this case, as indicated in that answer. See also this comment.

For criterion 2, UsedRange is the most reliable option, as compared to other options also designed for this use. It even makes it unnecessary to save a workbook to make sure that the last cell is updated. Ctrl+End will go to a wrong cell prior to saving (“The last cell is not reset until you save the worksheet”, from http://msdn.microsoft.com/en-us/library/aa139976%28v=office.10%29.aspx. It is an old reference, but in this respect valid).

For criterion 3, I do not know any built-in method. Criterion 2 does not account for Conditional Formatting. One may have formatted cells, based on formulas, which are not detected by UsedRange or Ctrl+End. In the figure, the last cell is B3, since formatting was applied explicitly to it. Cells B6:D7 have a format derived from a Conditional Formatting rule, and this is not detected even by UsedRange. Accounting for this would require some VBA programming.

enter image description here


As to your specific question: What's the reason behind this?

Your code uses the first cell in your range E4:E48 as a trampoline, for jumping down with End(xlDown).

The "erroneous" output will obtain if there are no non-blank cells in your range other than perhaps the first. Then, you are leaping in the dark, i.e., down the worksheet (you should note the difference between blank and empty string!).

Note that:

  1. If your range contains non-contiguous non-blank cells, then it will also give a wrong result.

  2. If there is only one non-blank cell, but it is not the first one, your code will still give you the correct result.

Pointer to a string in C?

The same notation is used for pointing at a single character or the first character of a null-terminated string:

char c = 'Z';
char a[] = "Hello world";

char *ptr1 = &c;
char *ptr2 = a;      // Points to the 'H' of "Hello world"
char *ptr3 = &a[0];  // Also points to the 'H' of "Hello world"
char *ptr4 = &a[6];  // Points to the 'w' of "world"
char *ptr5 = a + 6;  // Also points to the 'w' of "world"

The values in ptr2 and ptr3 are the same; so are the values in ptr4 and ptr5. If you're going to treat some data as a string, it is important to make sure it is null terminated, and that you know how much space there is for you to use. Many problems are caused by not understanding what space is available and not knowing whether the string was properly null terminated.

Note that all the pointers above can be dereferenced as if they were an array:

 *ptr1    == 'Z'
  ptr1[0] == 'Z'

 *ptr2    == 'H'
  ptr2[0] == 'H'
  ptr2[4] == 'o'

 *ptr4    == 'w'
  ptr4[0] == 'w'
  ptr4[4] == 'd'

  ptr5[0] ==   ptr3[6]
*(ptr5+0) == *(ptr3+6)

Late addition to question

What does char (*ptr)[N]; represent?

This is a more complex beastie altogether. It is a pointer to an array of N characters. The type is quite different; the way it is used is quite different; the size of the object pointed to is quite different.

char (*ptr)[12] = &a;

(*ptr)[0] == 'H'
(*ptr)[6] == 'w'

*(*ptr + 6) == 'w'

Note that ptr + 1 points to undefined territory, but points 'one array of 12 bytes' beyond the start of a. Given a slightly different scenario:

char b[3][12] = { "Hello world", "Farewell", "Au revoir" };

char (*pb)[12] = &b[0];

Now:

(*(pb+0))[0] == 'H'
(*(pb+1))[0] == 'F'
(*(pb+2))[5] == 'v'

You probably won't come across pointers to arrays except by accident for quite some time; I've used them a few times in the last 25 years, but so few that I can count the occasions on the fingers of one hand (and several of those have been answering questions on Stack Overflow). Beyond knowing that they exist, that they are the result of taking the address of an array, and that you probably didn't want it, you don't really need to know more about pointers to arrays.

Python script header

The Python executable might be installed at a location other than /usr/bin, but env is nearly always present in that location so using /usr/bin/envis more portable.

Pass path with spaces as parameter to bat file

Interesting one. I love collecting quotes about quotes handling in cmd/command.

Your particular scripts gets fixed by using %1 instead of "%1" !!!

By adding an 'echo on' ( or getting rid of an echo off ), you could have easily found that out.

Closure in Java 7

A closure is a block of code that can be referenced (and passed around) with access to the variables of the enclosing scope.

Since Java 1.1, anonymous inner class have provided this facility in a highly verbose manner. They also have a restriction of only being able to use final (and definitely assigned) local variables. (Note, even non-final local variables are in scope, but cannot be used.)

Java SE 8 is intended to have a more concise version of this for single-method interfaces*, called "lambdas". Lambdas have much the same restrictions as anonymous inner classes, although some details vary randomly.

Lambdas are being developed under Project Lambda and JSR 335.

*Originally the design was more flexible allowing Single Abstract Methods (SAM) types. Unfortunately the new design is less flexible, but does attempt to justify allowing implementation within interfaces.

Highlight a word with jQuery

You need to get the content of the p tag and replace all the dolors in it with the highlighted version.

You don't even need to have jQuery for this. :-)

Invalid length for a Base-64 char array

My guess is that you simply need to URL-encode your Base64 string when you include it in the querystring.

Base64 encoding uses some characters which must be encoded if they're part of a querystring (namely + and /, and maybe = too). If the string isn't correctly encoded then you won't be able to decode it successfully at the other end, hence the errors.

You can use the HttpUtility.UrlEncode method to encode your Base64 string:

string msg = "Please click on the link below or paste it into a browser "
             + "to verify your email account.<br /><br /><a href=\""
             + _configuration.RootURL + "Accounts/VerifyEmail.aspx?a="
             + HttpUtility.UrlEncode(userName.Encrypt("verify")) + "\">"
             + _configuration.RootURL + "Accounts/VerifyEmail.aspx?a="
             + HttpUtility.UrlEncode(userName.Encrypt("verify")) + "</a>";

JavaScript checking for null vs. undefined and difference between == and ===

Try With Different Logic. You can use bellow code for check all four(4) condition for validation like not null, not blank, not undefined and not zero only use this code (!(!(variable))) in javascript and jquery.

function myFunction() {
var data;  //The Values can be like as null, blank, undefined, zero you can test

if(!(!(data)))
{
   //If data has valid value
    alert("data "+data);
} 
else 
{
    //If data has null, blank, undefined, zero etc.
    alert("data is "+data);
}

}

Disable vertical scroll bar on div overflow: auto

This rules are compatible whit all browser:

body {overflow: hidden; }
body::-webkit-scrollbar { width: 0 !important; }
body { overflow: -moz-scrollbars-none; }
body { -ms-overflow-style: none; }

Conversion of a datetime2 data type to a datetime data type results out-of-range value

Adding this code to a class in ASP.NET worked fort me:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Properties<DateTime>().Configure(c => c.HasColumnType("datetime2"));
}

Java - What does "\n" mean?

\n 

This means insert a newline in the text at this point.

Just example

System.out.println("hello\nworld");

Output:

hello
world

C# Error: Parent does not contain a constructor that takes 0 arguments

The compiler cannot guess what should be passed for the base constructor argument. You have to do it explicitly:

public class child : parent {
    public child(int i) : base(i) {
        Console.WriteLine("child");
    }
}

AJAX jQuery refresh div every 5 seconds

Try this out.

function loadlink(){
    $('#links').load('test.php',function () {
         $(this).unwrap();
    });
}

loadlink(); // This will run on page load
setInterval(function(){
    loadlink() // this will run after every 5 seconds
}, 5000);

Hope this helps.

Check list of words in another string

Easiest and Simplest method of solving this problem is using re

import re

search_list = ['one', 'two', 'there']
long_string = 'some one long two phrase three'
if re.compile('|'.join(search_list),re.IGNORECASE).search(long_string): #re.IGNORECASE is used to ignore case
    # Do Something if word is present
else:
    # Do Something else if word is not present

Slide div left/right using jQuery

_x000D_
_x000D_
$(document).ready(function(){_x000D_
$("#left").on('click', function (e) {_x000D_
        e.stopPropagation();_x000D_
        e.preventDefault();_x000D_
        $('#left').hide("slide", { direction: "left" }, 500, function () {_x000D_
            $('#right').show("slide", { direction: "right" }, 500);_x000D_
        });_x000D_
    });_x000D_
    $("#right").on('click', function (e) {_x000D_
        e.stopPropagation();_x000D_
        e.preventDefault();_x000D_
        $('#right').hide("slide", { direction: "right" }, 500, function () {_x000D_
            $('#left').show("slide", { direction: "left" }, 500);_x000D_
        });_x000D_
    });_x000D_
_x000D_
})
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>_x000D_
_x000D_
<div style="height:100%;width:100%;background:cyan" id="left">_x000D_
<h1>Hello im going left to hide and will comeback from left to show</h1>_x000D_
</div>_x000D_
<div style="height:100%;width:100%;background:blue;display:none" id="right">_x000D_
<h1>Hello im coming from right to sho and will go back to right to hide</h1>_x000D_
</div>
_x000D_
_x000D_
_x000D_

$("#btnOpenEditing").off('click');
$("#btnOpenEditing").on('click', function (e) {
    e.stopPropagation();
    e.preventDefault();
    $('#mappingModel').hide("slide", { direction: "right" }, 500, function () {
        $('#fsEditWindow').show("slide", { direction: "left" }, 500);
    });
});

It will work like charm take a look at the demo.

Remove leading comma from a string

s=s.substring(1);

I like to keep stuff simple.

How to stop console from closing on exit?

Yes, in VS2010 they changed this behavior somewhy.
Open your project and navigate to the following menu: Project -> YourProjectName Properties -> Configuration Properties -> Linker -> System. There in the field SubSystem use the drop-down to select Console (/SUBSYSTEM:CONSOLE) and apply the change.
"Start without debugging" should do the right thing now.

Or, if you write in C++ or in C, put

system("pause");

at the end of your program, then you'll get "Press any key to continue..." even when running in debug mode.

UITextField border color

Try this:

UITextField *theTextFiels=[[UITextField alloc]initWithFrame:CGRectMake(40, 40, 150, 30)];
    theTextFiels.borderStyle=UITextBorderStyleNone;
    theTextFiels.layer.cornerRadius=8.0f;
    theTextFiels.layer.masksToBounds=YES;
        theTextFiels.backgroundColor=[UIColor redColor];
    theTextFiels.layer.borderColor=[[UIColor blackColor]CGColor];
    theTextFiels.layer.borderWidth= 1.0f;

    [self.view addSubview:theTextFiels];
    [theTextFiels release];

and import QuartzCore:

#import <QuartzCore/QuartzCore.h>

HTTP POST Returns Error: 417 "Expectation Failed."

System.Net.HttpWebRequest adds the header 'HTTP header "Expect: 100-Continue"' to every request unless you explicitly ask it not to by setting this static property to false:

System.Net.ServicePointManager.Expect100Continue = false;

Some servers choke on that header and send back the 417 error you're seeing.

Give that a shot.

How to reload .bashrc settings without logging out and back in again?

Depending upon your environment, you may want to add scripting to have .bashrc load automatically when you open an SSH session. I recently did a migration to a server running Ubuntu, and there, .profile, not .bashrc or .bash_profile is loaded by default. To run any scripts in .bashrc, I had to run source ~/.bashrc every time a session was opened, which doesn't help when running remote deploys.

To have your .bashrc load automatically when opening a session, try adding this to .profile:

if [ -n "$BASH_VERSION" ]; then
    # include .bashrc if it exists
    if [ -f "$HOME/.bashrc" ]; then
        . "$HOME/.bashrc"
    fi
fi

Reopen your session, and it should load any paths/scripts you have in .bashrc.

How to convert the system date format to dd/mm/yy in SQL Server 2008 R2?

The query below will result in dd-mmm-yy format.

select 
cast(DAY(getdate()) as varchar)+'-'+left(DATEname(m,getdate()),3)+'-'+  
Right(Year(getdate()),2)

Make a float only show two decimal places

Here's some methods to format dynamically according to a precision:

+ (NSNumber *)numberFromString:(NSString *)string
{
    if (string.length) {
        NSNumberFormatter * f = [[NSNumberFormatter alloc] init];
        f.numberStyle = NSNumberFormatterDecimalStyle;
        return [f numberFromString:string];
    } else {
        return nil;
    }
}

+ (NSString *)stringByFormattingString:(NSString *)string toPrecision:(NSInteger)precision
{
    NSNumber *numberValue = [self numberFromString:string];

    if (numberValue) {
        NSString *formatString = [NSString stringWithFormat:@"%%.%ldf", (long)precision];
        return [NSString stringWithFormat:formatString, numberValue.floatValue];
    } else {
        /* return original string */
        return string;
    }
}

e.g.

[TSPAppDelegate stringByFormattingString:@"2.346324" toPrecision:4];

=> 2.3453

[TSPAppDelegate stringByFormattingString:@"2.346324" toPrecision:0];

=> 2

[TSPAppDelegate stringByFormattingString:@"2.346324" toPrecision:2];

=> 2.35 (round up)

VB.Net Properties - Public Get, Private Set

I'm not sure what the minimum required version of Visual Studio is, but in VS2015 you can use

Public ReadOnly Property Name As String

It is read-only for public access but can be privately modified using _Name

What is a regex to match ONLY an empty string?

Another possible answer considering also the case that an empty string might contain several whitespace characters for example spaces,tabs,line break characters can be the folllowing pattern.

pattern = r"^(\s*)$"

This pattern matches if the string starts and ends with zero or more whitespace characters.

It was tested in Python 3

if checkbox is checked, do this

Why not use the built in events?

$('#checkbox').click(function(e){
    if(e.target.checked) {
     // code to run if checked
        console.log('Checked');

     } else {

     //code to run if unchecked
        console.log('Unchecked');
     }
});

Reactjs convert html string to jsx

i found this js fiddle. this works like this

function unescapeHTML(html) {
    var escapeEl = document.createElement('textarea');
    escapeEl.innerHTML = html;
    return escapeEl.textContent;
}

<textarea className="form-control redactor"
                          rows="5" cols="9"
                          defaultValue={unescapeHTML(this.props.destination.description)}
                          name='description'></textarea>

jsfiddle link

How to fix "could not find a base address that matches schema http"... in WCF

I had to do two things to the IIS configuration of the site/application. My issue had to do with getting net.tcp working in an IIS Web Site App:

First:

  1. Right click on the IIS App name.
  2. Manage Web Site
  3. Advanced Settings
  4. Set Enabled protocols to be "http,net.tcp"

Second:

  1. Under the Actions menu on the right side of the Manager, click Bindings...
  2. Click Add
  3. Change type to "net.tcp"
  4. Set binding information to {open port number}:*
  5. OK

Transpose a range in VBA

Strictly in reference to prefacing "transpose", by the book, either one will work; i.e., application.transpose() OR worksheetfunction.transpose(), and by experience, if you really like typing, application.WorksheetFunction.Transpose() will work also-

How do I see if Wi-Fi is connected on Android?

Here is what I use as a utility method in my apps:

public static boolean isDeviceOnWifi(final Context context) {
        ConnectivityManager connManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo mWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
        return mWifi != null && mWifi.isConnectedOrConnecting();
}

Check if a string contains a number

You can use NLTK method for it.

This will find both '1' and 'One' in the text:

import nltk 

def existence_of_numeric_data(text):
    text=nltk.word_tokenize(text)
    pos = nltk.pos_tag(text)
    count = 0
    for i in range(len(pos)):
        word , pos_tag = pos[i]
        if pos_tag == 'CD':
            return True
    return False

existence_of_numeric_data('We are going out. Just five you and me.')

Markdown `native` text alignment

To center align, surround the text you wish to center align with arrows (-> <-) like so:

-> This is center aligned <-

How do I add a newline to command output in PowerShell?

Ultimately, what you're trying to do with the EXTRA blank lines between each one is a little confusing :)

I think what you really want to do is use Get-ItemProperty. You'll get errors when values are missing, but you can suppress them with -ErrorAction 0 or just leave them as reminders. Because the Registry provider returns extra properties, you'll want to stick in a Select-Object that uses the same properties as the Get-Properties.

Then if you want each property on a line with a blank line between, use Format-List (otherwise, use Format-Table to get one per line).

gci -path hklm:\software\microsoft\windows\currentversion\uninstall |
gp -Name DisplayName, InstallDate | 
select DisplayName, InstallDate | 
fl | out-file addrem.txt

Is there a way to suppress JSHint warning for one given line?

As you can see in the documentation of JSHint you can change options per function or per file. In your case just place a comment in your file or even more local just in the function that uses eval:

/*jshint evil:true */

function helloEval(str) {
    /*jshint evil:true */
    eval(str);
}

What is the meaning of CTOR?

Usually this region should contains the constructors of the class

Client to send SOAP request and receive response

Call SOAP webservice in c#

using (var client = new UpdatedOutlookServiceReferenceAPI.OutlookServiceSoapClient("OutlookServiceSoap"))
{
    ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls12;
    var result = client.UploadAttachmentBase64(GUID, FinalFileName, fileURL);

    if (result == true)
    {
        resultFlag = true;
    }
    else
    {
        resultFlag = false;
    }
    LogWriter.LogWrite1("resultFlag : " + resultFlag);
}

Where does PHP store the error log? (php5, apache, fastcgi, cpanel)

It appears that by default php does not log errors anywhere, the error_log key in php.ini is commented out in all the install's I've seen.

Generally I:

  1. look for php.ini files. locate php.ini.
  2. Search these files for the error_reporting value;

    Which should be set to whatever amalgamation of php log levels are enough for you.,

    Eg: E_ALL & ~E_DEPRECATED & ~E_STRICT

  3. Check the error_log value to make sure it points to an actual place and is not commented out.

    The default value doesn't give a full path, only a file name, I don't know where this path resolves to normally. Probably /var/log/.

Grunt watch error - Waiting...Fatal error: watch ENOSPC

After trying grenade's answer you may use a temporary fix:

sudo bash -c 'echo 524288 > /proc/sys/fs/inotify/max_user_watches'

This does the same thing as kds's answer, but without persisting the changes. This is useful if the error just occurs after some uptime of your system.

Get first element of Series without knowing the index

Use iloc to access by position (rather than label):

In [11]: df = pd.DataFrame([[1, 2], [3, 4]], ['a', 'b'], ['A', 'B'])

In [12]: df
Out[12]: 
   A  B
a  1  2
b  3  4

In [13]: df.iloc[0]  # first row in a DataFrame
Out[13]: 
A    1
B    2
Name: a, dtype: int64

In [14]: df['A'].iloc[0]  # first item in a Series (Column)
Out[14]: 1

How to correctly assign a new string value?

The two structs are different. When you initialize the first struct, about 40 bytes of memory are allocated. When you initialize the second struct, about 10 bytesof memory are allocated. (Actual amount is architecture dependent)

You can use the string literals (string constants) to initalize character arrays. This is why

person p = {"John", "Doe",30};

works in the first example.

You cannot assign (in the conventional sense) a string in C.

The string literals you have ("John") are loaded into memory when your code executes. When you initialize an array with one of these literals, then the string is copied into a new memory location. In your second example, you are merely copying the pointer to (location of) the string literal. Doing something like:

char* string = "Hello";
*string = 'C'

might cause compile or runtime errors (I am not sure.) It is a bad idea because you are modifying the literal string "Hello" which, for example on a microcontroler, could be located in read-only memory.

How to convert a .eps file to a high quality 1024x1024 .jpg?

Maybe you should try it with -quality 100 -size "1024x1024", because resize often gives results that are ugly to view.

Remove all classes that begin with a certain string

An approach I would use using simple jQuery constructs and array handling functions, is to declare an function that takes id of the control and prefix of the class and deleted all classed. The code is attached:

function removeclasses(controlIndex,classPrefix){
    var classes = $("#"+controlIndex).attr("class").split(" ");
    $.each(classes,function(index) {
        if(classes[index].indexOf(classPrefix)==0) {
            $("#"+controlIndex).removeClass(classes[index]);
        }
    });
}

Now this function can be called from anywhere, onclick of button or from code:

removeclasses("a","bg");

How to debug a bash script?

This answer is valid and useful: https://stackoverflow.com/a/951352

But, I find that the "standard" script debugging methods are inefficient, unintuitive, and hard to use. For those used to sophisticated GUI debuggers that put everything at your fingertips and make the job a breeze for easy problems (and possible for hard problems), these solutions aren't very satisfactory.

What I do is use a combination of DDD and bashdb. The former executes the latter, and the latter executes your script. This provides a multi-window UI with the ability to step through code in context and view variables, stack, etc., without the constant mental effort to maintain context in your head or keep re-listing the source.

There is guidance on setting that up here: http://ubuntuforums.org/showthread.php?t=660223

Pandas: Creating DataFrame from Series

I guess anther way, possibly faster, to achieve this is 1) Use dict comprehension to get desired dict (i.e., taking 2nd col of each array) 2) Then use pd.DataFrame to create an instance directly from the dict without loop over each col and concat.

Assuming your mat looks like this (you can ignore this since your mat is loaded from file):

In [135]: mat = {'a': np.random.randint(5, size=(4,2)),
   .....: 'b': np.random.randint(5, size=(4,2))}

In [136]: mat
Out[136]: 
{'a': array([[2, 0],
        [3, 4],
        [0, 1],
        [4, 2]]), 'b': array([[1, 0],
        [1, 1],
        [1, 0],
        [2, 1]])}

Then you can do:

In [137]: df = pd.DataFrame ({name:mat[name][:,1] for name in mat})

In [138]: df
Out[138]: 
   a  b
0  0  0
1  4  1
2  1  0
3  2  1

[4 rows x 2 columns]

How to create nested directories using Mkdir in Golang?

os.Mkdir is used to create a single directory. To create a folder path, instead try using:

os.MkdirAll(folderPath, os.ModePerm)

Go documentation

func MkdirAll(path string, perm FileMode) error

MkdirAll creates a directory named path, along with any necessary parents, and returns nil, or else returns an error. The permission bits perm are used for all directories that MkdirAll creates. If path is already a directory, MkdirAll does nothing and returns nil.

Edit:

Updated to correctly use os.ModePerm instead.
For concatenation of file paths, use package path/filepath as described in @Chris' answer.

How do I best silence a warning about unused variables?

doesn't flag these warnings by default. This warning must have been turned on either explicitly by passing -Wunused-parameter to the compiler or implicitly by passing -Wall -Wextra (or possibly some other combination of flags).

Unused parameter warnings can simply be suppressed by passing -Wno-unused-parameter to the compiler, but note that this disabling flag must come after any possible enabling flags for this warning in the compiler command line, so that it can take effect.

How to get a substring of text?

Use String#slice, also aliased as [].

a = "hello there"
a[1]                   #=> "e"
a[1,3]                 #=> "ell"
a[1..3]                #=> "ell"
a[6..-1]               #=> "there"
a[6..]                 #=> "there" (requires Ruby 2.6+)
a[-3,2]                #=> "er"
a[-4..-2]              #=> "her"
a[12..-1]              #=> nil
a[-2..-4]              #=> ""
a[/[aeiou](.)\1/]      #=> "ell"
a[/[aeiou](.)\1/, 0]   #=> "ell"
a[/[aeiou](.)\1/, 1]   #=> "l"
a[/[aeiou](.)\1/, 2]   #=> nil
a["lo"]                #=> "lo"
a["bye"]               #=> nil

Div height 100% and expands to fit content

Modern browsers support the "viewport height" unit. This will expand the div to the available viewport height. I find it more reliable than any other approach.

#some_div {
    height: 100vh;
    background: black;
}

How do you reverse a string in place in C or C++?

#include <algorithm>
std::reverse(str.begin(), str.end());

This is the simplest way in C++.

PHP executable not found. Install PHP 7 and add it to your PATH or set the php.executablePath setting

This one also works

  1. Remove the "php.executablePath" line from the VS code settings.

  2. Then add the xampp php path to the System variables

enter image description here

enter image description here

After that restart the Visual Studio Code

How to add Certificate Authority file in CentOS 7

copy your certificates inside

/etc/pki/ca-trust/source/anchors/

then run the following command

update-ca-trust

Create a menu Bar in WPF?

<DockPanel>
    <Menu DockPanel.Dock="Top">
        <MenuItem Header="_File">
            <MenuItem Header="_Open"/>
            <MenuItem Header="_Close"/>
            <MenuItem Header="_Save"/>
        </MenuItem>
    </Menu>
    <StackPanel></StackPanel>
</DockPanel>

Angular2: How to load data before rendering the component?

A nice solution that I've found is to do on UI something like:

<div *ngIf="isDataLoaded">
 ...Your page...
</div

Only when: isDataLoaded is true the page is rendered.

JavaScript calculate the day of the year (1 - 366)

You can pass parameter as date number in setDate function:

var targetDate = new Date();
targetDate.setDate(1);

// Now we can see the expected date as: Mon Jan 01 2018 01:43:24
console.log(targetDate);

targetDate.setDate(365);

// You can see: Mon Dec 31 2018 01:44:47
console.log(targetDate)

Determine if running on a rooted device

Instead of using isRootAvailable() you can use isAccessGiven(). Direct from RootTools wiki:

if (RootTools.isAccessGiven()) {
    // your app has been granted root access
}

RootTools.isAccessGiven() not only checks that a device is rooted, it also calls su for your app, requests permission, and returns true if your app was successfully granted root permissions. This can be used as the first check in your app to make sure that you will be granted access when you need it.

Reference

How to convert interface{} to string?

You don't need to use a type assertion, instead just use the %v format specifier with Sprintf:

hostAndPort := fmt.Sprintf("%v:%v", arguments["<host>"], arguments["<port>"])

How to check file MIME type with javascript before upload?

As Drake states this could be done with FileReader. However, what I present here is a functional version. Take in consideration that the big problem with doing this with JavaScript is to reset the input file. Well, this restricts to only JPG (for other formats you will have to change the mime type and the magic number):

<form id="form-id">
  <input type="file" id="input-id" accept="image/jpeg"/>
</form>

<script type="text/javascript">
    $(function(){
        $("#input-id").on('change', function(event) {
            var file = event.target.files[0];
            if(file.size>=2*1024*1024) {
                alert("JPG images of maximum 2MB");
                $("#form-id").get(0).reset(); //the tricky part is to "empty" the input file here I reset the form.
                return;
            }

            if(!file.type.match('image/jp.*')) {
                alert("only JPG images");
                $("#form-id").get(0).reset(); //the tricky part is to "empty" the input file here I reset the form.
                return;
            }

            var fileReader = new FileReader();
            fileReader.onload = function(e) {
                var int32View = new Uint8Array(e.target.result);
                //verify the magic number
                // for JPG is 0xFF 0xD8 0xFF 0xE0 (see https://en.wikipedia.org/wiki/List_of_file_signatures)
                if(int32View.length>4 && int32View[0]==0xFF && int32View[1]==0xD8 && int32View[2]==0xFF && int32View[3]==0xE0) {
                    alert("ok!");
                } else {
                    alert("only valid JPG images");
                    $("#form-id").get(0).reset(); //the tricky part is to "empty" the input file here I reset the form.
                    return;
                }
            };
            fileReader.readAsArrayBuffer(file);
        });
    });
</script>

Take in consideration that this was tested on latest versions of Firefox and Chrome, and on IExplore 10.

For a complete list of mime types see Wikipedia.

For a complete list of magic number see Wikipedia.

How to join entries in a set into one string?

You have the join statement backwards try:

print ', '.join(set_3)

Actual meaning of 'shell=True' in subprocess

The other answers here adequately explain the security caveats which are also mentioned in the subprocess documentation. But in addition to that, the overhead of starting a shell to start the program you want to run is often unnecessary and definitely silly for situations where you don't actually use any of the shell's functionality. Moreover, the additional hidden complexity should scare you, especially if you are not very familiar with the shell or the services it provides.

Where the interactions with the shell are nontrivial, you now require the reader and maintainer of the Python script (which may or may not be your future self) to understand both Python and shell script. Remember the Python motto "explicit is better than implicit"; even when the Python code is going to be somewhat more complex than the equivalent (and often very terse) shell script, you might be better off removing the shell and replacing the functionality with native Python constructs. Minimizing the work done in an external process and keeping control within your own code as far as possible is often a good idea simply because it improves visibility and reduces the risks of -- wanted or unwanted -- side effects.

Wildcard expansion, variable interpolation, and redirection are all simple to replace with native Python constructs. A complex shell pipeline where parts or all cannot be reasonably rewritten in Python would be the one situation where perhaps you could consider using the shell. You should still make sure you understand the performance and security implications.

In the trivial case, to avoid shell=True, simply replace

subprocess.Popen("command -with -options 'like this' and\\ an\\ argument", shell=True)

with

subprocess.Popen(['command', '-with','-options', 'like this', 'and an argument'])

Notice how the first argument is a list of strings to pass to execvp(), and how quoting strings and backslash-escaping shell metacharacters is generally not necessary (or useful, or correct). Maybe see also When to wrap quotes around a shell variable?

If you don't want to figure this out yourself, the shlex.split() function can do this for you. It's part of the Python standard library, but of course, if your shell command string is static, you can just run it once, during development, and paste the result into your script.

As an aside, you very often want to avoid Popen if one of the simpler wrappers in the subprocess package does what you want. If you have a recent enough Python, you should probably use subprocess.run.

  • With check=True it will fail if the command you ran failed.
  • With stdout=subprocess.PIPE it will capture the command's output.
  • With text=True (or somewhat obscurely, with the synonym universal_newlines=True) it will decode output into a proper Unicode string (it's just bytes in the system encoding otherwise, on Python 3).

If not, for many tasks, you want check_output to obtain the output from a command, whilst checking that it succeeded, or check_call if there is no output to collect.

I'll close with a quote from David Korn: "It's easier to write a portable shell than a portable shell script." Even subprocess.run('echo "$HOME"', shell=True) is not portable to Windows.