Programs & Examples On #Consensus

Setting up and using Meld as your git difftool and mergetool

For Windows 10 I had to put this in my .gitconfig:

[merge]
  tool = meld
[mergetool "meld"]
  cmd = 'C:/Program Files (x86)/Meld/Meld.exe' $LOCAL $BASE $REMOTE --output=$MERGED
[mergetool]
  prompt = false

Everything else you need to know is written in this super answer by mattst further above.

PS: For some reason, this only worked with Meld 3.18.x, Meld 3.20.x gives me an error.

Has Facebook sharer.php changed to no longer accept detailed parameters?

I review your url in use:

https://www.facebook.com/sharer/sharer.php?s=100&p[title]=EXAMPLE&p[summary]=EXAMPLE&p[url]=EXAMPLE&p[images][0]=EXAMPLE

and see this differences:

  1. The sharer URL not is same.
  2. The strings are in different order. ( Do not know if this affects ).

I use this URL string:

http://www.facebook.com/sharer.php?s=100&p[url]=http://www.example.com/&p[images][0]=/images/image.jpg&p[title]=Title&p[summary]=Summary

In the "title" and "summary" section, I use the php function urlencode(); like this:

<?php echo urlencode($detail->title); ?>

And working fine for me.

Are there any SHA-256 javascript implementations that are generally considered trustworthy?

Forge's SHA-256 implementation is fast and reliable.

To run tests on several SHA-256 JavaScript implementations, go to http://brillout.github.io/test-javascript-hash-implementations/.

The results on my machine suggests forge to be the fastest implementation and also considerably faster than the Stanford Javascript Crypto Library (sjcl) mentioned in the accepted answer.

Forge is 256 KB big, but extracting the SHA-256 related code reduces the size to 4.5 KB, see https://github.com/brillout/forge-sha256

Insertion sort vs Bubble Sort Algorithms

The main advantage of insert sort is that it's online algorithm. You don't have to have all the values at start. This could be useful, when dealing with data coming from network, or some sensor.

I have a feeling, that this would be faster than other conventional n log(n) algorithms. Because the complexity would be n*(n log(n)) e.g. reading/storing each value from stream (O(n)) and then sorting all the values (O(n log(n))) resulting in O(n^2 log(n))

On the contrary using Insert Sort needs O(n) for reading values from the stream and O(n) to put the value to the correct place, thus it's O(n^2) only. Other advantage is, that you don't need buffers for storing values, you sort them in the final destination.

How to update Python?

  • Official Python .msi installers are designed to replace:

    • any previous micro release (in x.y.z, z is "micro") because they are guaranteed to be backward-compatible and binary-compatible
    • a "snapshot" (built from source) installation with any micro version
  • A snapshot installer is designed to replace any snapshot with a lower micro version.

(See responsible code for 2.x, for 3.x)

Any other versions are not necessarily compatible and are thus installed alongside the existing one. If you wish to uninstall the old version, you'll need to do that manually. And also uninstall any 3rd-party modules you had for it:

  • If you installed any modules from bdist_wininst packages (Windows .exes), uninstall them before uninstalling the version, or the uninstaller might not work correctly if it has custom logic
  • modules installed with setuptools/pip that reside in Lib\site-packages can just be deleted afterwards
  • packages that you installed per-user, if any, reside in %APPDATA%/Python/PythonXY/site-packages and can likewise be deleted

How to display JavaScript variables in a HTML page without document.write

You can use javascript to access elements on the page and modify their contents. So for example you might have a page with some HTML markup like so:

<div id="MyEdit">
    This text will change
</div>

You can use javascript to change the content like so...

document.getElementById("MyEdit").innerHTML = "My new text!";?

Here is a working example


You can also look at using the JQuery javascript library for DOM manipulation, it has some great features to make things like this very easy.

For example, with JQuery, you could do this to acheive the same result...

$("#MyEdit").html("My new text!");

Here is a working example of the JQuery version


Based on this example you provided in your post. The following JQuery would work for you:

var x = "hello wolrd";
$("p").html(x);

Here is the working version

Using a P tag like this however is not recommended. You would ideally want to use an element with a unique ID so you can ensure you are selecting the correct one with JQuery.

How to semantically add heading to a list

Your first option is the good one. It's the least problematic one and you've already found the correct reasons why you couldn't use the other options.

By the way, your heading IS explicitly associated with the <ul> : it's right before the list! ;)

edit: Steve Faulkner, one of the editors of W3C HTML5 and 5.1 has sketched out a definition of an lt element. That's an unofficial draft that he'll discuss for HTML 5.2, nothing more yet.

Sorted array list in Java

I think the choice between SortedSets/Lists and 'normal' sortable collections depends, whether you need sorting only for presentation purposes or at almost every point during runtime. Using a sorted collection may be much more expensive because the sorting is done everytime you insert an element.

If you can't opt for a collection in the JDK, you can take a look at the Apache Commons Collections

Performance of FOR vs FOREACH in PHP

My personal opinion is to use what makes sense in the context. Personally I almost never use for for array traversal. I use it for other types of iteration, but foreach is just too easy... The time difference is going to be minimal in most cases.

The big thing to watch for is:

for ($i = 0; $i < count($array); $i++) {

That's an expensive loop, since it calls count on every single iteration. So long as you're not doing that, I don't think it really matters...

As for the reference making a difference, PHP uses copy-on-write, so if you don't write to the array, there will be relatively little overhead while looping. However, if you start modifying the array within the array, that's where you'll start seeing differences between them (since one will need to copy the entire array, and the reference can just modify inline)...

As for the iterators, foreach is equivalent to:

$it->rewind();
while ($it->valid()) {
    $key = $it->key();     // If using the $key => $value syntax
    $value = $it->current();

    // Contents of loop in here

    $it->next();
}

As far as there being faster ways to iterate, it really depends on the problem. But I really need to ask, why? I understand wanting to make things more efficient, but I think you're wasting your time for a micro-optimization. Remember, Premature Optimization Is The Root Of All Evil...

Edit: Based upon the comment, I decided to do a quick benchmark run...

$a = array();
for ($i = 0; $i < 10000; $i++) {
    $a[] = $i;
}

$start = microtime(true);
foreach ($a as $k => $v) {
    $a[$k] = $v + 1;
}
echo "Completed in ", microtime(true) - $start, " Seconds\n";

$start = microtime(true);
foreach ($a as $k => &$v) {
    $v = $v + 1;
}
echo "Completed in ", microtime(true) - $start, " Seconds\n";

$start = microtime(true);
foreach ($a as $k => $v) {}
echo "Completed in ", microtime(true) - $start, " Seconds\n";

$start = microtime(true);
foreach ($a as $k => &$v) {}    
echo "Completed in ", microtime(true) - $start, " Seconds\n";

And the results:

Completed in 0.0073502063751221 Seconds
Completed in 0.0019769668579102 Seconds
Completed in 0.0011849403381348 Seconds
Completed in 0.00111985206604 Seconds

So if you're modifying the array in the loop, it's several times faster to use references...

And the overhead for just the reference is actually less than copying the array (this is on 5.3.2)... So it appears (on 5.3.2 at least) as if references are significantly faster...

How line ending conversions work with git core.autocrlf between different operating systems

Things are about to change on the "eol conversion" front, with the upcoming Git 1.7.2:

A new config setting core.eol is being added/evolved:

This is a replacement for the 'Add "core.eol" config variable' commit that's currently in pu (the last one in my series).
Instead of implying that "core.autocrlf=true" is a replacement for "* text=auto", it makes explicit the fact that autocrlf is only for users who want to work with CRLFs in their working directory on a repository that doesn't have text file normalization.
When it is enabled, "core.eol" is ignored.

Introduce a new configuration variable, "core.eol", that allows the user to set which line endings to use for end-of-line-normalized files in the working directory.
It defaults to "native", which means CRLF on Windows and LF everywhere else. Note that "core.autocrlf" overrides core.eol.
This means that:

[core]
  autocrlf = true

puts CRLFs in the working directory even if core.eol is set to "lf".

core.eol:

Sets the line ending type to use in the working directory for files that have the text property set.
Alternatives are 'lf', 'crlf' and 'native', which uses the platform's native line ending.
The default value is native.


Other evolutions are being considered:

For 1.8, I would consider making core.autocrlf just turn on normalization and leave the working directory line ending decision to core.eol, but that will break people's setups.


git 2.8 (March 2016) improves the way core.autocrlf influences the eol:

See commit 817a0c7 (23 Feb 2016), commit 6e336a5, commit df747b8, commit df747b8 (10 Feb 2016), commit df747b8, commit df747b8 (10 Feb 2016), and commit 4b4024f, commit bb211b4, commit 92cce13, commit 320d39c, commit 4b4024f, commit bb211b4, commit 92cce13, commit 320d39c (05 Feb 2016) by Torsten Bögershausen (tboegi).
(Merged by Junio C Hamano -- gitster -- in commit c6b94eb, 26 Feb 2016)

convert.c: refactor crlf_action

Refactor the determination and usage of crlf_action.
Today, when no "crlf" attribute are set on a file, crlf_action is set to CRLF_GUESS. Use CRLF_UNDEFINED instead, and search for "text" or "eol" as before.

Replace the old CRLF_GUESS usage:

CRLF_GUESS && core.autocrlf=true -> CRLF_AUTO_CRLF
CRLF_GUESS && core.autocrlf=false -> CRLF_BINARY
CRLF_GUESS && core.autocrlf=input -> CRLF_AUTO_INPUT

Make more clear, what is what, by defining:

- CRLF_UNDEFINED : No attributes set. Temparally used, until core.autocrlf
                   and core.eol is evaluated and one of CRLF_BINARY,
                   CRLF_AUTO_INPUT or CRLF_AUTO_CRLF is selected
- CRLF_BINARY    : No processing of line endings.
- CRLF_TEXT      : attribute "text" is set, line endings are processed.
- CRLF_TEXT_INPUT: attribute "input" or "eol=lf" is set. This implies text.
- CRLF_TEXT_CRLF : attribute "eol=crlf" is set. This implies text.
- CRLF_AUTO      : attribute "auto" is set.
- CRLF_AUTO_INPUT: core.autocrlf=input (no attributes)
- CRLF_AUTO_CRLF : core.autocrlf=true  (no attributes)

As torek adds in the comments:

all these translations (any EOL conversion from eol= or autocrlf settings, and "clean" filters) are run when files move from work-tree to index, i.e., during git add rather than at git commit time.
(Note that git commit -a or --only or --include do add files to the index at that time, though.)

For more on that, see "What is difference between autocrlf and eol".

Apply CSS to jQuery Dialog Buttons

You should change the word "className" for "class"

buttons: [ 
    { 
        text: "Cancel",
        class: 'ui-state-default2', 
        click: function() { 
            $(this).dialog("close"); 
        } 
    }
],

What is the most accurate way to retrieve a user's correct IP address in PHP?

I know this is too late to answer. But you may try these options:

Option 1: (Using curl)

$ch = curl_init();

// set URL and other appropriate options
curl_setopt($ch, CURLOPT_URL, "https://ifconfig.me/");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

// grab URL and pass it to the browser
$ip = curl_exec($ch);

// close cURL resource, and free up system resources
curl_close($ch);

return $ip;

Option 2: (Works good on mac)

return trim(shell_exec("dig +short myip.opendns.com @resolver1.opendns.com"));

Option 3: (Just used a trick)

return str_replace('Current IP CheckCurrent IP Address: ', '', strip_tags(file_get_contents('http://checkip.dyndns.com')));

Might be a reference: https://www.tecmint.com/find-linux-server-public-ip-address/

The Definitive C Book Guide and List

Beginner

Introductory, no previous programming experience

  • C++ Primer * (Stanley Lippman, Josée Lajoie, and Barbara E. Moo) (updated for C++11) Coming at 1k pages, this is a very thorough introduction into C++ that covers just about everything in the language in a very accessible format and in great detail. The fifth edition (released August 16, 2012) covers C++11. [Review]

    * Not to be confused with C++ Primer Plus (Stephen Prata), with a significantly less favorable review.

  • Programming: Principles and Practice Using C++ (Bjarne Stroustrup, 2nd Edition - May 25, 2014) (updated for C++11/C++14) An introduction to programming using C++ by the creator of the language. A good read, that assumes no previous programming experience, but is not only for beginners.

Introductory, with previous programming experience

  • A Tour of C++ (Bjarne Stroustrup) (2nd edition for C++17) The “tour” is a quick (about 180 pages and 14 chapters) tutorial overview of all of standard C++ (language and standard library, and using C++11) at a moderately high level for people who already know C++ or at least are experienced programmers. This book is an extended version of the material that constitutes Chapters 2-5 of The C++ Programming Language, 4th edition.

  • Accelerated C++ (Andrew Koenig and Barbara Moo, 1st Edition - August 24, 2000) This basically covers the same ground as the C++ Primer, but does so on a fourth of its space. This is largely because it does not attempt to be an introduction to programming, but an introduction to C++ for people who've previously programmed in some other language. It has a steeper learning curve, but, for those who can cope with this, it is a very compact introduction to the language. (Historically, it broke new ground by being the first beginner's book to use a modern approach to teaching the language.) Despite this, the C++ it teaches is purely C++98. [Review]

Best practices

  • Effective C++ (Scott Meyers, 3rd Edition - May 22, 2005) This was written with the aim of being the best second book C++ programmers should read, and it succeeded. Earlier editions were aimed at programmers coming from C, the third edition changes this and targets programmers coming from languages like Java. It presents ~50 easy-to-remember rules of thumb along with their rationale in a very accessible (and enjoyable) style. For C++11 and C++14 the examples and a few issues are outdated and Effective Modern C++ should be preferred. [Review]

  • Effective Modern C++ (Scott Meyers) This is basically the new version of Effective C++, aimed at C++ programmers making the transition from C++03 to C++11 and C++14.

  • Effective STL (Scott Meyers) This aims to do the same to the part of the standard library coming from the STL what Effective C++ did to the language as a whole: It presents rules of thumb along with their rationale. [Review]


Intermediate

  • More Effective C++ (Scott Meyers) Even more rules of thumb than Effective C++. Not as important as the ones in the first book, but still good to know.

  • Exceptional C++ (Herb Sutter) Presented as a set of puzzles, this has one of the best and thorough discussions of the proper resource management and exception safety in C++ through Resource Acquisition is Initialization (RAII) in addition to in-depth coverage of a variety of other topics including the pimpl idiom, name lookup, good class design, and the C++ memory model. [Review]

  • More Exceptional C++ (Herb Sutter) Covers additional exception safety topics not covered in Exceptional C++, in addition to discussion of effective object-oriented programming in C++ and correct use of the STL. [Review]

  • Exceptional C++ Style (Herb Sutter) Discusses generic programming, optimization, and resource management; this book also has an excellent exposition of how to write modular code in C++ by using non-member functions and the single responsibility principle. [Review]

  • C++ Coding Standards (Herb Sutter and Andrei Alexandrescu) “Coding standards” here doesn't mean “how many spaces should I indent my code?” This book contains 101 best practices, idioms, and common pitfalls that can help you to write correct, understandable, and efficient C++ code. [Review]

  • C++ Templates: The Complete Guide (David Vandevoorde and Nicolai M. Josuttis) This is the book about templates as they existed before C++11. It covers everything from the very basics to some of the most advanced template metaprogramming and explains every detail of how templates work (both conceptually and at how they are implemented) and discusses many common pitfalls. Has excellent summaries of the One Definition Rule (ODR) and overload resolution in the appendices. A second edition covering C++11, C++14 and C++17 has been already published. [Review]

  • C++ 17 - The Complete Guide (Nicolai M. Josuttis) This book describes all the new features introduced in the C++17 Standard covering everything from the simple ones like 'Inline Variables', 'constexpr if' all the way up to 'Polymorphic Memory Resources' and 'New and Delete with overaligned Data'. [Review]

  • C++ in Action (Bartosz Milewski). This book explains C++ and its features by building an application from ground up. [Review]

  • Functional Programming in C++ (Ivan Cukic). This book introduces functional programming techniques to modern C++ (C++11 and later). A very nice read for those who want to apply functional programming paradigms to C++.

  • Professional C++ (Marc Gregoire, 5th Edition - Feb 2021) Provides a comprehensive and detailed tour of the C++ language implementation replete with professional tips and concise but informative in-text examples, emphasizing C++20 features. Uses C++20 features, such as modules and std::format throughout all examples.


Advanced

  • Modern C++ Design (Andrei Alexandrescu) A groundbreaking book on advanced generic programming techniques. Introduces policy-based design, type lists, and fundamental generic programming idioms then explains how many useful design patterns (including small object allocators, functors, factories, visitors, and multi-methods) can be implemented efficiently, modularly, and cleanly using generic programming. [Review]

  • C++ Template Metaprogramming (David Abrahams and Aleksey Gurtovoy)

  • C++ Concurrency In Action (Anthony Williams) A book covering C++11 concurrency support including the thread library, the atomics library, the C++ memory model, locks and mutexes, as well as issues of designing and debugging multithreaded applications. A second edition covering C++14 and C++17 has been already published. [Review]

  • Advanced C++ Metaprogramming (Davide Di Gennaro) A pre-C++11 manual of TMP techniques, focused more on practice than theory. There are a ton of snippets in this book, some of which are made obsolete by type traits, but the techniques, are nonetheless useful to know. If you can put up with the quirky formatting/editing, it is easier to read than Alexandrescu, and arguably, more rewarding. For more experienced developers, there is a good chance that you may pick up something about a dark corner of C++ (a quirk) that usually only comes about through extensive experience.


Reference Style - All Levels

  • The C++ Programming Language (Bjarne Stroustrup) (updated for C++11) The classic introduction to C++ by its creator. Written to parallel the classic K&R, this indeed reads very much like it and covers just about everything from the core language to the standard library, to programming paradigms to the language's philosophy. [Review] Note: All releases of the C++ standard are tracked in the question "Where do I find the current C or C++ standard documents?".

  • C++ Standard Library Tutorial and Reference (Nicolai Josuttis) (updated for C++11) The introduction and reference for the C++ Standard Library. The second edition (released on April 9, 2012) covers C++11. [Review]

  • The C++ IO Streams and Locales (Angelika Langer and Klaus Kreft) There's very little to say about this book except that, if you want to know anything about streams and locales, then this is the one place to find definitive answers. [Review]

C++11/14/17/… References:

  • The C++11/14/17 Standard (INCITS/ISO/IEC 14882:2011/2014/2017) This, of course, is the final arbiter of all that is or isn't C++. Be aware, however, that it is intended purely as a reference for experienced users willing to devote considerable time and effort to its understanding. The C++17 standard is released in electronic form for 198 Swiss Francs.

  • The C++17 standard is available, but seemingly not in an economical form – directly from the ISO it costs 198 Swiss Francs (about $200 US). For most people, the final draft before standardization is more than adequate (and free). Many will prefer an even newer draft, documenting new features that are likely to be included in C++20.

  • Overview of the New C++ (C++11/14) (PDF only) (Scott Meyers) (updated for C++14) These are the presentation materials (slides and some lecture notes) of a three-day training course offered by Scott Meyers, who's a highly respected author on C++. Even though the list of items is short, the quality is high.

  • The C++ Core Guidelines (C++11/14/17/…) (edited by Bjarne Stroustrup and Herb Sutter) is an evolving online document consisting of a set of guidelines for using modern C++ well. The guidelines are focused on relatively higher-level issues, such as interfaces, resource management, memory management and concurrency affecting application architecture and library design. The project was announced at CppCon'15 by Bjarne Stroustrup and others and welcomes contributions from the community. Most guidelines are supplemented with a rationale and examples as well as discussions of possible tool support. Many rules are designed specifically to be automatically checkable by static analysis tools.

  • The C++ Super-FAQ (Marshall Cline, Bjarne Stroustrup and others) is an effort by the Standard C++ Foundation to unify the C++ FAQs previously maintained individually by Marshall Cline and Bjarne Stroustrup and also incorporating new contributions. The items mostly address issues at an intermediate level and are often written with a humorous tone. Not all items might be fully up to date with the latest edition of the C++ standard yet.

  • cppreference.com (C++03/11/14/17/…) (initiated by Nate Kohl) is a wiki that summarizes the basic core-language features and has extensive documentation of the C++ standard library. The documentation is very precise but is easier to read than the official standard document and provides better navigation due to its wiki nature. The project documents all versions of the C++ standard and the site allows filtering the display for a specific version. The project was presented by Nate Kohl at CppCon'14.


Classics / Older

Note: Some information contained within these books may not be up-to-date or no longer considered best practice.

  • The Design and Evolution of C++ (Bjarne Stroustrup) If you want to know why the language is the way it is, this book is where you find answers. This covers everything before the standardization of C++.

  • Ruminations on C++ - (Andrew Koenig and Barbara Moo) [Review]

  • Advanced C++ Programming Styles and Idioms (James Coplien) A predecessor of the pattern movement, it describes many C++-specific “idioms”. It's certainly a very good book and might still be worth a read if you can spare the time, but quite old and not up-to-date with current C++.

  • Large Scale C++ Software Design (John Lakos) Lakos explains techniques to manage very big C++ software projects. Certainly, a good read, if it only was up to date. It was written long before C++ 98 and misses on many features (e.g. namespaces) important for large-scale projects. If you need to work in a big C++ software project, you might want to read it, although you need to take more than a grain of salt with it. The first volume of a new edition is released in 2019.

  • Inside the C++ Object Model (Stanley Lippman) If you want to know how virtual member functions are commonly implemented and how base objects are commonly laid out in memory in a multi-inheritance scenario, and how all this affects performance, this is where you will find thorough discussions of such topics.

  • The Annotated C++ Reference Manual (Bjarne Stroustrup, Margaret A. Ellis) This book is quite outdated in the fact that it explores the 1989 C++ 2.0 version - Templates, exceptions, namespaces and new casts were not yet introduced. Saying that however, this book goes through the entire C++ standard of the time explaining the rationale, the possible implementations, and features of the language. This is not a book to learn programming principles and patterns on C++, but to understand every aspect of the C++ language.

  • Thinking in C++ (Bruce Eckel, 2nd Edition, 2000). Two volumes; is a tutorial style free set of intro level books. Downloads: vol 1, vol 2. Unfortunately they're marred by a number of trivial errors (e.g. maintaining that temporaries are automatically const), with no official errata list. A partial 3rd party errata list is available at http://www.computersciencelab.com/Eckel.htm, but it is apparently not maintained.

  • Scientific and Engineering C++: An Introduction to Advanced Techniques and Examples (John Barton and Lee Nackman) It is a comprehensive and very detailed book that tried to explain and make use of all the features available in C++, in the context of numerical methods. It introduced at the time several new techniques, such as the Curiously Recurring Template Pattern (CRTP, also called Barton-Nackman trick). It pioneered several techniques such as dimensional analysis and automatic differentiation. It came with a lot of compilable and useful code, ranging from an expression parser to a Lapack wrapper. The code is still available online. Unfortunately, the books have become somewhat outdated in the style and C++ features, however, it was an incredible tour-de-force at the time (1994, pre-STL). The chapters on dynamics inheritance are a bit complicated to understand and not very useful. An updated version of this classic book that includes move semantics and the lessons learned from the STL would be very nice.

What is the best way to calculate a checksum for a file that is on my machine?

On MySQL.com, MD5s are listed alongside each file that you can download. For instance, MySQL "Windows Essentials" 5.1 is 528c89c37b3a6f0bd34480000a56c372.

You can download md5 (md5.exe), a command line tool that will calculate the MD5 of any file that you have locally. MD5 is just like any other cryptographic hash function, which means that a given array of bytes will always produce the same hash. That means if your downloaded MySQL zip file (or whatever) has the same MD5 as they post on their site, you have the exact same file.

What's the difference between an argument and a parameter?

They both dont have much difference in usage in C, both the terms are used in practice. Mostly arguments are often used with functions. The value passed with the function calling statement is called the argument, And the parameter would be the variable which copies the value in the function definition (called as formal parameter).

int main ()
{
   /* local variable definition */
   int a = 100;
   int b = 200;
   int ret;

   /* calling a function to get max value */
   ret = max(a, b);

   printf( "Max value is : %d\n", ret );

   return 0;
}

/* function returning the max between two numbers */
int max(int num1, int num2) 
{
   /* local variable declaration */
   int result;

   if (num1 > num2)
      result = num1;
   else
      result = num2;

   return result; 
}

In the above code num1 and num2 are formal parameters and a and b are actual arguments.

Should try...catch go inside or outside a loop?

If you put the try/catch inside the loop, you'll keep looping after an exception. If you put it outside the loop you'll stop as soon as an exception is thrown.

Forward declaring an enum in C++

Because the enum can be an integral size of varying size (the compiler decides which size a given enum has), the pointer to the enum can also have varying size, since it's an integral type (chars have pointers of a different size on some platforms for instance).

So the compiler can't even let you forward-declare the enum and user a pointer to it, because even there, it needs the size of the enum.

Is there a simple, elegant way to define singletons?

The Python documentation does cover this:

class Singleton(object):
    def __new__(cls, *args, **kwds):
        it = cls.__dict__.get("__it__")
        if it is not None:
            return it
        cls.__it__ = it = object.__new__(cls)
        it.init(*args, **kwds)
        return it
    def init(self, *args, **kwds):
        pass

I would probably rewrite it to look more like this:

class Singleton(object):
    """Use to create a singleton"""
    def __new__(cls, *args, **kwds):
        """
        >>> s = Singleton()
        >>> p = Singleton()
        >>> id(s) == id(p)
        True
        """
        self = "__self__"
        if not hasattr(cls, self):
            instance = object.__new__(cls)
            instance.init(*args, **kwds)
            setattr(cls, self, instance)
        return getattr(cls, self)

    def init(self, *args, **kwds):
        pass

It should be relatively clean to extend this:

class Bus(Singleton):
    def init(self, label=None, *args, **kwds):
        self.label = label
        self.channels = [Channel("system"), Channel("app")]
        ...

"error: assignment to expression with array type error" when I assign a struct field (C)

Please check this example here: Accessing Structure Members

There is explained that the right way to do it is like this:

strcpy(s1.name , "Egzona");
printf( "Name : %s\n", s1.name);

Check if null Boolean is true results in exception

as your variable bool is pointing to a null, you will always get a NullPointerException, you need to initialize the variable first somewhere with a not null value, and then modify it.

Error Code: 2013. Lost connection to MySQL server during query

Change "read time out" time in Edit->Preferences->SQL editor->MySQL session

bootstrap 4 file input doesn't show the file name

If you want you can use the recommended Bootstrap plugin to dynamize your custom file input: https://www.npmjs.com/package/bs-custom-file-input

This plugin can be use with or without jQuery and works with React an Angular

Oracle: If Table Exists

There is no 'DROP TABLE IF EXISTS' in oracle, you would have to do the select statement.

try this (i'm not up on oracle syntax, so if my variables are ify, please forgive me):

declare @count int
select @count=count(*) from all_tables where table_name='Table_name';
if @count>0
BEGIN
    DROP TABLE tableName;
END

jQuery override default validation error message display (Css) Popup/Tooltip like

Unfortunately I can't comment with my newbie reputation, but I have a solution for the issue of the screen going blank, or at least this is what worked for me. Instead of setting the wrapper class inside of the errorPlacement function, set it immediately when you're setting the wrapper type.

$('#myForm').validate({
    errorElement: "div",
    wrapper: "div class=\"message\"",
    errorPlacement: function(error, element) {
        offset = element.offset();
        error.insertBefore(element);
        //error.addClass('message');  // add a class to the wrapper
        error.css('position', 'absolute');
        error.css('left', offset.left + element.outerWidth() + 5);
        error.css('top', offset.top - 3);
    }

});

I'm assuming doing it this way allows the validator to know which div elements to remove, instead of all of them. Worked for me but I'm not entirely sure why, so if someone could elaborate that might help others out a ton.

Java Enum Methods - return opposite direction enum

Create an abstract method, and have each of your enumeration values override it. Since you know the opposite while you're creating it, there's no need to dynamically generate or create it.

It doesn't read nicely though; perhaps a switch would be more manageable?

public enum Direction {
    NORTH(1) {
        @Override
        public Direction getOppositeDirection() {
            return Direction.SOUTH;
        }
    },
    SOUTH(-1) {
        @Override
        public Direction getOppositeDirection() {
            return Direction.NORTH;
        }
    },
    EAST(-2) {
        @Override
        public Direction getOppositeDirection() {
            return Direction.WEST;
        }
    },
    WEST(2) {
        @Override
        public Direction getOppositeDirection() {
            return Direction.EAST;
        }
    };

    Direction(int code){
        this.code=code;
    }
    protected int code;

    public int getCode() {
        return this.code;
    }

    public abstract Direction getOppositeDirection();
}

pythonic way to do something N times without an index variable?

Use the _ variable, as I learned when I asked this question, for example:

# A long way to do integer exponentiation
num = 2
power = 3
product = 1
for _ in xrange(power):
    product *= num
print product

SSRS custom number format

Have you tried with the custom format "#,##0.##" ?

Change class on mouseover in directive

I think it would be much easier to put an anchor tag around i. You can just use the css :hover selector. Less moving parts makes maintenance easier, and less javascript to load makes the page quicker.

This will do the trick:

<style>
 a.icon-link:hover {
   background-color: pink;
 }
</style>

<a href="#" class="icon-link" id="course-0"><i class="icon-thumbsup"></id></a>

jsfiddle example

Link to Flask static files with url_for

In my case I had special instruction into nginx configuration file:

location ~ \.(js|css|png|jpg|gif|swf|ico|pdf|mov|fla|zip|rar)$ {
            try_files $uri =404;
    }

All clients have received '404' because nginx nothing known about Flask.

I hope it help someone.

Using variables inside strings

Up to C#5 (-VS2013) you have to call a function/method for it. Either a "normal" function such as String.Format or an overload of the + operator.

string str = "Hello " + name; // This calls an overload of operator +.

In C#6 (VS2015) string interpolation has been introduced (as described by other answers).

Making button go full-width?

You should add these styles to a CSS sheet

div .no-padding {
  padding:0;
}

button .full-width{
  width:100%;
  //display:block; //only if you're having issues
}

Then change add the classes to your code

<div class="span9 btn-block no-padding">
    <button class="btn btn-large btn-block btn-primary full-width" type="button">Block level button</button>
</div>

I haven't tested this and I'm not 100% sure what you want, but I think this will get you close.

How to make full screen background in a web page

I have followed this tutorial: https://css-tricks.com/perfect-full-page-background-image/

Specifically, the first Demo was the one that helped me out a lot!

CSS
 {
    background: url(images/bg.jpg) no-repeat center center fixed;
    -webkit-background-size: cover;
    -webkit-background-size: cover;
    -moz-background-size: cover;
    -o-background-size: cover;
    background-size: cover; 
}

this might help!

(Excel) Conditional Formatting based on Adjacent Cell Value

You need to take out the $ signs before the row numbers in the formula....and the row number used in the formula should correspond to the first row of data, so if you are applying this to the ("applies to") range $B$2:$B$5 it must be this formula

=$B2>$C2

by using that "relative" version rather than your "absolute" one Excel (implicitly) adjusts the formula for each row in the range, as if you were copying the formula down

How to print binary number via printf

printf() doesn't directly support that. Instead you have to make your own function.

Something like:

while (n) {
    if (n & 1)
        printf("1");
    else
        printf("0");

    n >>= 1;
}
printf("\n");

Difference between int32, int, int32_t, int8 and int8_t

Always keep in mind that 'size' is variable if not explicitly specified so if you declare

 int i = 10;

On some systems it may result in 16-bit integer by compiler and on some others it may result in 32-bit integer (or 64-bit integer on newer systems).

In embedded environments this may end up in weird results (especially while handling memory mapped I/O or may be consider a simple array situation), so it is highly recommended to specify fixed size variables. In legacy systems you may come across

 typedef short INT16;
 typedef int INT32;
 typedef long INT64; 

Starting from C99, the designers added stdint.h header file that essentially leverages similar typedefs.

On a windows based system, you may see entries in stdin.h header file as

 typedef signed char       int8_t;
 typedef signed short      int16_t;
 typedef signed int        int32_t;
 typedef unsigned char     uint8_t;

There is quite more to that like minimum width integer or exact width integer types, I think it is not a bad thing to explore stdint.h for a better understanding.

Get value from JToken that may not exist (best practices)

I would write GetValue as below

public static T GetValue<T>(this JToken jToken, string key, T defaultValue = default(T))
{
    dynamic ret = jToken[key];
    if (ret == null) return defaultValue;
    if (ret is JObject) return JsonConvert.DeserializeObject<T>(ret.ToString());
    return (T)ret;
}

This way you can get the value of not only the basic types but also complex objects. Here is a sample

public class ClassA
{
    public int I;
    public double D;
    public ClassB ClassB;
}
public class ClassB
{
    public int I;
    public string S;
}

var jt = JToken.Parse("{ I:1, D:3.5, ClassB:{I:2, S:'test'} }");

int i1 = jt.GetValue<int>("I");
double d1 = jt.GetValue<double>("D");
ClassB b = jt.GetValue<ClassB>("ClassB");

How to make HTTP Post request with JSON body in Swift

    // prepare json data
    let mapDict = [ "1":"First", "2":"Second"]

    let json = [ "title":"ABC" , "dict": mapDict ] as [String : Any]
    let jsonData : NSData = NSKeyedArchiver.archivedData(withRootObject: json) as NSData

    // create post request
    let url = NSURL(string: "http://httpbin.org/post")!
    let request = NSMutableURLRequest(url: url as URL)
    request.httpMethod = "POST"

    // insert json data to the request
    request.httpBody = jsonData as Data


    let task = URLSession.shared.dataTask(with: request as URLRequest){ data,response,error in
        if error != nil{
            return
        }
        do {
            let result = try JSONSerialization.jsonObject(with: data!, options: []) as? [String:AnyObject]

            print("Result",result!)

        } catch {
            print("Error -> \(error)")
        }
    }

    task.resume()

How to split a String by space

Here is a method to trim a String that has a "," or white space

private String shorterName(String s){
        String[] sArr = s.split("\\,|\\s+");
        String output = sArr[0];

        return output;
    }

How to add/update an attribute to an HTML element using JavaScript?

You can read here about the behaviour of attributes in many different browsers, including IE.

element.setAttribute() should do the trick, even in IE. Did you try it? If it doesn't work, then maybe element.attributeName = 'value' might work.

How do I encode a JavaScript object as JSON?

I think you can use JSON.stringify:

// after your each loop
JSON.stringify(values);

Android getText from EditText field

You can simply get the text in editText by applying below code:

EditText editText=(EditText)findViewById(R.id.vnosZadeve);
String text=editText.getText().toString();

then you can toast string text!

Happy coding!

Razor MVC Populating Javascript array with Model Array

To expand on the top-voted answer, for reference, if the you want to add more complex items to the array:

@:myArray.push(ClassMember1: "@d.ClassMember1", ClassMember2: "@d.ClassMember2");

etc.

Furthermore, if you want to pass the array as a parameter to your controller, you can stringify it first:

myArray = JSON.stringify({ 'myArray': myArray });

How to debug JavaScript / jQuery event bindings with Firebug or similar tools?

Using DevTools in the latest Chrome (v29) I find these two tips very helpful for debugging events:

  1. Listing jQuery events of the last selected DOM element

    • Inspect an element on the page
    • type the following in the console:

      $._data($0, "events") //assuming jQuery 1.7+

    • It will list all jQuery event objects associated with it, expand the interested event, right-click on the function of the "handler" property and choose "Show function definition". It will open the file containing the specified function.

  2. Utilizing the monitorEvents() command

How to stop line breaking in vim

I like that the long lines are displayed over more than one terminal line

This sort of visual/virtual line wrapping is enabled with the wrap window option:

set wrap

I don’t like that vim inserts newlines into my actual text.

To turn off physical line wrapping, clear both the textwidth and wrapmargin buffer options:

set textwidth=0 wrapmargin=0

How to make a boolean variable switch between true and false every time a method is invoked?

Without looking at it, set it to not itself. I don't know how to code it in Java, but in Objective-C I would say

booleanVariable = !booleanVariable;

This flips the variable.

Compare string with all values in list

I assume you mean list and not array? There is such a thing as an array in Python, but more often than not you want a list instead of an array.

The way to check if a list contains a value is to use in:

if paid[j] in d:
    # ...

Determine path of the executing script

I work in an HPC cluster environment. I develop my code in a different location from where I do my production runs. During development, I'm usually calling R interactively from the command line (not using RStudio). There is lots of source("foo.R") going on.

During production runs, I usually write a bash script that tries different parameters and runs each set of parameters in a separate directory. The bash script utilizes the workload manager (i.e. SLURM). In this environment, it is trivial to set an environmental variable. With this in mind, the below solution works best for me.

other.R

my_message <- function(){
return("R is awkward")
}

foo.R

srcpath = Sys.getenv("R_SRC")
# Check if runnning w/o setting R_SRC - presumably done in directory of development, i.e. /path/to/R/code
if(srcpath == ""){
    srcpath="./"
}
source(sprintf("%s/other.R", srcpath))
string = my_message()
print(string)

If running this from the R interactive shell and within /path/to/R/code, simply do

> source("foo.R")

If running not from the interactive shell and not running from /path/to/R/code, set the environmental variable R_SRC first, then call Rscript

$ export R_SRC=/path/to/R/code/
$ Rscript /path/to/R/code/foo.R

Convert INT to FLOAT in SQL

In oracle db there is a trick for casting int to float (I suppose, it should also work in mysql):

select myintfield + 0.0 as myfloatfield from mytable

While @Heximal's answer works, I don't personally recommend it.

This is because it uses implicit casting. Although you didn't type CAST, either the SUM() or the 0.0 need to be cast to be the same data-types, before the + can happen. In this case the order of precedence is in your favour, and you get a float on both sides, and a float as a result of the +. But SUM(aFloatField) + 0 does not yield an INT, because the 0 is being implicitly cast to a FLOAT.

I find that in most programming cases, it is much preferable to be explicit. Don't leave things to chance, confusion, or interpretation.

If you want to be explicit, I would use the following.

CAST(SUM(sl.parts) AS FLOAT) * cp.price
-- using MySQL CAST FLOAT  requires 8.0

I won't discuss whether NUMERIC or FLOAT *(fixed point, instead of floating point)* is more appropriate, when it comes to rounding errors, etc. I'll just let you google that if you need to, but FLOAT is so massively misused that there is a lot to read about the subject already out there.

You can try the following to see what happens...

CAST(SUM(sl.parts) AS NUMERIC(10,4)) * CAST(cp.price AS NUMERIC(10,4))

Postgres: check if array field contains value?

This worked for me:

select * from mytable
where array_to_string(pub_types, ',') like '%Journal%'

Depending on your normalization needs, it might be better to implement a separate table with a FK reference as you may get better performance and manageability.

Google Maps JavaScript API RefererNotAllowedMapError

The Problem
Google suggestions the format *.example.com/*
This format does not work.

The Solution
Check the browser console for the Google Maps JavaScript API error: RefererNotAllowedMapError
Underneath the error it should have: "Your site URL to be authorized: https://example.com/".
Use that url for the referrer and add a wildcard * to the end of it (https://example.com/*, in this case).

How would I extract a single file (or changes to a file) from a git stash?

If you use git stash apply rather than git stash pop, it will apply the stash to your working tree but still keep the stash.

With this done, you can add/commit the file that you want and then reset the remaining changes.

Easiest way to activate PHP and MySQL on Mac OS 10.6 (Snow Leopard), 10.7 (Lion), 10.8 (Mountain Lion)?

I would agree with Benjamin, either install MAMP or MacPorts (http://www.macports.org/). Keeping your PHP install separate is simpler and avoids messing up the core PHP install if you make any mistakes!

MacPorts is a bit better for installing other software, such as ImageMagick. See a full list of available ports at http://www.macports.org/ports.php

MAMP just really does PHP, Apache and MySQL so any future PHP modules you want will need to be manually enabled. It is incredibly easy to use though.

Remove Primary Key in MySQL

In case you have composite primary key, do like this- ALTER TABLE table_name DROP PRIMARY KEY,ADD PRIMARY KEY (col_name1, col_name2);

How do I check if file exists in Makefile so I can delete it?

It's strange to see so many people using shell scripting for this. I was looking for a way to use native makefile syntax, because I'm writing this outside of any target. You can use the wildcard function to check if file exists:

 ifeq ($(UNAME),Darwin)
     SHELL := /opt/local/bin/bash
     OS_X  := true
 else ifneq (,$(wildcard /etc/redhat-release))
     OS_RHEL := true
 else
     OS_DEB  := true
     SHELL := /bin/bash
 endif 

Update:

I found a way which is really working for me:

ifneq ("$(wildcard $(PATH_TO_FILE))","")
    FILE_EXISTS = 1
else
    FILE_EXISTS = 0
endif

Unstage a deleted file in git

From manual page,

git-reset - Reset current HEAD to the specified state
git reset [-q] [<tree-ish>] [--] <paths>...
In the first and second form, copy entries from <tree-ish> to the index.

for example, when we use git reset HEAD~1 it reset our current HEAD to HEAD~1

so when we use git reset 'some-deleted-file-path'

git assume 'some-deleted-file-path' as some commit point and try to reset out current HEAD to there.

And it ends up fail

fatal: ambiguous argument 'some-deleted-file-path': unknown revision or path not in the working tree.

Message Queue vs. Web Services?

There's been a fair amount of recent research in considering how REST HTTP calls could replace the message queue concept.

If you introduce the concept of a process and a task as a resource, the need for middle messaging layer starts to evaporate.

Ex:

POST /task/name
    - Returns a 202 accepted status immediately
    - Returns a resource url for the created task: /task/name/X
    - Returns a resource url for the started process: /process/Y

GET /process/Y
    - Returns status of ongoing process

A task can have multiple steps for initialization, and a process can return status when polled or POST to a callback URL when complete.

This is dead simple, and becomes quite powerful when you realize that you can now subscribe to an rss/atom feed of all running processes and tasks without any middle layer. Any queuing system is going to require some sort of web front end anyway, and this concept has it built in without another layer of custom code.

Your resources exist until you delete them, which means you can view historical information long after the process and task complete.

You have built in service discovery, even for a task that has multiple steps, without any extra complicated protocols.

GET /task/name
    - returns form with required fields

POST (URL provided form's "action" attribute)

Your service discovery is an HTML form - a universal and human readable format.

The entire flow can be used programmatically or by a human, using universally accepted tools. It's a client driven, and therefore RESTful. Every tool created for the web can drive your business processes. You still have alternate message channels by POSTing asynchronously to a separate array of log servers.

After you consider it for a while, you sit back and start to realize that REST may just eliminate the need for a messaging queue and an ESB altogether.

http://www.infoq.com/presentations/BPM-with-REST

HighCharts Hide Series Name from the Legend

Looks like HighChart 2.2.0 has resolved this issue. I tried it here with the same code you have, and the first series is hidden now. Could you try it with HighChart 2.2.0?

Change button background color using swift language

After you connect the UIButton that you want to change its background as an OUtlet to your ViewController.swift file you can use the following:

 yourUIButton.backgroundColor = UIColor.blue

Using Predicate in Swift

This is really just a syntax switch. OK, so we have this method call:

[NSPredicate predicateWithFormat:@"name contains[c] %@", searchText];

In Swift, constructors skip the "blahWith…" part and just use the class name as a function and then go straight to the arguments, so [NSPredicate predicateWithFormat: …] would become NSPredicate(format: …). (For another example, [NSArray arrayWithObject: …] would become NSArray(object: …). This is a regular pattern in Swift.)

So now we just need to pass the arguments to the constructor. In Objective-C, NSString literals look like @"", but in Swift we just use quotation marks for strings. So that gives us:

let resultPredicate = NSPredicate(format: "name contains[c] %@", searchText)

And in fact that is exactly what we need here.

(Incidentally, you'll notice some of the other answers instead use a format string like "name contains[c] \(searchText)". That is not correct. That uses string interpolation, which is different from predicate formatting and will generally not work for this.)

Accessing constructor of an anonymous class

Yes , It is right that you can not define construct in an Anonymous class but it doesn't mean that anonymous class don't have constructor. Confuse... Actually you can not define construct in an Anonymous class but compiler generates an constructor for it with the same signature as its parent constructor called. If the parent has more than one constructor, the anonymous will have one and only one constructor

how to exit a python script in an if statement

This works fine for me:

while True:
   answer = input('Do you want to continue?:')
   if answer.lower().startswith("y"):
      print("ok, carry on then")
   elif answer.lower().startswith("n"):
      print("sayonara, Robocop")
      exit()

edit: use input in python 3.2 instead of raw_input

Matplotlib tight_layout() doesn't take into account figure suptitle

This website has a simple solution to this with an example that worked for me. The line of code that does the actual leaving of space for the title is the following:

plt.tight_layout(rect=[0, 0, 1, 0.95]) 

Here is an image of proof that it worked for me: Image Link

Avoid browser popup blockers

Based on Jason Sebring's very useful tip, and on the stuff covered here and there, I found a perfect solution for my case:

Pseudo code with Javascript snippets:

  1. immediately create a blank popup on user action

     var importantStuff = window.open('', '_blank');
    

    (Enrich the call to window.open with whatever additional options you need.)

    Optional: add some "waiting" info message. Examples:

    a) An external HTML page: replace the above line with

     var importantStuff = window.open('http://example.com/waiting.html', '_blank');
    

    b) Text: add the following line below the above one:

     importantStuff.document.write('Loading preview...');
    
  2. fill it with content when ready (when the AJAX call is returned, for instance)

     importantStuff.location.href = 'https://example.com/finally.html';
    

    Alternatively, you could close the window here if you don't need it after all (if ajax request fails, for example - thanks to @Goose for the comment):

     importantStuff.close();
    

I actually use this solution for a mailto redirection, and it works on all my browsers (windows 7, Android). The _blank bit helps for the mailto redirection to work on mobile, btw.

When increasing the size of VARCHAR column on a large table could there be any problems?

This is a metadata change only: it is quick.

An observation: specify NULL or NOT NULL explicitly to avoid "accidents" if one of the SET ANSI_xx settings are different eg run in osql not SSMS for some reason

How do I get a YouTube video thumbnail from the YouTube API?

    function get_video_thumbnail( $src ) {
            $url_pieces = explode('/', $src);
            if( $url_pieces[2] == 'dai.ly'){
                $id = $url_pieces[3];
                $hash = json_decode(file_get_contents('https://api.dailymotion.com/video/'.$id.'?fields=thumbnail_large_url'), TRUE);
                $thumbnail = $hash['thumbnail_large_url'];
            }else if($url_pieces[2] == 'www.dailymotion.com'){
                $id = $url_pieces[4];
                $hash = json_decode(file_get_contents('https://api.dailymotion.com/video/'.$id.'?fields=thumbnail_large_url'), TRUE);
                $thumbnail = $hash['thumbnail_large_url'];
            }else if ( $url_pieces[2] == 'vimeo.com' ) { // If Vimeo
                $id = $url_pieces[3];
                $hash = unserialize(file_get_contents('http://vimeo.com/api/v2/video/' . $id . '.php'));
                $thumbnail = $hash[0]['thumbnail_large'];
            } elseif ( $url_pieces[2] == 'youtu.be' ) { // If Youtube
                $extract_id = explode('?', $url_pieces[3]);
                $id = $extract_id[0];
                $thumbnail = 'http://img.youtube.com/vi/' . $id . '/mqdefault.jpg';
            }else if ( $url_pieces[2] == 'player.vimeo.com' ) { // If Vimeo
                $id = $url_pieces[4];
                $hash = unserialize(file_get_contents('http://vimeo.com/api/v2/video/' . $id . '.php'));
                $thumbnail = $hash[0]['thumbnail_large'];
            } elseif ( $url_pieces[2] == 'www.youtube.com' ) { // If Youtube
                $extract_id = explode('=', $url_pieces[3]);
                $id = $extract_id[1];
                $thumbnail = 'http://img.youtube.com/vi/' . $id . '/mqdefault.jpg';
            } else{
                $thumbnail = tim_thumb_default_image('video-icon.png', null, 147, 252);
            }
            return $thumbnail;
        }

get_video_thumbnail('https://vimeo.com/154618727');
get_video_thumbnail('https://www.youtube.com/watch?v=SwU0I7_5Cmc');
get_video_thumbnail('https://youtu.be/pbzIfnekjtM');
get_video_thumbnail('http://www.dailymotion.com/video/x5thjyz');

What are the differences between char literals '\n' and '\r' in Java?

When you print a string in console(Eclipse),\n,\r and \r\n have the same effect,all of them will give you a new line;but \n\r(also \n\n,\r\r) will give you two new lines;when you write a string to a file,only \r\n can give you a new line.

How can I remove text within parentheses with a regex?

If you don't absolutely need to use a regex, useconsider using Perl's Text::Balanced to remove the parenthesis.

use Text::Balanced qw(extract_bracketed);

my ($extracted, $remainder, $prefix) = extract_bracketed( $filename, '()', '[^(]*' );

{   no warnings 'uninitialized';

    $filename = (defined $prefix or defined $remainder)
                ? $prefix . $remainder
                : $extracted;
}

You may be thinking, "Why do all this when a regex does the trick in one line?"

$filename =~ s/\([^}]*\)//;

Text::Balanced handles nested parenthesis. So $filename = 'foo_(bar(baz)buz)).foo' will be extracted properly. The regex based solutions offered here will fail on this string. The one will stop at the first closing paren, and the other will eat them all.

   $filename =~ s/\([^}]*\)//;
   # returns 'foo_buz)).foo'

   $filename =~ s/\(.*\)//;
   # returns 'foo_.foo'

   # text balanced example returns 'foo_).foo'

If either of the regex behaviors is acceptable, use a regex--but document the limitations and the assumptions being made.

How to drop columns using Rails migration

Generate a migration to remove a column such that if it is migrated (rake db:migrate), it should drop the column. And it should add column back if this migration is rollbacked (rake db:rollback).

The syntax:

remove_column :table_name, :column_name, :type

Removes column, also adds column back if migration is rollbacked.

Example:

remove_column :users, :last_name, :string

Note: If you skip the data_type, the migration will remove the column successfully but if you rollback the migration it will throw an error.

How to use LocalBroadcastManager?

enter code here if (createSuccses){
                        val userDataChange=Intent(BRODCAST_USER_DATA_CHANGE)
                        LocalBroadcastManager.getInstance(this).sendBroadcast(
                            userDataChange
                        )
                        enableSpinner(false)
                        finish()

How do I load the contents of a text file into a javascript variable?

If you only want a constant string from the text file, you could include it as JavaScript:

_x000D_
_x000D_
// This becomes the content of your foo.txt file_x000D_
let text = `_x000D_
My test text goes here!_x000D_
`;
_x000D_
<script src="foo.txt"></script>_x000D_
<script>_x000D_
  console.log(text);_x000D_
</script>
_x000D_
_x000D_
_x000D_

The string loaded from the file becomes accessible to JavaScript after being loaded. The `(backtick) character begins and ends a template literal, allowing for both " and ' characters in your text block.

This approach works well when you're attempting to load a file locally, as Chrome will not allow AJAX on URLs with the file:// scheme.

Read and write a text file in typescript

import * as fs from 'fs';
import * as path from 'path';

fs.readFile(path.join(__dirname, "filename.txt"), (err, data) => {
    if (err) throw err;
    console.log(data);
})

EDIT:

consider the project structure:

../readfile/
+-- filename.txt
+-- src
    +-- index.js
    +-- index.ts

consider the index.ts:

import * as fs from 'fs';
import * as path from 'path';

function lookFilesInDirectory(path_directory) {
    fs.stat(path_directory, (err, stat) => {
        if (!err) {
            if (stat.isDirectory()) {
                console.log(path_directory)
                fs.readdirSync(path_directory).forEach(file => {
                    console.log(`\t${file}`);
                });
                console.log();
            }
        }
    });
}

let path_view = './';
lookFilesInDirectory(path_view);
lookFilesInDirectory(path.join(__dirname, path_view));

if you have in the readfile folder and run tsc src/index.ts && node src/index.js, the output will be:

./
        filename.txt
        src

/home/andrei/scripts/readfile/src/
        index.js
        index.ts

that is, it depends on where you run the node.

the __dirname is directory name of the current module.

MongoDB distinct aggregation

Distinct and the aggregation framework are not inter-operable.

Instead you just want:

db.zips.aggregate([ 
    {$group:{_id:{city:'$city', state:'$state'}, numberOfzipcodes:{$sum:1}}}, 
    {$sort:{numberOfzipcodes:-1}},
    {$group:{_id:'$_id.state', city:{$first:'$_id.city'}, 
              numberOfzipcode:{$first:'$numberOfzipcodes'}}}
]);

What is the purpose of class methods?

Honestly? I've never found a use for staticmethod or classmethod. I've yet to see an operation that can't be done using a global function or an instance method.

It would be different if python used private and protected members more like Java does. In Java, I need a static method to be able to access an instance's private members to do stuff. In Python, that's rarely necessary.

Usually, I see people using staticmethods and classmethods when all they really need to do is use python's module-level namespaces better.

os.walk without digging into directories below

Since Python 3.5 you can use os.scandir instead of os.listdir. Instead of strings you get an iterator of DirEntry objects in return. From the docs:

Using scandir() instead of listdir() can significantly increase the performance of code that also needs file type or file attribute information, because DirEntry objects expose this information if the operating system provides it when scanning a directory. All DirEntry methods may perform a system call, but is_dir() and is_file() usually only require a system call for symbolic links; DirEntry.stat() always requires a system call on Unix but only requires one for symbolic links on Windows.

You can access the name of the object via DirEntry.name which is then equivalent to the output of os.listdir

Can Android do peer-to-peer ad-hoc networking?

Your answer is Wi-Fi direct which is made available with ICS. Here is a link for explanation in Android doc

How to get year and month from a date - PHP

You can use this code:

$dateValue = strtotime('2012-06-05');
$year = date('Y',$dateValue);
$monthName = date('F',$dateValue);
$monthNo = date('m',$dateValue);
printf("m=[%s], m=[%d], y=[%s]\n", $monthName, $monthNo, $year);

Git error: src refspec master does not match any

You've created a new repository and added some files to the index, but you haven't created your first commit yet. After you've done:

 git add a_text_file.txt 

... do:

 git commit -m "Initial commit."

... and those errors should go away.

What REST PUT/POST/DELETE calls should return by a convention?

Forgive the flippancy, but if you are doing REST over HTTP then RFC7231 describes exactly what behaviour is expected from GET, PUT, POST and DELETE.

Update (Jul 3 '14):
The HTTP spec intentionally does not define what is returned from POST or DELETE. The spec only defines what needs to be defined. The rest is left up to the implementer to choose.

Blur effect on a div element

Try using this library: https://github.com/jakiestfu/Blur.js-II

That should do it for ya.

how to avoid a new line with p tag?

Use the display: inline CSS property.

Ideal: In the stylesheet:

#container p { display: inline }

Bad/Extreme situation: Inline:

<p style="display:inline">...</p>

How to get week number of the month from the date in sql server 2008

Here is the tried and tested solution for this query in any situation - like if 1st of the month is on Friday , then also this will work -

select (DATEPART(wk,@date_given)-DATEPART(wk,dateadd(d,1-day(@date_given),@date_given)))+1

above are some solutions which will fail if the month's first date is on Friday , then 4th will be 2nd week of the month

Unit testing private methods in C#

You can use PrivateObject Class

Class target = new Class();
PrivateObject obj = new PrivateObject(target);
var retVal = obj.Invoke("PrivateMethod");
Assert.AreEqual(expectedVal, retVal);

Note: PrivateObject and PrivateType are not available for projects targeting netcoreapp2.0 - GitHub Issue 366

How to read .pem file to get private and public key

Try this class.

package groovy;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.GeneralSecurityException;
import java.security.InvalidKeyException;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Signature;
import java.security.SignatureException;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;

import javax.crypto.Cipher;

import org.apache.commons.codec.binary.Base64;

public class RSA {

private static String getKey(String filename) throws IOException {
    // Read key from file
    String strKeyPEM = "";
    BufferedReader br = new BufferedReader(new FileReader(filename));
    String line;
    while ((line = br.readLine()) != null) {
        strKeyPEM += line + "\n";
    }
    br.close();
    return strKeyPEM;
}
public static RSAPrivateKey getPrivateKey(String filename) throws IOException, GeneralSecurityException {
    String privateKeyPEM = getKey(filename);
    return getPrivateKeyFromString(privateKeyPEM);
}

public static RSAPrivateKey getPrivateKeyFromString(String key) throws IOException, GeneralSecurityException {
    String privateKeyPEM = key;
    privateKeyPEM = privateKeyPEM.replace("-----BEGIN PRIVATE KEY-----\n", "");
    privateKeyPEM = privateKeyPEM.replace("-----END PRIVATE KEY-----", "");
    byte[] encoded = Base64.decodeBase64(privateKeyPEM);
    KeyFactory kf = KeyFactory.getInstance("RSA");
    PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(encoded);
    RSAPrivateKey privKey = (RSAPrivateKey) kf.generatePrivate(keySpec);
    return privKey;
}


public static RSAPublicKey getPublicKey(String filename) throws IOException, GeneralSecurityException {
    String publicKeyPEM = getKey(filename);
    return getPublicKeyFromString(publicKeyPEM);
}

public static RSAPublicKey getPublicKeyFromString(String key) throws IOException, GeneralSecurityException {
    String publicKeyPEM = key;
    publicKeyPEM = publicKeyPEM.replace("-----BEGIN PUBLIC KEY-----\n", "");
    publicKeyPEM = publicKeyPEM.replace("-----END PUBLIC KEY-----", "");
    byte[] encoded = Base64.decodeBase64(publicKeyPEM);
    KeyFactory kf = KeyFactory.getInstance("RSA");
    RSAPublicKey pubKey = (RSAPublicKey) kf.generatePublic(new X509EncodedKeySpec(encoded));
    return pubKey;
}

public static String sign(PrivateKey privateKey, String message) throws NoSuchAlgorithmException, InvalidKeyException, SignatureException, UnsupportedEncodingException {
    Signature sign = Signature.getInstance("SHA1withRSA");
    sign.initSign(privateKey);
    sign.update(message.getBytes("UTF-8"));
    return new String(Base64.encodeBase64(sign.sign()), "UTF-8");
}


public static boolean verify(PublicKey publicKey, String message, String signature) throws SignatureException, NoSuchAlgorithmException, UnsupportedEncodingException, InvalidKeyException {
    Signature sign = Signature.getInstance("SHA1withRSA");
    sign.initVerify(publicKey);
    sign.update(message.getBytes("UTF-8"));
    return sign.verify(Base64.decodeBase64(signature.getBytes("UTF-8")));
}

public static String encrypt(String rawText, PublicKey publicKey) throws IOException, GeneralSecurityException {
    Cipher cipher = Cipher.getInstance("RSA");
    cipher.init(Cipher.ENCRYPT_MODE, publicKey);
    return Base64.encodeBase64String(cipher.doFinal(rawText.getBytes("UTF-8")));
}

public static String decrypt(String cipherText, PrivateKey privateKey) throws IOException, GeneralSecurityException {
    Cipher cipher = Cipher.getInstance("RSA");
    cipher.init(Cipher.DECRYPT_MODE, privateKey);
    return new String(cipher.doFinal(Base64.decodeBase64(cipherText)), "UTF-8");
}
}


Required jar library "common-codec-1.6"

remove first element from array and return the array minus the first element

This can be done in one line with lodash _.tail:

_x000D_
_x000D_
var arr = ["item 1", "item 2", "item 3", "item 4"];_x000D_
console.log(_.tail(arr));
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>
_x000D_
_x000D_
_x000D_

How do I specify "close existing connections" in sql script

According to the ALTER DATABASE SET documentation, there is still a possibility that after setting a database to SINGLE_USER mode you won't be able to access that database:

Before you set the database to SINGLE_USER, verify the AUTO_UPDATE_STATISTICS_ASYNC option is set to OFF. When set to ON, the background thread used to update statistics takes a connection against the database, and you will be unable to access the database in single-user mode.

So, a complete script to drop the database with existing connections may look like this:

DECLARE @dbId int
DECLARE @isStatAsyncOn bit
DECLARE @jobId int
DECLARE @sqlString nvarchar(500)

SELECT @dbId = database_id,
       @isStatAsyncOn = is_auto_update_stats_async_on
FROM sys.databases
WHERE name = 'db_name'

IF @isStatAsyncOn = 1
BEGIN
    ALTER DATABASE [db_name] SET  AUTO_UPDATE_STATISTICS_ASYNC OFF

    -- kill running jobs
    DECLARE jobsCursor CURSOR FOR
    SELECT job_id
    FROM sys.dm_exec_background_job_queue
    WHERE database_id = @dbId

    OPEN jobsCursor

    FETCH NEXT FROM jobsCursor INTO @jobId
    WHILE @@FETCH_STATUS = 0
    BEGIN
        set @sqlString = 'KILL STATS JOB ' + STR(@jobId)
        EXECUTE sp_executesql @sqlString
        FETCH NEXT FROM jobsCursor INTO @jobId
    END

    CLOSE jobsCursor
    DEALLOCATE jobsCursor
END

ALTER DATABASE [db_name] SET  SINGLE_USER WITH ROLLBACK IMMEDIATE

DROP DATABASE [db_name]

Loop through files in a folder using VBA?

Try this one. (LINK)

Private Sub CommandButton3_Click()

Dim FileExtStr As String
Dim FileFormatNum As Long
Dim xWs As Worksheet
Dim xWb As Workbook
Dim FolderName As String
Application.ScreenUpdating = False
Set xWb = Application.ThisWorkbook
DateString = Format(Now, "yyyy-mm-dd hh-mm-ss")
FolderName = xWb.Path & "\" & xWb.Name & " " & DateString
MkDir FolderName
For Each xWs In xWb.Worksheets
    xWs.Copy
    If Val(Application.Version) < 12 Then
        FileExtStr = ".xls": FileFormatNum = -4143
    Else
        Select Case xWb.FileFormat
            Case 51:
                FileExtStr = ".xlsx": FileFormatNum = 51
            Case 52:
                If Application.ActiveWorkbook.HasVBProject Then
                    FileExtStr = ".xlsm": FileFormatNum = 52
                Else
                    FileExtStr = ".xlsx": FileFormatNum = 51
                End If
            Case 56:
                FileExtStr = ".xls": FileFormatNum = 56
            Case Else:
                FileExtStr = ".xlsb": FileFormatNum = 50
        End Select
    End If
    xFile = FolderName & "\" & Application.ActiveWorkbook.Sheets(1).Name & FileExtStr
    Application.ActiveWorkbook.SaveAs xFile, FileFormat:=FileFormatNum
    Application.ActiveWorkbook.Close False
Next
MsgBox "You can find the files in " & FolderName
Application.ScreenUpdating = True

End Sub

MySQL INSERT INTO ... VALUES and SELECT

 
INSERT INTO table_name1
            (id,
             name,
             address,
             contact_number) 
SELECT id, name, address, contact_number FROM table_name2;   

Please enter a commit message to explain why this merge is necessary, especially if it merges an updated upstream into a topic branch

Actually it's not an error! It means you should enter some message to mark this merge. My OS is Ubuntu 14.04.If you use the same OS, you just need to do this as follows:

  1. Type some message

  2. CtrlCO

  3. Type the file name (such as "Merge_feature01") and press Enter

  4. CtrlX to exit

Now if you go to .git and you will find the file "Merge_feature01", that's the merge log actually.

How do I get specific properties with Get-AdUser

using select-object for example:

Get-ADUser -Filter * -SearchBase 'OU=Users & Computers, DC=aaaaaaa, DC=com' -Properties DisplayName | select -expand displayname | Export-CSV "ADUsers.csv" 

Why use pointers?

In java and C# all the object references are pointers, the thing with c++ is that you have more control on where you pointer points. Remember With great power comes grand responsibility.

error: expected declaration or statement at end of input in c

For me this problem was caused by a missing ) at the end of an if statement in a function called by the function the error was reported as from. Try scrolling up in the output to find the first error reported by the compiler. Fixing that error may fix this error.

A Generic error occurred in GDI+ in Bitmap.Save method

from msdn: public void Save (string filename); which is quite surprising to me because we dont just have to pass in the filename, we have to pass the filename along with the path for example: MyDirectory/MyImage.jpeg, here MyImage.jpeg does not actually exist yet, but our file will be saved with this name.

Another important point here is that if you are using Save() in a web application then use Server.MapPath() along with it which basically just returns the physical path for the virtual path which is passed in. Something like: image.Save(Server.MapPath("~/images/im111.jpeg"));

Could not load file or assembly 'System.Web.WebPages.Razor, Version=2.0.0.0

So simple. In Nuget Package Manager Console:

Update-Package Microsoft.AspNet.Mvc -Reinstall

Visual Studio Code PHP Intelephense Keep Showing Not Necessary Error

Intelephense 1.3 added undefined type, function, constant, class constant, method, and property diagnostics, where previously in 1.2 there was only undefined variable diagnostics.

Some frameworks are written in a way that provide convenient shortcuts for the user but make it difficult for static analysis engines to discover symbols that are available at runtime.

Stub generators like https://github.com/barryvdh/laravel-ide-helper help fill the gap here and using this with Laravel will take care of many of the false diagnostics by providing concrete definitions of symbols that can be easily discovered.

Still, PHP is a very flexible language and there may be other instances of false undefined symbols depending on how code is written. For this reason, since 1.3.3, intelephense has config options to enable/disable each category of undefined symbol to suit the workspace and coding style.

These options are: intelephense.diagnostics.undefinedTypes intelephense.diagnostics.undefinedFunctions intelephense.diagnostics.undefinedConstants intelephense.diagnostics.undefinedClassConstants intelephense.diagnostics.undefinedMethods intelephense.diagnostics.undefinedProperties intelephense.diagnostics.undefinedVariables

Setting all of these to false except intelephense.diagnostics.undefinedVariables will give version 1.2 behaviour. See the VSCode settings UI and search for intelephense.

How to connect HTML Divs with Lines?

I made something like this to my project

_x000D_
_x000D_
function adjustLine(from, to, line){_x000D_
_x000D_
  var fT = from.offsetTop  + from.offsetHeight/2;_x000D_
  var tT = to.offsetTop    + to.offsetHeight/2;_x000D_
  var fL = from.offsetLeft + from.offsetWidth/2;_x000D_
  var tL = to.offsetLeft   + to.offsetWidth/2;_x000D_
  _x000D_
  var CA   = Math.abs(tT - fT);_x000D_
  var CO   = Math.abs(tL - fL);_x000D_
  var H    = Math.sqrt(CA*CA + CO*CO);_x000D_
  var ANG  = 180 / Math.PI * Math.acos( CA/H );_x000D_
_x000D_
  if(tT > fT){_x000D_
      var top  = (tT-fT)/2 + fT;_x000D_
  }else{_x000D_
      var top  = (fT-tT)/2 + tT;_x000D_
  }_x000D_
  if(tL > fL){_x000D_
      var left = (tL-fL)/2 + fL;_x000D_
  }else{_x000D_
      var left = (fL-tL)/2 + tL;_x000D_
  }_x000D_
_x000D_
  if(( fT < tT && fL < tL) || ( tT < fT && tL < fL) || (fT > tT && fL > tL) || (tT > fT && tL > fL)){_x000D_
    ANG *= -1;_x000D_
  }_x000D_
  top-= H/2;_x000D_
_x000D_
  line.style["-webkit-transform"] = 'rotate('+ ANG +'deg)';_x000D_
  line.style["-moz-transform"] = 'rotate('+ ANG +'deg)';_x000D_
  line.style["-ms-transform"] = 'rotate('+ ANG +'deg)';_x000D_
  line.style["-o-transform"] = 'rotate('+ ANG +'deg)';_x000D_
  line.style["-transform"] = 'rotate('+ ANG +'deg)';_x000D_
  line.style.top    = top+'px';_x000D_
  line.style.left   = left+'px';_x000D_
  line.style.height = H + 'px';_x000D_
}_x000D_
adjustLine(_x000D_
  document.getElementById('div1'), _x000D_
  document.getElementById('div2'),_x000D_
  document.getElementById('line')_x000D_
);
_x000D_
#content{_x000D_
  position:relative;_x000D_
}_x000D_
.mydiv{_x000D_
  border:1px solid #368ABB;_x000D_
  background-color:#43A4DC;_x000D_
  position:absolute;_x000D_
}_x000D_
.mydiv:after{_x000D_
  content:no-close-quote;_x000D_
  position:absolute;_x000D_
  top:50%;_x000D_
  left:50%;_x000D_
  background-color:black;_x000D_
  width:4px;_x000D_
  height:4px;_x000D_
  border-radius:50%;_x000D_
  margin-left:-2px;_x000D_
  margin-top:-2px;_x000D_
}_x000D_
#div1{_x000D_
  left:200px;_x000D_
  top:200px;_x000D_
  width:50px;_x000D_
  height:50px;_x000D_
}_x000D_
#div2{_x000D_
  left:20px;_x000D_
  top:20px;_x000D_
  width:50px;_x000D_
  height:40px;_x000D_
}_x000D_
#line{_x000D_
  position:absolute;_x000D_
  width:1px;_x000D_
  background-color:red;_x000D_
}  
_x000D_
  _x000D_
_x000D_
<div id="content">_x000D_
  <div id="div1" class="mydiv"></div>_x000D_
  <div id="div2" class="mydiv"></div>_x000D_
  <div id="line"></div>_x000D_
</div>_x000D_
  
_x000D_
_x000D_
_x000D_

What is the purpose of the var keyword and when should I use it (or omit it)?

Saying it's the difference between "local and global" isn't entirely accurate.

It might be better to think of it as the difference between "local and nearest". The nearest can surely be global, but that won't always be the case.

/* global scope */
var local = true;
var global = true;

function outer() {
    /* local scope */
    var local = true;
    var global = false;

    /* nearest scope = outer */
    local = !global;

    function inner() {
        /* nearest scope = outer */
        local = false;
        global = false;

        /* nearest scope = undefined */
        /* defaults to defining a global */
        public = global;
    }
}

Check if a file exists or not in Windows PowerShell?

Use Test-Path:

if (!(Test-Path $exactadminfile) -and !(Test-Path $userfile)) {
  Write-Warning "$userFile absent from both locations"
}

Placing the above code in your ForEach loop should do what you want

How to pass credentials to httpwebrequest for accessing SharePoint Library

If you need to run request as the current user from desktop application use CredentialCache.DefaultCredentials (see on MSDN).

Your code looks fine if you need to run a request from server side code or under a different user.

Please note that you should be careful when storing passwords - consider using the SecureString version of the constructor.

Cannot implicitly convert type 'System.Collections.Generic.IEnumerable<AnonymousType#1>' to 'System.Collections.Generic.List<string>

If you have source as a string like "abcd" and want to produce a list like this:

{ "a.a" },
{ "b.b" },
{ "c.c" },
{ "d.d" }

then call:

List<string> list = source.Select(c => String.Concat(c, ".", c)).ToList();

MSSQL Error 'The underlying provider failed on Open'

I had this error suddenly happen out of the blue on one of our sites. In my case, it turned out that the SQL user's password had expired! Unticking the password expiration box in SQL Server Management Studio did the trick!

What does the JSLint error 'body of a for in should be wrapped in an if statement' mean?

Surely it's a little extreme to say

...never use a for in loop to enumerate over an array. Never. Use good old for(var i = 0; i<arr.length; i++)

?

It is worth highlighting the section in the Douglas Crockford extract

...The second form should be used with objects...

If you require an associative array ( aka hashtable / dictionary ) where keys are named instead of numerically indexed, you will have to implement this as an object, e.g. var myAssocArray = {key1: "value1", key2: "value2"...};.

In this case myAssocArray.length will come up null (because this object doesn't have a 'length' property), and your i < myAssocArray.length won't get you very far. In addition to providing greater convenience, I would expect associative arrays to offer performance advantages in many situations, as the array keys can be useful properties (i.e. an array member's ID property or name), meaning you don't have to iterate through a lengthy array repeatedly evaluating if statements to find the array entry you're after.

Anyway, thanks also for the explanation of the JSLint error messages, I will use the 'isOwnProperty' check now when interating through my myriad associative arrays!

Why am I seeing net::ERR_CLEARTEXT_NOT_PERMITTED errors after upgrading to Cordova Android 8?

Following is the solution which worked for me. The files which I updated are as follows:

  1. config.xml (Full Path: /config.xml)
  2. network_security_config.xml (Full Path: /resources/android/xml/network_security_config.xml)

Changes in the corresponding files are as follows:

1. config.xml

I have added <application android:usesCleartextTraffic="true" /> tag within <edit-config> tag in the config.xml file

<platform name="android">
    <edit-config file="app/src/main/AndroidManifest.xml" mode="merge" target="/manifest/application" xmlns:android="http://schemas.android.com/apk/res/android">
        <application android:usesCleartextTraffic="true" />
        <application android:networkSecurityConfig="@xml/network_security_config" />
    </edit-config>
    ...
<platform name="android">

2. network_security_config.xml

In this file I have added 2 <domain> tag within <domain-config> tag, the main domain and a sub domain as per my project requirement

<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
    <domain-config cleartextTrafficPermitted="true">
        <domain includeSubdomains="true">mywebsite.in</domain>
        <domain includeSubdomains="true">api.mywebsite.in</domain>
    </domain-config>
</network-security-config>

Thanks @Ashutosh for the providing the help.

Hope it helps.

How do I convert a string to enum in TypeScript?

There's a lot of mixed information in this question, so let's cover the whole implementation for TypeScript 2.x+ in Nick's Guide to Using Enums in Models with TypeScript.

This guide is for: people who are creating client-side code that's ingesting a set of known strings from the server that would be conveniently modeled as an Enum on the client side.

Define the enum

Let's start with the enum. It should look something like this:

export enum IssueType {
  REPS = 'REPS',
  FETCH = 'FETCH',
  ACTION = 'ACTION',
  UNKNOWN = 'UNKNOWN',
}

Two thing of note here:

  1. We're explicitly declaring these as string-backed enum cases which allows us to instantiate them with strings, not some other unrelated numbers.

  2. We've added an option that may or may not exist on our server model: UNKNOWN. This can be handled as undefined if you prefer, but I like to avoid | undefined on types whenever possible to simplify handling.

The great thing about having an UNKNOWN case is that you can be really obvious about it in code and make styles for unknown enum cases bright red and blinky so you know you're not handling something correctly.

Parse the enum

You might be using this enum embedded in another model, or all alone, but you're going to have to parse the string-y typed enum from JSON or XML (ha) into your strongly typed counterpart. When embedded in another model, this parser lives in the class constructor.

parseIssueType(typeString: string): IssueType {
  const type = IssueType[typeString];
  if (type === undefined) {
    return IssueType.UNKNOWN;
  }

  return type;
}

If the enum is properly parsed, it'll end up as the proper type. Otherwise, it'll be undefined and you can intercept it and return your UNKNOWN case. If you prefer using undefined as your unknown case, you can just return any result from the attempted enum parsing.

From there, it's only a matter of using the parse function and using your newly strong typed variable.

const strongIssueType: IssueType = parseIssueType('ACTION');
// IssueType.ACTION
const wrongIssueType: IssueType = parseIssueType('UNEXPECTED');
// IssueType.UNKNOWN

Ubuntu says "bash: ./program Permission denied"

Sounds like you don't have the execute flag set on the file permissions, try:

chmod u+x program_name

Application.WorksheetFunction.Match method

You are getting this error because the value cannot be found in the range. String or integer doesn't matter. Best thing to do in my experience is to do a check first to see if the value exists.

I used CountIf below, but there is lots of different ways to check existence of a value in a range.

Public Sub test()

Dim rng As Range
Dim aNumber As Long

aNumber = 666

Set rng = Sheet5.Range("B16:B615")

    If Application.WorksheetFunction.CountIf(rng, aNumber) > 0 Then

        rowNum = Application.WorksheetFunction.Match(aNumber, rng, 0)

    Else
        MsgBox aNumber & " does not exist in range " & rng.Address
    End If

End Sub

ALTERNATIVE WAY

Public Sub test()
    Dim rng As Range
    Dim aNumber As Variant
    Dim rowNum As Long

    aNumber = "2gg"

    Set rng = Sheet5.Range("B1:B20")

    If Not IsError(Application.Match(aNumber, rng, 0)) Then
        rowNum = Application.Match(aNumber, rng, 0)
        MsgBox rowNum
    Else
        MsgBox "error"
    End If
End Sub

OR

Public Sub test()
    Dim rng As Range
    Dim aNumber As Variant
    Dim rowNum As Variant

    aNumber = "2gg"

    Set rng = Sheet5.Range("B1:B20")

    rowNum = Application.Match(aNumber, rng, 0)

    If Not IsError(rowNum) Then
        MsgBox rowNum
    Else
        MsgBox "error"
    End If
End Sub

set height of imageview as matchparent programmatically

You can use the MATCH_PARENT constant or its numeric value -1.

Check Postgres access for a user

For all users on a specific database, do the following:

# psql
\c your_database
select grantee, table_catalog, privilege_type, table_schema, table_name from information_schema.table_privileges order by grantee, table_schema, table_name;

html/css buttons that scroll down to different div sections on a webpage

There is a much easier way to get the smooth scroll effect without javascript. In your CSS just target the entire html tag and give it scroll-behavior: smooth;

_x000D_
_x000D_
html {_x000D_
  scroll-behavior: smooth;_x000D_
 }_x000D_
 _x000D_
 a {_x000D_
  text-decoration: none;_x000D_
  color: black;_x000D_
 } _x000D_
 _x000D_
 #down {_x000D_
  margin-top: 100%;_x000D_
  padding-bottom: 25%;_x000D_
 } 
_x000D_
<html>_x000D_
  <a href="#down">Click Here to Smoothly Scroll Down</a>_x000D_
  <div id="down">_x000D_
    <h1>You are down!</h1>_x000D_
  </div>_x000D_
</html
_x000D_
_x000D_
_x000D_

The "scroll-behavior" is telling the page how it should scroll and is so much easier than using javascript. Javascript will give you more options on speed and the smoothness but this will deliver without all of the confusing code.

Filtering Sharepoint Lists on a "Now" or "Today"

Have you tried this: create a Computed column, called 'Expiry', with a formula that amounts to '[Created] + 7 days'. Then use the computed column in your View's filter. Let us know whether this worked or what problems this poses!

HTTP client timeout and server timeout

According to https://bugzilla.mozilla.org/show_bug.cgi?id=592284, the pref network.http.connection-retry-timeout controls the amount of time in ms (Milliseconds !) to wait for success on the initial connection before beginning the second one. Setting it to 0 disables the parallel connection.

From io.Reader to string in Go

EDIT:

Since 1.10, strings.Builder exists. Example:

buf := new(strings.Builder)
n, err := io.Copy(buf, r)
// check errors
fmt.Println(buf.String())

OUTDATED INFORMATION BELOW

The short answer is that it it will not be efficient because converting to a string requires doing a complete copy of the byte array. Here is the proper (non-efficient) way to do what you want:

buf := new(bytes.Buffer)
buf.ReadFrom(yourReader)
s := buf.String() // Does a complete copy of the bytes in the buffer.

This copy is done as a protection mechanism. Strings are immutable. If you could convert a []byte to a string, you could change the contents of the string. However, go allows you to disable the type safety mechanisms using the unsafe package. Use the unsafe package at your own risk. Hopefully the name alone is a good enough warning. Here is how I would do it using unsafe:

buf := new(bytes.Buffer)
buf.ReadFrom(yourReader)
b := buf.Bytes()
s := *(*string)(unsafe.Pointer(&b))

There we go, you have now efficiently converted your byte array to a string. Really, all this does is trick the type system into calling it a string. There are a couple caveats to this method:

  1. There are no guarantees this will work in all go compilers. While this works with the plan-9 gc compiler, it relies on "implementation details" not mentioned in the official spec. You can not even guarantee that this will work on all architectures or not be changed in gc. In other words, this is a bad idea.
  2. That string is mutable! If you make any calls on that buffer it will change the string. Be very careful.

My advice is to stick to the official method. Doing a copy is not that expensive and it is not worth the evils of unsafe. If the string is too large to do a copy, you should not be making it into a string.

How do I use T-SQL's Case/When?

As soon as a WHEN statement is true the break is implicit.

You will have to concider which WHEN Expression is the most likely to happen. If you put that WHEN at the end of a long list of WHEN statements, your sql is likely to be slower. So put it up front as the first.

More information here: break in case statement in T-SQL

How to sort an array of ints using a custom comparator?

java 8:

Arrays.stream(new int[]{10,4,5,6,1,2,3,7,9,8}).boxed().sorted((e1,e2)-> e2-e1).collect(Collectors.toList());

php random x digit number

This is another simple solution to generate random number of N digits:

$number_of_digits = 10;
echo substr(number_format(time() * mt_rand(),0,'',''),0,$number_of_digits);

Check it here: http://codepad.org/pyVvNiof

How to inject window into a service?

Angular 4 introduce InjectToken, and they also create a token for document called DOCUMENT. I think this is the official solution and it works in AoT.

I use the same logic to create a small library called ngx-window-token to prevent doing this over and over.

I have used it in other project and build in AoT without issues.

Here is how I used it in other package

Here is the plunker

In your module

imports: [ BrowserModule, WindowTokenModule ] In your component

constructor(@Inject(WINDOW) _window) { }

Is there a W3C valid way to disable autocomplete in a HTML form?

Another way - which will also help with security is to call the input box something different every time you display it: just like a captha. That way, the session can read the one-time only input and Auto-Complete has nothing to go on.

Just a point regarding rmeador's question of whether you should be interfering with the browser experience: We develop Contact Management & CRM systems, and when you are typing other people's data into a form you don't want it constantly suggesting your own details.

This works for our needs, but then we have the luxury of telling users to get a decent browser:)

autocomplete='off' 

How to request a random row in SQL?

In late, but got here via Google, so for the sake of posterity, I'll add an alternative solution.

Another approach is to use TOP twice, with alternating orders. I don't know if it is "pure SQL", because it uses a variable in the TOP, but it works in SQL Server 2008. Here's an example I use against a table of dictionary words, if I want a random word.

SELECT TOP 1
  word
FROM (
  SELECT TOP(@idx)
    word 
  FROM
    dbo.DictionaryAbridged WITH(NOLOCK)
  ORDER BY
    word DESC
) AS D
ORDER BY
  word ASC

Of course, @idx is some randomly-generated integer that ranges from 1 to COUNT(*) on the target table, inclusively. If your column is indexed, you'll benefit from it too. Another advantage is that you can use it in a function, since NEWID() is disallowed.

Lastly, the above query runs in about 1/10 of the exec time of a NEWID()-type of query on the same table. YYMV.

JQuery Event for user pressing enter in a textbox?

   $('#textbox').on('keypress', function (e) {
         if(e.which === 13){

            //Disable textbox to prevent multiple submit
            $(this).attr("disabled", "disabled");

            //Do Stuff, submit, etc..

            //Enable the textbox again if needed.
            $(this).removeAttr("disabled");
         }
   });

CSS Equivalent of the "if" statement

css files do not support conditional statements.

If you want something to look one of two ways, depending on some condition, give it a suitable class using your server side scripting language or javascript. eg

<div class="oh-yes"></div>
<div class="hell-no"></div>

Update OpenSSL on OS X with Homebrew

In a terminal, run:

export PATH=/usr/local/bin:$PATH
brew link --force openssl

You may have to unlink openssl first if you get a warning: brew unlink openssl

This ensures we're linking the correct openssl for this situation. (and doesn't mess with .profile)

Hat tip to @Olaf's answer and @Felipe's comment. Some people - such as myself - may have some pretty messed up PATH vars.

Apply CSS rules if browser is IE

A fast approach is to use the following according to ie that you want to focus (check the comments), inside your css files (where margin-top, set whatever css attribute you like):

margin-top: 10px\9; /*It will apply to all ie from 8 and below */
*margin-top: 10px; /*It will apply to ie 7 and below */
_margin-top: 10px; /*It will apply to ie 6 and below*/

A better approach would be to check user agent or a conditional if, in order to avoid the loading of unnecessary CSS in other browsers.

Create XML in Javascript

this work for me..

var xml  = parser.parseFromString('<?xml version="1.0" encoding="utf-8"?><root></root>', "application/xml");

developer.mozilla.org/en-US/docs/Web/API/DOMParser

how can I enable PHP Extension intl?

  1. Go to C:\xampp\php
  2. open the file "php.ini-development" on a text editor.
  3. Then uncomment ;extension=php_intl.dll by removing the semicolon

Managing SSH keys within Jenkins for Git

This works for me if you have config and the private key file in the /Jenkins/.ssh/ you need to chown (change owner) for these 2 files then restart jenkins in order for the jenkins instance to read these 2 files.

How to handle the click event in Listview in android?

    //get main activity
    final Activity main_activity=getActivity();

    //list view click listener
    final ListView listView = (ListView) inflatedView.findViewById(R.id.listView_id);
    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            String stringText;

            //in normal case
            stringText= ((TextView)view).getText().toString();                

            //in case if listview has separate item layout
            TextView textview=(TextView)view.findViewById(R.id.textview_id_of_listview_Item);
            stringText=textview.getText().toString();                

            //show selected
            Toast.makeText(main_activity, stringText, Toast.LENGTH_LONG).show();
        }
    });

    //populate listview

Generate war file from tomcat webapp folder

There is a way to create war file of your project from eclipse.

First a create an xml file with the following code,

Replace HistoryCheck with your project name.

<?xml version="1.0" encoding="UTF-8"?>
<project name="HistoryCheck" basedir="." default="default">
    <target name="default" depends="buildwar,deploy"></target>
    <target name="buildwar">
        <war basedir="war" destfile="HistoryCheck.war" webxml="war/WEB-INF/web.xml">
            <exclude name="WEB-INF/**" />
            <webinf dir="war/WEB-INF/">
                <include name="**/*.jar" />
            </webinf>
        </war>
    </target>
    <target name="deploy">
        <copy file="HistoryCheck.war" todir="." />
    </target>
</project>

Now, In project explorer right click on that xml file and Run as-> ant build

You can see the war file of your project in your project folder.

Determine device (iPhone, iPod Touch) with iOS

The possible vales of

[[UIDevice currentDevice] model];

are iPod touch, iPhone, iPhone Simulator, iPad, iPad Simulator

If you want to know which hardware iOS is ruining on like iPhone3, iPhone4, iPhone5 etc below is the code for that


NOTE: The below code may not contain all device's string, I'm with other guys are maintaining the same code on GitHub so please take the latest code from there

Objective-C : GitHub/DeviceUtil

Swift : GitHub/DeviceGuru


#include <sys/types.h>
#include <sys/sysctl.h>

- (NSString*)hardwareDescription {
    NSString *hardware = [self hardwareString];
    if ([hardware isEqualToString:@"iPhone1,1"]) return @"iPhone 2G";
    if ([hardware isEqualToString:@"iPhone1,2"]) return @"iPhone 3G";
    if ([hardware isEqualToString:@"iPhone3,1"]) return @"iPhone 4";
    if ([hardware isEqualToString:@"iPhone4,1"]) return @"iPhone 4S";
    if ([hardware isEqualToString:@"iPhone5,1"]) return @"iPhone 5";
    if ([hardware isEqualToString:@"iPod1,1"]) return @"iPodTouch 1G";
    if ([hardware isEqualToString:@"iPod2,1"]) return @"iPodTouch 2G";
    if ([hardware isEqualToString:@"iPad1,1"]) return @"iPad";
    if ([hardware isEqualToString:@"iPad2,6"]) return @"iPad Mini";
    if ([hardware isEqualToString:@"iPad4,1"]) return @"iPad Air WIFI";
    //there are lots of other strings too, checkout the github repo
    //link is given at the top of this answer

    if ([hardware isEqualToString:@"i386"]) return @"Simulator";
    if ([hardware isEqualToString:@"x86_64"]) return @"Simulator";

    return nil;
}

- (NSString*)hardwareString {
    size_t size = 100;
    char *hw_machine = malloc(size);
    int name[] = {CTL_HW,HW_MACHINE};
    sysctl(name, 2, hw_machine, &size, NULL, 0);
    NSString *hardware = [NSString stringWithUTF8String:hw_machine];
    free(hw_machine);
    return hardware;
}

How do I pass along variables with XMLHTTPRequest

Following is correct way:

xmlhttp.open("GET","getuser.php?fname="+abc ,true);

How to change Java version used by TOMCAT?

On Linux, Tomcat7 has a configuration file located at:

/etc/sysconfig/tomcat7

... which is where server specific configurations should be made. You can set the JAVA_HOME env variable here w/o needing to create a profile.d/ script.

This worked for me.

Spring Boot yaml configuration for a list of strings

In addition to Ahmet's answer you can add line breaks to the coma separated string using > symbol.

application.yml:

ignoreFilenames: >
  .DS_Store, 
  .hg

Java code:

@Value("${ignoreFilenames}")    
String[] ignoreFilenames;

How to set value in @Html.TextBoxFor in Razor syntax?

I tried replacing value with Value and it worked out. It has set the value in input tag now.

How to open PDF file in a new tab or window instead of downloading it (using asp.net)?

Instead of loading a stream into a byte array and writing it to the response stream, you should have a look at HttpResponse.TransmitFile

Response.ContentType = "Application/pdf";
Response.TransmitFile(pathtofile);

If you want the PDF to open in a new window you would have to open the downloading page in a new window, for example like this:

<a href="viewpdf.aspx" target="_blank">View PDF</a>

gradlew command not found?

Running this bash command works for me by running chmod 755 gradlew as sometimes file properties changed upon moving from one OS to another (Windows, Linux and Mac).

Where/how can I download (and install) the Microsoft.Jet.OLEDB.4.0 for Windows 8, 64 bit?

Make sure to target x86 on your project in Visual Studio. This should fix your trouble.

How to export data to an excel file using PHPExcel

If you've copied this directly, then:

->setCellValue('B2', Ackermann') 

should be

->setCellValue('B2', 'Ackermann') 

In answer to your question:

Get the data that you want from limesurvey, and use setCellValue() to store those data values in the cells where you want to store it.

The Quadratic.php example file in /Tests might help as a starting point: it takes data from an input form and sets it to cells in an Excel workbook.

EDIT

An extremely simplistic example:

// Create your database query
$query = "SELECT * FROM myDataTable";  

// Execute the database query
$result = mysql_query($query) or die(mysql_error());

// Instantiate a new PHPExcel object
$objPHPExcel = new PHPExcel(); 
// Set the active Excel worksheet to sheet 0
$objPHPExcel->setActiveSheetIndex(0); 
// Initialise the Excel row number
$rowCount = 1; 
// Iterate through each result from the SQL query in turn
// We fetch each database result row into $row in turn
while($row = mysql_fetch_array($result)){ 
    // Set cell An to the "name" column from the database (assuming you have a column called name)
    //    where n is the Excel row number (ie cell A1 in the first row)
    $objPHPExcel->getActiveSheet()->SetCellValue('A'.$rowCount, $row['name']); 
    // Set cell Bn to the "age" column from the database (assuming you have a column called age)
    //    where n is the Excel row number (ie cell A1 in the first row)
    $objPHPExcel->getActiveSheet()->SetCellValue('B'.$rowCount, $row['age']); 
    // Increment the Excel row counter
    $rowCount++; 
} 

// Instantiate a Writer to create an OfficeOpenXML Excel .xlsx file
$objWriter = new PHPExcel_Writer_Excel2007($objPHPExcel); 
// Write the Excel file to filename some_excel_file.xlsx in the current directory
$objWriter->save('some_excel_file.xlsx'); 

EDIT #2

Using your existing code as the basis

// Instantiate a new PHPExcel object 
$objPHPExcel = new PHPExcel();  
// Set the active Excel worksheet to sheet 0 
$objPHPExcel->setActiveSheetIndex(0);  
// Initialise the Excel row number 
$rowCount = 1;  

//start of printing column names as names of MySQL fields  
$column = 'A';
for ($i = 1; $i < mysql_num_fields($result); $i++)  
{
    $objPHPExcel->getActiveSheet()->setCellValue($column.$rowCount, mysql_field_name($result,$i));
    $column++;
}
//end of adding column names  

//start while loop to get data  
$rowCount = 2;  
while($row = mysql_fetch_row($result))  
{  
    $column = 'A';
    for($j=1; $j<mysql_num_fields($result);$j++)  
    {  
        if(!isset($row[$j]))  
            $value = NULL;  
        elseif ($row[$j] != "")  
            $value = strip_tags($row[$j]);  
        else  
            $value = "";  

        $objPHPExcel->getActiveSheet()->setCellValue($column.$rowCount, $value);
        $column++;
    }  
    $rowCount++;
} 


// Redirect output to a client’s web browser (Excel5) 
header('Content-Type: application/vnd.ms-excel'); 
header('Content-Disposition: attachment;filename="Limesurvey_Results.xls"'); 
header('Cache-Control: max-age=0'); 
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5'); 
$objWriter->save('php://output');

What is a handle in C++?

A handle can be anything from an integer index to a pointer to a resource in kernel space. The idea is that they provide an abstraction of a resource, so you don't need to know much about the resource itself to use it.

For instance, the HWND in the Win32 API is a handle for a Window. By itself it's useless: you can't glean any information from it. But pass it to the right API functions, and you can perform a wealth of different tricks with it. Internally you can think of the HWND as just an index into the GUI's table of windows (which may not necessarily be how it's implemented, but it makes the magic make sense).

EDIT: Not 100% certain what specifically you were asking in your question. This is mainly talking about pure C/C++.

AngularJS: ng-model not binding to ng-checked for checkboxes

You don't need ng-checked when you use ng-model. If you're performing CRUD on your HTML Form, just create a model for CREATE mode that is consistent with your EDIT mode during the data-binding:

CREATE Mode: Model with default values only

$scope.dataModel = {
   isItemSelected: true,
   isApproved: true,
   somethingElse: "Your default value"
}

EDIT Mode: Model from database

$scope.dataModel = getFromDatabaseWithSameStructure()

Then whether EDIT or CREATE mode, you can consistently make use of your ng-model to sync with your database.

Listening for variable changes in JavaScript

As Luke Schafer's answer (note: this refers to his original post; but the whole point here remains valid after the edit), I would also suggest a pair of Get/Set methods to access your value.

However I would suggest some modifications (and that's why I'm posting...).

A problem with that code is that the field a of the object myobj is directly accessible, so it's possible to access it / change its value without triggering the listeners:

var myobj = { a : 5, get_a : function() { return this.a;}, set_a : function(val) { this.a = val; }}
/* add listeners ... */
myobj.a = 10; // no listeners called!

Encapsulation

So, to guarantee that the listeners are actually called, we would have to prohibit that direct access to the field a. How to do so? Use a closure!

var myobj = (function() { // Anonymous function to create scope.

    var a = 5;            // 'a' is local to this function
                          // and cannot be directly accessed from outside
                          // this anonymous function's scope

    return {
        get_a : function() { return a; },   // These functions are closures:
        set_a : function(val) { a = val; }  // they keep reference to
                                            // something ('a') that was on scope
                                            // where they were defined
    };
})();

Now you can use the same method to create and add the listeners as Luke proposed, but you can rest assured that there's no possible way to read from or write to a going unnoticed!

Adding encapsulated fields programmatically

Still on Luke's track, I propose now a simple way to add encapsulated fields and the respective getters/setters to objects by the means of a simple function call.

Note that this will only work properly with value types. For this to work with reference types, some kind of deep copy would have to be implemented (see this one, for instance).

function addProperty(obj, name, initial) {
    var field = initial;
    obj["get_" + name] = function() { return field; }
    obj["set_" + name] = function(val) { field = val; }
}

This works the same as before: we create a local variable on a function, and then we create a closure.

How to use it? Simple:

var myobj = {};
addProperty(myobj, "total", 0);
window.alert(myobj.get_total() == 0);
myobj.set_total(10);
window.alert(myobj.get_total() == 10);

Disable scrolling on `<input type=number>`

Easiest solution is to add onWheel={ event => event.currentTarget.blur() }} on input itself.

Get a Div Value in JQuery

myDivObj = document.getElementById("myDiv");
if ( myDivObj ) {
   alert ( myDivObj.innerHTML ); 
}else{
   alert ( "Alien Found" );
}

Above code will show the innerHTML, i.e if you have used html tags inside div then it will show even those too. probably this is not what you expected. So another solution is to use: innerText / textContent property [ thanx to bobince, see his comment ]

function showDivText(){
            divObj = document.getElementById("myDiv");
            if ( divObj ){
                if ( divObj.textContent ){ // FF
                    alert ( divObj.textContent );
                }else{  // IE           
                    alert ( divObj.innerText );  //alert ( divObj.innerHTML );
                } 
            }  
        }

Str_replace for multiple items

You could use preg_replace(). The following example can be run using command line php:

<?php
$s1 = "the string \\/:*?\"<>|";
$s2 = preg_replace("^[\\\\/:\*\?\"<>\|]^", " ", $s1) ;
echo "\n\$s2: \"" . $s2 . "\"\n";
?>

Output:

$s2: "the string          "

How can I combine flexbox and vertical scroll in a full-height app?

Flexbox spec editor here.

This is an encouraged use of flexbox, but there are a few things you should tweak for best behavior.

  • Don't use prefixes. Unprefixed flexbox is well-supported across most browsers. Always start with unprefixed, and only add prefixes if necessary to support it.

  • Since your header and footer aren't meant to flex, they should both have flex: none; set on them. Right now you have a similar behavior due to some overlapping effects, but you shouldn't rely on that unless you want to accidentally confuse yourself later. (Default is flex:0 1 auto, so they start at their auto height and can shrink but not grow, but they're also overflow:visible by default, which triggers their default min-height:auto to prevent them from shrinking at all. If you ever set an overflow on them, the behavior of min-height:auto changes (switching to zero rather than min-content) and they'll suddenly get squished by the extra-tall <article> element.)

  • You can simplify the <article> flex too - just set flex: 1; and you'll be good to go. Try to stick with the common values in https://drafts.csswg.org/css-flexbox/#flex-common unless you have a good reason to do something more complicated - they're easier to read and cover most of the behaviors you'll want to invoke.

Remove specific characters from a string in Python

Strings are immutable in Python. The replace method returns a new string after the replacement. Try:

for char in line:
    if char in " ?.!/;:":
        line = line.replace(char,'')

This is identical to your original code, with the addition of an assignment to line inside the loop.

Note that the string replace() method replaces all of the occurrences of the character in the string, so you can do better by using replace() for each character you want to remove, instead of looping over each character in your string.

Access Control Request Headers, is added to header in AJAX request with jQuery

And that is why you can't create a bot with JavaScript, because your options are limited to what the browser allows you to do. You can't just order a browser that follows the CORS policy, which most browsers follow, to send random requests to other origins and allow you to get the response that simply!

Additionally, if you tried to edit some request headers manually, like origin-header from the developers tools that come with the browsers, the browser will refuse your edit and may send a preflight OPTIONS request.

ASP.NET MVC Razor render without encoding

@(new HtmlString(myString))

Why use 'virtual' for class properties in Entity Framework model definitions?

The virtual keyword in C# enables a method or property to be overridden by child classes. For more information please refer to the MSDN documentation on the 'virtual' keyword

UPDATE: This doesn't answer the question as currently asked, but I'll leave it here for anyone looking for a simple answer to the original, non-descriptive question asked.

JSON.Parse,'Uncaught SyntaxError: Unexpected token o

Your last example is invalid JSON. Single quotes are not allowed in JSON except inside strings. In the second example, the single quotes are not in the string, but serve to show the start and end.

See http://www.json.org/ for the specifications.

Should add: Why do you think this: "like I seem to need to in my real code"? Then maybe we can help you come up with the solution.

Change drive in git bash for windows

TL;DR; for Windows users:

(Quotation marks not needed if path has no blank spaces)

Git Bash: cd "/C/Program Files (x86)/Android" // macOS/Linux syntax

Cmd.exe: cd "C:\Program Files (x86)\Android" // windows syntax


When using git bash on windows, you have to:

  • remove the colon after the drive letter
  • replace your back-slashes with forward-slashes
  • If you have blank spaces in your path: Put quotation marks at beginning and end of the path

Git Bash: cd "/C/Program Files (x86)/Android" // macOS/Linux syntax

Cmd.exe: cd "C:\Program Files (x86)\Android" // windows syntax

Creating email templates with Django

Django Mail Templated is a feature-rich Django application to send emails with Django template system.

Installation:

pip install django-mail-templated

Configuration:

INSTALLED_APPS = (
    ...
    'mail_templated'
)

Template:

{% block subject %}
Hello {{ user.name }}
{% endblock %}

{% block body %}
{{ user.name }}, this is the plain text part.
{% endblock %}

Python:

from mail_templated import send_mail
send_mail('email/hello.tpl', {'user': user}, from_email, [user.email])

More info: https://github.com/artemrizhov/django-mail-templated

When is the @JsonProperty property used and what is it used for?

Without annotations, inferred property name (to match from JSON) would be "set", and not -- as seems to be the intent -- "isSet". This is because as per Java Beans specification, methods of form "isXxx" and "setXxx" are taken to mean that there is logical property "xxx" to manage.

Print array to a file

file_put_contents($file, print_r($array, true), FILE_APPEND)

Java: Date from unix timestamp

Date's constructor expects the timeStamp value to be in milliseconds. Multiply your timestamp's value with 1000, then pass it to the constructor.

What is the curl error 52 "empty reply from server"?

It can happen when server does not respond due to 100% CPU or Memory utilization.

I got this error when I was trying to access sonarqube API and the server was not responding due to full memory utilization

LINUX: Link all files from one to another directory

GNU cp has an option to create symlinks instead of copying.

cp -rs /mnt/usr/lib /usr/

Note this is a GNU extension not found in POSIX cp.

VMWare Player vs VMWare Workstation

Workstation has some features that Player lacks, such as teams (groups of VMs connected by private LAN segments) and multi-level snapshot trees. It's aimed at power users and developers; they even have some hooks for using a debugger on the host to debug code in the VM (including kernel-level stuff). The core technology is the same, though.

Google Map API v3 ~ Simply Close an infowindow?

We can use infowindow.close(map); to close all info windows if you already initialize the info window using infowindow = new google.maps.InfoWindow();

What's the difference between "app.render" and "res.render" in express.js?

Here are some differences:

  1. You can call app.render on root level and res.render only inside a route/middleware.

  2. app.render always returns the html in the callback function, whereas res.render does so only when you've specified the callback function as your third parameter. If you call res.render without the third parameter/callback function the rendered html is sent to the client with a status code of 200.

    Take a look at the following examples.

    • app.render

      app.render('index', {title: 'res vs app render'}, function(err, html) {
          console.log(html)
      });
      
      // logs the following string (from default index.jade)
      <!DOCTYPE html><html><head><title>res vs app render</title><link rel="stylesheet" href="/stylesheets/style.css"></head><body><h1>res vs app render</h1><p>Welcome to res vs app render</p></body></html>
      
    • res.render without third parameter

      app.get('/render', function(req, res) {
          res.render('index', {title: 'res vs app render'})
      })
      
      // also renders index.jade but sends it to the client 
      // with status 200 and content-type text/html on GET /render
      
    • res.render with third parameter

      app.get('/render', function(req, res) {
          res.render('index', {title: 'res vs app render'}, function(err, html) {
              console.log(html);
              res.send('done');
          })
      })
      
      // logs the same as app.render and sends "done" to the client instead 
      // of the content of index.jade
      
  3. res.render uses app.render internally to render template files.

  4. You can use the render functions to create html emails. Depending on your structure of your app, you might not always have acces to the app object.

    For example inside an external route:

    app.js

    var routes = require('routes');
    
    app.get('/mail', function(req, res) {
        // app object is available -> app.render
    })
    
    app.get('/sendmail', routes.sendmail);
    

    routes.js

    exports.sendmail = function(req, res) {
        // can't use app.render -> therefore res.render
    }
    

Select data between a date/time range

Here is a simple way using the date function:

select *
from hockey_stats
where date(game_date) between date('2012-11-03') and date('2012-11-05')
order by game_date desc

JavaFX Application Icon

stage.getIcons().add(new Image("/images/logo_only.png"));

It is good habit to make images folder in your src folder and get images from it.

How to add an onchange event to a select box via javascript?

yourSelect.setAttribute( "onchange", "yourFunction()" );

Add a column to a table, if it does not already exist

Here's another variation that worked for me.

IF NOT EXISTS (SELECT 1
        FROM INFORMATION_SCHEMA.COLUMNS
        WHERE upper(TABLE_NAME) = 'TABLENAME'
        AND upper(COLUMN_NAME) = 'COLUMNNAME')
BEGIN
    ALTER TABLE [dbo].[Person] ADD Column
END
GO

EDIT: Note that INFORMATION_SCHEMA views may not always be updated, use SYS.COLUMNS instead:

IF NOT EXISTS (SELECT 1 FROM SYS.COLUMNS....

How to remove package using Angular CLI?

I think best approach until Angular team add this feature to cli is first create angular (ng new something) in other place and then add what you want to delete. Using git to check witch files are changed or added by angular cli. then you can revert that changes. Be careful of untracked files from .gitignore.

How to create a drop-down list?

You can create spinner by these simple steps

first create spinner in xml

<Spinner
        android:id="@+id/select"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:textColor="#070707"></Spinner>

now create string arary in values

 <string-array name="itemselect">
    <item>Repurchase</item>
    <item>Coupons</item>
</string-array>

now initialized in java file

public class MemberCart_Activity extends AppCompatActivity {

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

 
    select=findViewById(R.id.select);
 ArrayAdapter<String> myadapter=new ArrayAdapter<String>(Main_Activity.this,android.R.layout.simple_list_item_1,getResources().getStringArray(R.array.itemselect));
    myadapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    select.setAdapter(myadapter);

Sending SMS from PHP

You need to subscribe to a SMS gateway. There are thousands of those (try searching with google) and they are usually not free. For example this one has support for PHP.

Change R default library path using .libPaths in Rprofile.site fails to work

If you do not have admin-rights, it can also be helpful to open the Rprofile.site-file located in \R-3.1.0\etc and add:

.First <- function(){
  .libPaths("your path here")
}

This evaluates the .libPath() command directly at start

Change name of folder when cloning from GitHub?

You can do this.

git clone https://github.com/sferik/sign-in-with-twitter.git signin

refer the manual here

org.hibernate.MappingException: Unknown entity: annotations.Users

 public static void main(String[] args) {
      try{
        // factory = new Configuration().configure().buildSessionFactory();
         factory = new AnnotationConfiguration().
                   configure().
                   //addPackage("com.xyz") //add package if used.
                   addAnnotatedClass(Employee.class).
                   buildSessionFactory();
      }catch (Throwable ex) { 
         System.err.println("Failed to create sessionFactory object." + ex);
         throw new ExceptionInInitializerError(ex); 
      }//you can write like this in your test class inside main method.this way you will be able to do the things using annotaions only

Explanation of the UML arrows

Here's some explanations from the Visual Studio 2015 docs:

UML Class Diagrams: Reference: https://msdn.microsoft.com/library/dd409437%28VS.140%29.aspx

UML class diagram

5: Association: A relationship between the members of two classifiers.

5a: Aggregation: An association representing a shared ownership relationship. The Aggregation property of the owner role is set to Shared.

5b: Composition: An association representing a whole-part relationship. The Aggregation property of the owner role is set to Composite.

9: Generalization: The specific classifier inherits part of its definition from the general classifier. The general classifier is at the arrow end of the connector. Attributes, associations, and operations are inherited by the specific classifier. Use the Inheritance tool to create a generalization between two classifiers.

Package diagram

13: Import: A relationship between packages, indicating that one package includes all the definitions of another.

14: Dependency: The definition or implementation of the dependent classifier might change if the classifier at the arrowhead end is changed.

Realization relationship

15: Realization: The class implements the operations and attributes defined by the interface. Use the Inheritance tool to create a realization between a class and an interface.

16: Realization: An alternative presentation of the same relationship. The label on the lollipop symbol identifies the interface.

UML Class Diagrams: Guidelines: http://msdn.microsoft.com/library/dd409416%28VS.140%29.aspx

Properties of an Association

Aggregation: This appears as a diamond shape at one end of the connector. You can use it to indicate that instances at the aggregating role own or contain instances of the other.

Is Navigable: If true for only one role, an arrow appears in the navigable direction. You can use this to indicate navigability of links and database relations in the software.


Generalization: Generalization means that the specializing or derived type inherits attributes, operations, and associations of the general or base type. The general type appears at the arrowhead end of the relationship.

Realization: Realization means that a class implements the attributes and operations specified by the interface. The interface is at the arrow end of the connector.

Let me know if you have more questions.

How do I remove the title bar from my app?

In the manifest file Change:

    android:theme="@style/AppTheme" >
    android:theme="@style/Theme.AppCompat.NoActionBar"

Shell script to delete directories older than n days

OR

rm -rf `find /path/to/base/dir/* -type d -mtime +10`

Updated, faster version of it:

find /path/to/base/dir/* -mtime +10 -print0 | xargs -0 rm -f

Removing empty rows of a data file in R

Here are some dplyr options:

# sample data
df <- data.frame(a = c('1', NA, '3', NA), b = c('a', 'b', 'c', NA), c = c('e', 'f', 'g', NA))

library(dplyr)

# remove rows where all values are NA:
df %>% filter_all(any_vars(!is.na(.)))
df %>% filter_all(any_vars(complete.cases(.)))  


# remove rows where only some values are NA:
df %>% filter_all(all_vars(!is.na(.)))
df %>% filter_all(all_vars(complete.cases(.)))  

# or more succinctly:
df %>% filter(complete.cases(.))  
df %>% na.omit

# dplyr and tidyr:
library(tidyr)
df %>% drop_na

How do I fix "for loop initial declaration used outside C99 mode" GCC error?

I've gotten this error too.

for (int i=0;i<10;i++) { ..

is not valid in the C89/C90 standard. As OysterD says, you need to do:

int i;
for (i=0;i<10;i++) { ..

Your original code is allowed in C99 and later standards of the C language.

How to sort a list/tuple of lists/tuples by the element at a given index?

I just want to add to Stephen's answer if you want to sort the array from high to low, another way other than in the comments above is just to add this to the line:

reverse = True

and the result will be as follows:

data.sort(key=lambda tup: tup[1], reverse=True)

How to get the current URL within a Django template?

I suppose send to template full request is little bit redundant. I do it this way

from django.shortcuts import render

def home(request):
    app_url = request.path
    return render(request, 'home.html', {'app_url': app_url})

##template
{{ app_url }}

How can I copy a conditional formatting from one document to another?

If you want to copy conditional formatting to another document you can use the "Copy to..." feature for the worksheet (click the tab with the name of the worksheet at the bottom) and copy the worksheet to the other document.

Then you can just copy what you want from that worksheet and right-click select "Paste special" -> "Paste conditional formatting only", as described earlier.

Why does Firebug say toFixed() is not a function?

In a function, use as

render: function (args) {
    if (args.value != 0)
        return (parseFloat(args.value).toFixed(2));


},

How to obtain a QuerySet of all rows, with specific fields for each one of them?

In addition to values_list as Daniel mentions you can also use only (or defer for the opposite effect) to get a queryset of objects only having their id and specified fields:

Employees.objects.only('eng_name')

This will run a single query:

SELECT id, eng_name FROM employees

Maximum concurrent Socket.IO connections

This article may help you along the way: http://drewww.github.io/socket.io-benchmarking/

I wondered the same question, so I ended up writing a small test (using XHR-polling) to see when the connections started to fail (or fall behind). I found (in my case) that the sockets started acting up at around 1400-1800 concurrent connections.

This is a short gist I made, similar to the test I used: https://gist.github.com/jmyrland/5535279

How to check if the key pressed was an arrow key in Java KeyListener?

If you mean that you wanna attach this to your panel (Window that you are working with).

then you have to create an inner class that extend from IKeyListener interface and then add that method in to the class.

Then, attach that class to you panel by: this.addKeyListener(new subclass());

Copy text from nano editor to shell

nano does not seem to have the ability to copy/paste from the global/system clipboard or shell.

However, you can copy text from one file to another using nano's file buffers. When you open another file buffer with ^R (Ctrl + r), you can use nanos built-in copy/paste functionality (outlined below) to copy between files:

  • M-6 (Meta + 6) to copy lines to nano's clipboard.
  • ^K (Ctrl + k) to cut the current line and store it in nano's clipboard.
  • ^^ (Ctrl + Shift + 6) to select text. Once you have selected the text, you can use the above commands to copy it or cut it.
  • ^U (Ctrl + u) to paste the text from nano's clipboard.

Finally, if the above solution will not work for you and you are using a terminal emulator, you may be able to copy/paste from the global clipboard with Ctrl + Shift + c and Ctrl + Shift + v (Cmd + c and Cmd + v on OSX) respectively. screen also provides an external copy/paste that should work in nano. Finally if all you need to do is capture certain lines or text from a file, consider using grep to find the lines and xclip or xsel (or pbcopy/pbpaste on OSX) to copy them to the global clipboard (and/or paste from the clipboard) instead of nano.

Return JSON response from Flask view

jsonify serializes the data you pass it to JSON. If you want to serialize the data yourself, do what jsonify does by building a response with status=200 and mimetype='application/json'.

from flask import json

@app.route('/summary')
def summary():
    data = make_summary()
    response = app.response_class(
        response=json.dumps(data),
        status=200,
        mimetype='application/json'
    )
    return response

How to change line-ending settings

Line ending format used in OS

  • Windows: CR (Carriage Return \r) and LF (LineFeed \n) pair
  • OSX,Linux: LF (LineFeed \n)

We can configure git to auto-correct line ending formats for each OS in two ways.

  1. Git Global configuration
  2. Use .gitattributes file

Global Configuration

In Linux/OSX
git config --global core.autocrlf input

This will fix any CRLF to LF when you commit.

In Windows
git config --global core.autocrlf true

This will make sure when you checkout in windows, all LF will convert to CRLF

.gitattributes File

It is a good idea to keep a .gitattributes file as we don't want to expect everyone in our team set their config. This file should keep in repo's root path and if exist one, git will respect it.

* text=auto

This will treat all files as text files and convert to OS's line ending on checkout and back to LF on commit automatically. If wanted to tell explicitly, then use

* text eol=crlf
* text eol=lf

First one is for checkout and second one is for commit.

*.jpg binary

Treat all .jpg images as binary files, regardless of path. So no conversion needed.

Or you can add path qualifiers:

my_path/**/*.jpg binary

HTML5 Pre-resize images before uploading

fd.append("image", dataurl);

This will not work. On PHP side you can not save file with this.

Use this code instead:

var blobBin = atob(dataurl.split(',')[1]);
var array = [];
for(var i = 0; i < blobBin.length; i++) {
  array.push(blobBin.charCodeAt(i));
}
var file = new Blob([new Uint8Array(array)], {type: 'image/png', name: "avatar.png"});

fd.append("image", file); // blob file

Warnings Your Apk Is Using Permissions That Require A Privacy Policy: (android.permission.READ_PHONE_STATE)

Are you using AdSense or other ads in your app, or maybe Google Analytics ? I think if you do so, even if you don't have the android.permission.READ_PHONE_STATE in your manifest this is added by the ads library.

There are free templates that might help you create a privacy policy.

This is the email i received from Google about it :

Hello Google Play Developer, Our records show that your app, xxx, with package name xxx, currently violates our User Data policy regarding Personal and Sensitive Information. Policy issue: Google Play requires developers to provide a valid privacy policy when the app requests or handles sensitive user or device information. Your app requests sensitive permissions (e.g. camera, microphone, accounts, contacts, or phone) or user data, but does not include a valid privacy policy. Action required: Include a link to a valid privacy policy on your app's Store Listing page and within your app. You can find more information in our help center. Alternatively, you may opt-out of this requirement by removing any requests for sensitive permissions or user data. If you have additional apps in your catalog, please make sure they are compliant with our Prominent Disclosure requirements. Please resolve this issue by March 15, 2017, or administrative action will be taken to limit the visibility of your app, up to and including removal from the Play Store. Thanks for helping us provide a clear and transparent experience for Google Play users. Regards, The Google Play Team

Show image using file_get_contents

You can do that, or you can use the readfile function, which outputs it for you:

header('Content-Type: image/x-png'); //or whatever
readfile('thefile.png');
die();

Edit: Derp, fixed obvious glaring typo.

Could not load file or assembly Exception from HRESULT: 0x80131040

I have issue with itextsharp and itextsharp.xmlworker dlls for exception-from-hresult-0x80131040 so I have removed those both dlls from references and downloaded new dlls directly from nuget packages, which resolved my issue.

May be this method can be useful to resolved the issue to other people.

python: how to send mail with TO, CC and BCC?

The distinction between TO, CC and BCC occurs only in the text headers. At the SMTP level, everybody is a recipient.

TO - There is a TO: header with this recipient's address

CC - There is a CC: header with this recipient's address

BCC - This recipient isn't mentioned in the headers at all, but is still a recipient.

If you have

TO: [email protected]
CC: [email protected]
BCC: [email protected]

You have three recipients. The headers in the email body will include only the TO: and CC:

Index Error: list index out of range (Python)

Generally it means that you are providing an index for which a list element does not exist.

E.g, if your list was [1, 3, 5, 7], and you asked for the element at index 10, you would be well out of bounds and receive an error, as only elements 0 through 3 exist.

How to find the UpgradeCode and ProductCode of an installed application in Windows 7

Another way-too-complicated workaround, with the benefit of not having to re-install the application as the previous workaround required. This requires that you have access to the msi (or a setup.exe with the msi embedded).

If you have Visual Studio 2012 (or possibly other editions) and install the free "InstallShield LE", then you can create a new setup project using InstallShield.

One of the configuration options in the "Organize your Setup" step is called "Upgrade Paths". Open the properties for Upgrade Paths, and in the left pane right click "Upgrade Paths" and select "New Upgrade Path" ... now browse to the msi (or setup.exe containing the msi) and click "open". The upgrade code will be populated for you in the settings page in the right pane which you should now see.

Is there a way to word-wrap long words in a div?

Most of the previous answer didn't work for me in Firefox 38.0.5. This did...

<div style='padding: 3px; width: 130px; word-break: break-all; word-wrap: break-word;'>
    // Content goes here
</div>

Documentation:

Reading file from Workspace in Jenkins with Groovy script

I realize this question was about creating a plugin, but since the new Jenkins 2 Pipeline builds use Groovy, I found myself here while trying to figure out how to read a file from a workspace in a Pipeline build. So maybe I can help someone like me out in the future.

Turns out it's very easy, there is a readfile step, and I should have rtfm:

env.WORKSPACE = pwd()
def version = readFile "${env.WORKSPACE}/version.txt"

Nested objects in javascript, best practices

var defaultsettings = {
    ajaxsettings: {
        ...
    },
    uisettings: {
        ...
    }
};

Git on Bitbucket: Always asked for password, even after uploading my public SSH key

I was having other weirdness around logging in. I came across something that seemed totally dumb but worked in my case. Simply go to MacOS's keychain. Find the login lock icon in the sidebar. Click it to logout and then click to login. Sounds dumb but it solved my issues. Worth a shot.

Spring MVC 4: "application/json" Content Type is not being set correctly

When I upgraded to Spring 4 I needed to update the jackson dependencies as follows:

    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-core</artifactId>
        <version>2.5.1</version>
    </dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.5.1</version>
    </dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-annotations</artifactId>
        <version>2.5.1</version>
    </dependency>        

Center align a column in twitter bootstrap

I tried the approaches given above, but these methods fail when dynamically the height of the content in one of the cols increases, it basically pushes the other cols down.

for me the basic table layout solution worked.

// Apply this to the enclosing row
.row-centered {
  text-align: center;
  display: table-row;
}
// Apply this to the cols within the row
.col-centered {
  display: table-cell;
  float: none;
  vertical-align: top;
}

Composer: Command Not Found

I am using CentOS and had same problem.

I changed /usr/local/bin/composer to /usr/bin/composer and it worked.

Run below command :

curl -sS https://getcomposer.org/installer | php sudo mv composer.phar /usr/bin/composer

Verify Composer is installed or not

composer --version

C++ Fatal Error LNK1120: 1 unresolved externals

I have faced this particular error when I didn't defined the main() function. Check if the main() function exists or check the name of the function letter by letter as Timothy described above or check if the file where the main function is located is included to your project.

How to run java application by .bat file

javac Application.java

java Application

pause

The javac command will compile the java program and the java command will run the program and pause will pause the result until you cross it.

Disable cache for some images

If you need to do it dynamically in the browser using javascript, here is an example...

<img id=graph alt="" 
  src="http://www.kitco.com/images/live/gold.gif" 
  />

<script language="javascript" type="text/javascript">
    var d = new Date(); 
    document.getElementById("graph").src = 
      "http://www.kitco.com/images/live/gold.gif?ver=" + 
       d.getTime();
</script>

List of macOS text editors and code editors

There's a new kid on the block - PHPStorm. I used it for a whole year. Its not free but offers an individual license of 49$ for a year, free for Open Source Developers.

  • Speedy for an IDE - Its based on Java so looks somewhat like Eclipse/Netbeans but smokes them to dust in terms of speed (not as fast as Coda/Textmate as this is an IDE).
  • Keyboard shortcuts galore - I seldom touched the mouse while developing using PHPStorm (that's what I didn't like about Coda)
  • Subversion support built-in - Didn't need to touch Versions or any other SVN client on Mac
  • Supports snippets, templates - zen-coding is supported as well
  • Supports projects, though in separate windows
  • File search, code search
  • code completion, supports PHPDoc code completion too

What’s the difference between "Array()" and "[]" while declaring a JavaScript array?

Using the Array constructor makes a new array of the desired length and populates each of the indices with undefined, the assigned an array to a variable one creates the indices that you give it info for.

After installation of Gulp: “no command 'gulp' found”

I solved the issue removing gulp and installing gulp-cli again:

rm /usr/local/bin/gulp
npm install -g gulp-cli

How to draw border on just one side of a linear layout?

To get a border on just one side of a drawable, apply a negative inset to the other 3 sides (causing those borders to be drawn off-screen).

<?xml version="1.0" encoding="utf-8"?>
<inset xmlns:android="http://schemas.android.com/apk/res/android"
    android:insetTop="-2dp" 
    android:insetBottom="-2dp"
    android:insetLeft="-2dp">

    <shape android:shape="rectangle">
        <stroke android:width="2dp" android:color="#FF0000" />
        <solid android:color="#000000" />
    </shape>

</inset>

enter image description here

This approach is similar to naykah's answer, but without the use of a layer-list.

Check if a varchar is a number (TSQL)

Using SQL Server 2012+, you can use the TRY_* functions if you have specific needs. For example,

-- will fail for decimal values, but allow negative values
TRY_CAST(@value AS INT) IS NOT NULL 

-- will fail for non-positive integers; can be used with other examples below as well, or reversed if only negative desired
TRY_CAST(@value AS INT) > 0

-- will fail if a $ is used, but allow decimals to the specified precision
TRY_CAST(@value AS DECIMAL(10,2)) IS NOT NULL 

-- will allow valid currency
TRY_CAST(@value AS MONEY) IS NOT NULL  

-- will allow scientific notation to be used like 1.7E+3
TRY_CAST(@value AS FLOAT) IS NOT NULL 

What is the purpose of using WHERE 1=1 in SQL statements?

People use it because they're inherently lazy when building dynamic SQL queries. If you start with a "where 1 = 1" then all your extra clauses just start with "and" and you don't have to figure out.

Not that there's anything wrong with being inherently lazy. I've seen doubly-linked lists where an "empty" list consists of two sentinel nodes and you start processing at the first->next up until last->prev inclusive.

This actually removed all the special handling code for deleting first and last nodes. In this set-up, every node was a middle node since you weren't able to delete first or last. Two nodes were wasted but the code was simpler and (ever so slightly) faster.

The only other place I've ever seen the "1 = 1" construct is in BIRT. Reports often use positional parameters and are modified with Javascript to allow all values. So the query:

select * from tbl where col = ?

when the user selects "*" for the parameter being used for col is modified to read:

select * from tbl where ((col = ?) or (1 = 1))

This allows the new query to be used without fiddling around with the positional parameter details. There's still exactly one such parameter. Any decent DBMS (e.g., DB2/z) will optimize that query to basically remove the clause entirely before trying to construct an execution plan, so there's no trade-off.

make bootstrap twitter dialog modal draggable

i did this:

$("#myModal").modal({}).draggable();

and it make my very standard/basic modal draggable.

not sure how/why it worked, but it did.

Get name of property as a string

I've been using this answer to great effect: Get the property, as a string, from an Expression<Func<TModel,TProperty>>

I realize I already answered this question a while back. The only advantage my other answer has is that it works for static properties. I find the syntax in this answer much more useful because you don't have to create a variable of the type you want to reflect.

Python speed testing - Time Difference - milliseconds

I know this is late, but I actually really like using:

import time
start = time.time()

##### your timed code here ... #####

print "Process time: " + (time.time() - start)

time.time() gives you seconds since the epoch. Because this is a standardized time in seconds, you can simply subtract the start time from the end time to get the process time (in seconds). time.clock() is good for benchmarking, but I have found it kind of useless if you want to know how long your process took. For example, it's much more intuitive to say "my process takes 10 seconds" than it is to say "my process takes 10 processor clock units"

>>> start = time.time(); sum([each**8.3 for each in range(1,100000)]) ; print (time.time() - start)
3.4001404476250935e+45
0.0637760162354
>>> start = time.clock(); sum([each**8.3 for each in range(1,100000)]) ; print (time.clock() - start)
3.4001404476250935e+45
0.05

In the first example above, you are shown a time of 0.05 for time.clock() vs 0.06377 for time.time()

>>> start = time.clock(); time.sleep(1) ; print "process time: " + (time.clock() - start)
process time: 0.0
>>> start = time.time(); time.sleep(1) ; print "process time: " + (time.time() - start)
process time: 1.00111794472

In the second example, somehow the processor time shows "0" even though the process slept for a second. time.time() correctly shows a little more than 1 second.

Html ordered list 1.1, 1.2 (Nested counters and scope) not working

I encountered similar problem recently. The fix is to set the display property of the li items in the ordered list to list-item, and not display block, and ensure that the display property of ol is not list-item. i.e

li { display: list-item;}

With this, the html parser sees all li as the list item and assign the appropriate value to it, and sees the ol, as an inline-block or block element based on your settings, and doesn't try to assign any count value to it.

Eclipse cannot load SWT libraries

Simply specify the path to the libraries:

echo "-Djava.library.path=/usr/lib/jni/" >> /etc/eclipse.ini

How do Common Names (CN) and Subject Alternative Names (SAN) work together?

This depends on implementation, but the general rule is that the domain is checked against all SANs and the common name. If the domain is found there, then the certificate is ok for connection.

RFC 5280, section 4.1.2.6 says "The subject name MAY be carried in the subject field and/or the subjectAltName extension". This means that the domain name must be checked against both SubjectAltName extension and Subject property (namely it's common name parameter) of the certificate. These two places complement each other, and not duplicate it. And SubjectAltName is a proper place to put additional names, such as www.domain.com or www2.domain.com

Update: as per RFC 6125, published in 2011, the validator must check SAN first, and if SAN exists, then CN should not be checked. Note that RFC 6125 is relatively recent and there still exist certificates and CAs that issue certificates, which include the "main" domain name in CN and alternative domain names in SAN. I.e. by excluding CN from validation if SAN is present, you can deny some otherwise valid certificate.

Delete empty lines using sed

I believe this is the easiest and fastest one:

cat file.txt | grep .

If you need to ignore all white-space lines as well then try this:

cat file.txt | grep '\S'

Example:

s="\
\
a\
 b\
\
Below is TAB:\
    \
Below is space:\
 \
c\
\
"; echo "$s" | grep . | wc -l; echo "$s" | grep '\S' | wc -l

outputs

7
5

How to remove margin space around body or clear default css styles

That's the default margin/padding of the body element.

Some browsers have a default margin, some a default padding, and both are applied as a padding in the body element.

Add this to your CSS:

body { margin: 0; padding: 0; }

Launch iOS simulator from Xcode and getting a black screen, followed by Xcode hanging and unable to stop tasks

I had the same issue with Xcode... black screen on launching apps, no debugging and clicking would lock up Xcode.

I finally found the problem... following the lead that the simulator could not connect to Xcode I took a look at my etc/hosts file and found that months ago to solve a different issue I had edited the host file to map localhost to my fixed IP instead of the default... my value:

10.0.1.17 localhost

This should work since that is my IP, but changing it back to the default IP fixed Xcode...

127.0.0.1 localhost

Hope this helps.

Why does NULL = NULL evaluate to false in SQL server

Just because you don't know what two things are, does not mean they're equal. If when you think of NULL you think of “NULL” (string) then you probably want a different test of equality like Postgresql's IS DISTINCT FROM AND IS NOT DISTINCT FROM

From the PostgreSQL docs on "Comparison Functions and Operators"

expression IS DISTINCT FROM expression

expression IS NOT DISTINCT FROM expression

For non-null inputs, IS DISTINCT FROM is the same as the <> operator. However, if both inputs are null it returns false, and if only one input is null it returns true. Similarly, IS NOT DISTINCT FROM is identical to = for non-null inputs, but it returns true when both inputs are null, and false when only one input is null. Thus, these constructs effectively act as though null were a normal data value, rather than "unknown".