Programs & Examples On #Syndication item

How to check if array is empty or does not exist?

You want to do the check for undefined first. If you do it the other way round, it will generate an error if the array is undefined.

if (array === undefined || array.length == 0) {
    // array empty or does not exist
}

Update

This answer is getting a fair amount of attention, so I'd like to point out that my original answer, more than anything else, addressed the wrong order of the conditions being evaluated in the question. In this sense, it fails to address several scenarios, such as null values, other types of objects with a length property, etc. It is also not very idiomatic JavaScript.

The foolproof approach
Taking some inspiration from the comments, below is what I currently consider to be the foolproof way to check whether an array is empty or does not exist. It also takes into account that the variable might not refer to an array, but to some other type of object with a length property.

if (!Array.isArray(array) || !array.length) {
  // array does not exist, is not an array, or is empty
  // ? do not attempt to process array
}

To break it down:

  1. Array.isArray(), unsurprisingly, checks whether its argument is an array. This weeds out values like null, undefined and anything else that is not an array.
    Note that this will also eliminate array-like objects, such as the arguments object and DOM NodeList objects. Depending on your situation, this might not be the behavior you're after.

  2. The array.length condition checks whether the variable's length property evaluates to a truthy value. Because the previous condition already established that we are indeed dealing with an array, more strict comparisons like array.length != 0 or array.length !== 0 are not required here.

The pragmatic approach
In a lot of cases, the above might seem like overkill. Maybe you're using a higher order language like TypeScript that does most of the type-checking for you at compile-time, or you really don't care whether the object is actually an array, or just array-like.

In those cases, I tend to go for the following, more idiomatic JavaScript:

if (!array || !array.length) {
    // array or array.length are falsy
    // ? do not attempt to process array
}

Or, more frequently, its inverse:

if (array && array.length) {
    // array and array.length are truthy
    // ? probably OK to process array
}

With the introduction of the optional chaining operator (Elvis operator) in ECMAScript 2020, this can be shortened even further:

if (!array?.length) {
    // array or array.length are falsy
    // ? do not attempt to process array
}

Or the opposite:

if (array?.length) {
    // array and array.length are truthy
    // ? probably OK to process array
}

read file in classpath

Try getting Spring to inject it, assuming you're using Spring as a dependency-injection framework.

In your class, do something like this:

public void setSqlResource(Resource sqlResource) {
    this.sqlResource = sqlResource;
}

And then in your application context file, in the bean definition, just set a property:

<bean id="someBean" class="...">
    <property name="sqlResource" value="classpath:com/somecompany/sql/sql.txt" />
</bean>

And Spring should be clever enough to load up the file from the classpath and give it to your bean as a resource.

You could also look into PropertyPlaceholderConfigurer, and store all your SQL in property files and just inject each one separately where needed. There are lots of options.

WHERE Clause to find all records in a specific month

I find it easier to pass a value as a temporal data type (e.g. DATETIME) then use temporal functionality, specifically DATEADD and DATEPART, to find the start and end dates for the period, in this case the month e.g. this finds the start date and end date pair for the current month, just substitute CURRENT_TIMESTAMP for you parameter of of type DATETIME (note the 1990-01-01 value is entirely arbitrary):

SELECT DATEADD(M, 
          DATEDIFF(M, '1990-01-01T00:00:00.000', CURRENT_TIMESTAMP), 
          '1990-01-01T00:00:00.000'), 
       DATEADD(M, 
          DATEDIFF(M, '1990-01-01T00:00:00.000', CURRENT_TIMESTAMP), 
          '1990-01-31T23:59:59.997')

How to prettyprint a JSON file?

The json module already implements some basic pretty printing with the indent parameter that specifies how many spaces to indent by:

>>> import json
>>>
>>> your_json = '["foo", {"bar":["baz", null, 1.0, 2]}]'
>>> parsed = json.loads(your_json)
>>> print(json.dumps(parsed, indent=4, sort_keys=True))
[
    "foo", 
    {
        "bar": [
            "baz", 
            null, 
            1.0, 
            2
        ]
    }
]

To parse a file, use json.load():

with open('filename.txt', 'r') as handle:
    parsed = json.load(handle)

How can I change cols of textarea in twitter-bootstrap?

UPDATE: As of Bootstrap 3.0, the input-* classes described below for setting the width of input elements were removed. Instead use the col-* classes to set the width of input elements. Examples are provided in the documentation.


In Bootstrap 2.3, you'd use the input classes for setting the width.

<textarea class="input-mini"></textarea>
<textarea class="input-small"></textarea>
<textarea class="input-medium"></textarea>
<textarea class="input-large"></textarea>
<textarea class="input-xlarge"></textarea>
<textarea class="input-xxlarge"></textarea>?
<textarea class="input-block-level"></textarea>?

Do a find for "Control sizing" for examples in the documentation.

But for height I think you'd still use the rows attribute.

bs4.FeatureNotFound: Couldn't find a tree builder with the features you requested: lxml. Do you need to install a parser library?

For basic out of the box python with bs4 installed then you can process your xml with

soup = BeautifulSoup(html, "html5lib")

If however you want to use formatter='xml' then you need to

pip3 install lxml

soup = BeautifulSoup(html, features="xml")

MySQL Error: : 'Access denied for user 'root'@'localhost'

After trying all others answers, this it what finally worked for me

sudo mysql -- It does not ask me for any password

-- Then in MariaDB/MySQL console:
update mysql.user set plugin = 'mysql_native_password' where User='root';
FLUSH PRIVILEGES;
exit;

I found the answer in this post : https://medium.com/@chiragpatel_52497/solved-error-access-denied-for-user-root-localhost-of-mysql-programming-school-6e3611838d06

How to convert buffered image to image and vice-versa?

Example: say you have an 'image' you want to scale you will need a bufferedImage probably, and probably will be starting out with just 'Image' object. So this works I think... The AVATAR_SIZE is the target width we want our image to be:

Image imgData = image.getScaledInstance(Constants.AVATAR_SIZE, -1, Image.SCALE_SMOOTH);     

BufferedImage bufferedImage = new BufferedImage(imgData.getWidth(null), imgData.getHeight(null), BufferedImage.TYPE_INT_RGB);

bufferedImage.getGraphics().drawImage(imgData, 0, 0, null);

Mailbox unavailable. The server response was: 5.7.1 Unable to relay for [email protected]

Aahh got it... I got it working :)

Thanks Christopher, your suggesion is correct.

But, finding "Default SMTP Virtual Server" was tricky ;)

Even if you use IIS7 to deploy your web site, you have to open IIS6 Manager to configure SMTP server (why?).

I configured SMTP server as follows to make things work:

  1. Open IIS6 Manager using Control Panel --> Administrative Tools.
  2. Open SMTP Virtual Server properties.
  3. On General tab, Set IP address of the Web server instead of "All Unassigned".
  4. In Access tab, click on Relay button, this will open Relay Restrictions dialog.
  5. In relay computers list, add the loopback IP address i.e 127.0.0.1 and IP address of the Web server, so that they can pass/relay emails through the SMTP server.

How can I tell if a Java integer is null?

ints are value types; they can never be null. Instead, if the parsing failed, parseInt will throw a NumberFormatException that you need to catch.

Visual Studio Code always asking for git credentials

In case you are on Windows PC Then answer you are looking for!
Install Git for Windows

That's it!

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.

Setting a system environment variable from a Windows batch file?

For XP, I used a (free/donateware) tool called "RAPIDEE" (Rapid Environment Editor), but SETX is definitely sufficient for Win 7 (I did not know about this before).

Set up Python simpleHTTPserver on Windows

From Stack Overflow question What is the Python 3 equivalent of "python -m SimpleHTTPServer":

The following works for me:

python -m http.server [<portNo>]

Because I am using Python 3 the module SimpleHTTPServer has been replaced by http.server, at least in Windows.

How to prevent scanf causing a buffer overflow in C?

If you are using gcc, you can use the GNU-extension a specifier to have scanf() allocate memory for you to hold the input:

int main()
{
  char *str = NULL;

  scanf ("%as", &str);
  if (str) {
      printf("\"%s\"\n", str);
      free(str);
  }
  return 0;
}

Edit: As Jonathan pointed out, you should consult the scanf man pages as the specifier might be different (%m) and you might need to enable certain defines when compiling.

Initialize a string in C to empty string

Assigning string literals to char array is allowed only during declaration:

char string[] = "";

This declares string as a char array of size 1 and initializes it with \0.

Try this too:

char str1[] = ""; 
char str2[5] = ""; 
printf("%d, %d\n", sizeof(str1), sizeof(str2)); //prints 1, 5

How do I align views at the bottom of the screen?

Use android:layout_alignParentBottom="true" in your <RelativeLayout>.

This will definitely help.

No Main class found in NetBeans

You need to add }} to the end of your code.

Date constructor returns NaN in IE, but works in Firefox and Chrome

Here's my approach:

var parseDate = function(dateArg) {
    var dateValues = dateArg.split('-');
    var date = new Date(dateValues[0],dateValues[1],dateValues[2]);
    return date.format("m/d/Y");
}

replace ('-') with the delimeter you're using.

Install shows error in console: INSTALL FAILED CONFLICTING PROVIDER

i had this problem :

Installation did not succeed.
The application could not be installed: INSTALL_FAILED_CONFLICTING_PROVIDER

but it was not from provider of manifest the below library in my app has conflict with other app and the others can not be install:

implementation 'com.iceteck.silicompressorr:silicompressor:2.2.1'

Illegal access: this web application instance has been stopped already

If it's a local development tomcat launched from IDE, then restarting this IDE and rebuild project also helps.

Update:

You could also try to find if there is any running tomcat process in the background and kill it.

Getting all types that implement an interface

This worked for me (if you wish you could exclude system types in the lookup):

Type lookupType = typeof (IMenuItem);
IEnumerable<Type> lookupTypes = GetType().Assembly.GetTypes().Where(
        t => lookupType.IsAssignableFrom(t) && !t.IsInterface); 

Passing base64 encoded strings in URL

No, you would need to url-encode it, since base64 strings can contain the "+", "=" and "/" characters which could alter the meaning of your data - look like a sub-folder.

Valid base64 characters are below.

ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=

MYSQL: How to copy an entire row from one table to another in mysql with the second table having one extra column?

The safest way to do it is to fully specify the columns both for insertion and extraction. There's no guarantee (to the application) that either of these will be the order you think they may be.

insert into dues_storage (f1, f2, f3, cd)
    select f1, f2, f3, current_date() from dues where id = 5;

If you're worried about having to change many multiple PHP pages that do this (as you seem to indicate in the comment to another answer), this is ripe for a stored procedure. That way, all your PHP pages simply call the stored procedure with (for example) just the ID to copy and it controls the actual copy process. That way, there's only one place where you need to maintain the code, and, in my opinion, the DBMS is the right place to do it.

Explode string by one or more spaces or tabs

@OP it doesn't matter, you can just split on a space with explode. Until you want to use those values, iterate over the exploded values and discard blanks.

$str = "A      B      C      D";
$s = explode(" ",$str);
foreach ($s as $a=>$b){    
    if ( trim($b) ) {
     print "using $b\n";
    }
}

Difference between two numpy arrays in python

You can also use numpy.subtract

It has the advantage over the difference operator, -, that you do not have to transform the sequences (list or tuples) into a numpy arrays — you save the two commands:

array1 = np.array([1.1, 2.2, 3.3])
array2 = np.array([1, 2, 3])

Example: (Python 3.5)

import numpy as np
result = np.subtract([1.1, 2.2, 3.3], [1, 2, 3])
print ('the difference =', result)

which gives you

the difference = [ 0.1  0.2  0.3]

Remember, however, that if you try to subtract sequences (lists or tuples) with the - operator you will get an error. In this case, you need the above commands to transform the sequences in numpy arrays

Wrong Code:

print([1.1, 2.2, 3.3] - [1, 2, 3])

Using %s in C correctly - very basic level

Here goes:

char str[] = "This is the end";
char input[100];

printf("%s\n", str);
printf("%c\n", *str);

scanf("%99s", input);

String replacement in Objective-C

NSString objects are immutable (they can't be changed), but there is a mutable subclass, NSMutableString, that gives you several methods for replacing characters within a string. It's probably your best bet.

Check if a string is a palindrome

This C# method will check for even and odd length palindrome string (Recursive Approach):

public static bool IsPalindromeResursive(int rightIndex, int leftIndex, char[] inputString)
{
    if (rightIndex == leftIndex || rightIndex < leftIndex)
        return true;
    if (inputString[rightIndex] == inputString[leftIndex])
        return IsPalindromeResursive(--rightIndex, ++leftIndex, inputString);
    else
        return false;            
}

Laravel Query Builder where max id

Just like the docs say

DB::table('orders')->max('id');

How to undo last commit

Warning: Don't do this if you've already pushed

You want to do:

git reset HEAD~

If you don't want the changes and blow everything away:

git reset --hard HEAD~

How can I create an object based on an interface file definition in TypeScript?

If you want an empty object of an interface, you can do just:

var modal = <IModal>{};

The advantage of using interfaces in lieu of classes for structuring data is that if you don't have any methods on the class, it will show in compiled JS as an empty method. Example:

class TestClass {
    a: number;
    b: string;
    c: boolean;
}

compiles into

var TestClass = (function () {
    function TestClass() {
    }
    return TestClass;
})();

which carries no value. Interfaces, on the other hand, don't show up in JS at all while still providing the benefits of data structuring and type checking.

C# - How to get Program Files (x86) on Windows 64 bit

One way would be to look for the "ProgramFiles(x86)" environment variable:

String x86folder = Environment.GetEnvironmentVariable("ProgramFiles(x86)");

SELECTING with multiple WHERE conditions on same column

AND will return you an answer only when both volunteer and uploaded are present in your column. Otherwise it will return null value...

try using OR in your statement ...

SELECT contactid  WHERE flag = 'Volunteer' OR flag = 'Uploaded'

What is a good pattern for using a Global Mutex in C#?

A solution (for WPF) without WaitOne because it can cause an AbandonedMutexException. This solution uses the Mutex constructor that returns the createdNew boolean to check if the mutex is already created. It also uses the GetType().GUID so renaming an executable doesn't allow multiple instances.

Global vs local mutex see note in: https://docs.microsoft.com/en-us/dotnet/api/system.threading.mutex?view=netframework-4.8

private Mutex mutex;
private bool mutexCreated;

public App()
{
    string mutexId = $"Global\\{GetType().GUID}";
    mutex = new Mutex(true, mutexId, out mutexCreated);
}

protected override void OnStartup(StartupEventArgs e)
{
    base.OnStartup(e);
    if (!mutexCreated)
    {
        MessageBox.Show("Already started!");
        Shutdown();
    }
}

Because Mutex implements IDisposable it is released automatically but for completeness call dispose:

protected override void OnExit(ExitEventArgs e)
{
    base.OnExit(e);
    mutex.Dispose();
}

Move everything into a base class and add the allowEveryoneRule from the accepted answer. Also added ReleaseMutex though it doesn't look like it's really needed because it is released automatically by the OS (what if the application crashes and never calls ReleaseMutex would you need to reboot?).

public class SingleApplication : Application
{
    private Mutex mutex;
    private bool mutexCreated;

    public SingleApplication()
    {
        string mutexId = $"Global\\{GetType().GUID}";

        MutexAccessRule allowEveryoneRule = new MutexAccessRule(
            new SecurityIdentifier(WellKnownSidType.WorldSid, null),
            MutexRights.FullControl, 
            AccessControlType.Allow);
        MutexSecurity securitySettings = new MutexSecurity();
        securitySettings.AddAccessRule(allowEveryoneRule);

        // initiallyOwned: true == false + mutex.WaitOne()
        mutex = new Mutex(initiallyOwned: true, mutexId, out mutexCreated, securitySettings);        
    }

    protected override void OnExit(ExitEventArgs e)
    {
        base.OnExit(e);
        if (mutexCreated)
        {
            try
            {
                mutex.ReleaseMutex();
            }
            catch (ApplicationException ex)
            {
                MessageBox.Show(ex.Message, ex.GetType().FullName, MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
        mutex.Dispose();
    }

    protected override void OnStartup(StartupEventArgs e)
    {
        base.OnStartup(e);
        if (!mutexCreated)
        {
            MessageBox.Show("Already started!");
            Shutdown();
        }
    }
}

What is the right way to write my script 'src' url for a local development environment?

This is an old post but...

You can reference the working directory (the folder the .html file is located in) with ./, and the directory above that with ../

Example directory structure:

/html/public/
- index.html
- script2.js
- js/
   - script.js

To load script.js from inside index.html:

<script type="text/javascript" src="./js/script.js">

This goes to the current working directory (location of index.html) and then to the js folder, and then finds the script.

You could also specify ../ to go one directory above the working directory, to load things from there. But that is unusual.

How to check for valid email address?

The only really accurate way of distinguishing real, valid email addresses from invalid ones is to send mail to it. What counts as an email is surprisingly convoluted ("John Doe" <[email protected]>" actually is a valid email address), and you most likely want the email address to actually send mail to it later. After it passes some basic sanity checks (such as in Thomas's answer, has an @ and at least one . after the @), you should probably just send an email verification letter to the address, and wait for the user to follow a link embedded in the message to confirm that the email was valid.

jquery mobile background image

With JQM 1.4.2 this one works for me (Change theme to the used one):

.ui-page-theme-b, .ui-page-theme-b .ui-panel-wrapper {
    background: transparent url(../img/xxx) !important;
    background-repeat:repeat !important;
}

Created Button Click Event c#

Create the Button and add it to Form.Controls list to display it on your form:

Button buttonOk = new Button();
buttonOk.Location = new Point(295, 45);  //or what ever position you want it to give
buttonOk.Text = "OK"; //or what ever you want to write over it
buttonOk.Click += new EventHandler(buttonOk_Click);
this.Controls.Add(buttonOk); //here you add it to the Form's Controls list

Create the button click method here:

void buttonOk_Click(object sender, EventArgs e)
        {
            MessageBox.Show("clicked");
            this.Close(); //all your choice to close it or remove this line
        }

Show loading screen when navigating between routes in Angular 2

You could also use this existing solution. The demo is here. It looks like youtube loading bar. I just found it and added it to my own project.

How to detect the end of loading of UITableView

@folex answer is right.

But it will fail if the tableView has more than one section displayed at a time.

-(void) tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
   if([indexPath isEqual:((NSIndexPath*)[[tableView indexPathsForVisibleRows] lastObject])]){
    //end of loading

 }
}

how to set value of a input hidden field through javascript?

For me it works:

document.getElementById("checkyear").value = "1";
alert(document.getElementById("checkyear").value);

http://jsfiddle.net/zKNqg/

Maybe your JS is not executed and you need to add a function() {} around it all.

How To Format A Block of Code Within a Presentation?

http://www.tohtml.com/ created syntax highlighted HTML code for lots of languages. It might be what you're looking for.

Hide all warnings in ipython

The accepted answer does not work in Jupyter (at least when using some libraries).

The Javascript solutions here only hide warnings that are already showing but not warnings that would be shown in the future.

To hide/unhide warnings in Jupyter and JupyterLab I wrote the following script that essentially toggles css to hide/unhide warnings.

%%javascript
(function(on) {
const e=$( "<a>Setup failed</a>" );
const ns="js_jupyter_suppress_warnings";
var cssrules=$("#"+ns);
if(!cssrules.length) cssrules = $("<style id='"+ns+"' type='text/css'>div.output_stderr { } </style>").appendTo("head");
e.click(function() {
    var s='Showing';  
    cssrules.empty()
    if(on) {
        s='Hiding';
        cssrules.append("div.output_stderr, div[data-mime-type*='.stderr'] { display:none; }");
    }
    e.text(s+' warnings (click to toggle)');
    on=!on;
}).click();
$(element).append(e);
})(true);

How to return images in flask response?

You use something like

from flask import send_file

@app.route('/get_image')
def get_image():
    if request.args.get('type') == '1':
       filename = 'ok.gif'
    else:
       filename = 'error.gif'
    return send_file(filename, mimetype='image/gif')

to send back ok.gif or error.gif, depending on the type query parameter. See the documentation for the send_file function and the request object for more information.

How do I setup the dotenv file in Node.js?

I am using NodeJS on windows 10. I used process.env.var-name to access the variables but failed because it gives me windows path variables as a JSON object, so I installed dotenv ( npm install dotenv ). dotenv gets process envirnoment variables from your project's .evn file

  1. npm install dotenv or yarn add dotenv

enter image description here

  1. const dotenv = require('dotenv'); dotenv.config();

enter image description here

  1. process.env.variable_name

enter image description here enter image description here

  1. output

enter image description here

LIKE vs CONTAINS on SQL Server

I think that CONTAINS took longer and used Merge because you had a dash("-") in your query adventure-works.com.

The dash is a break word so the CONTAINS searched the full-text index for adventure and than it searched for works.com and merged the results.

Launch Bootstrap Modal on page load

You can activate the modal without writing any JavaScript simply via data attributes.

The option "show" set to true shows the modal when initialized:

<div class="modal fade" tabindex="-1" role="dialog" data-show="true"></div>

Format SQL in SQL Server Management Studio

There is a special trick I discovered by accident.

  1. Select the query you wish to format.
  2. Ctrl+Shift+Q (This will open your query in the query designer)
  3. Then just go OK Voila! Query designer will format your query for you. Caveat is that you can only do this for statements and not procedural code, but its better than nothing.

How to make sure that a certain Port is not occupied by any other process

It's (Get-NetTCPConnection -LocalPort "port no.").OwningProcess

How to condense if/else into one line in Python?

There is the conditional expression:

a if cond else b

but this is an expression, not a statement.

In if statements, the if (or elif or else) can be written on the same line as the body of the block if the block is just one like:

if something: somefunc()
else: otherfunc()

but this is discouraged as a matter of formatting-style.

Convert hex string to int

Try with this:

long abc=convertString2Hex("1A2A3B");

private  long  convertString2Hex(String numberHexString)
{
    char[] ChaArray = numberHexString.toCharArray();
    long HexSum=0;
    long cChar =0;

    for(int i=0;i<numberHexString.length();i++ )
    {
        if( (ChaArray[i]>='0') && (ChaArray[i]<='9') )
            cChar = ChaArray[i] - '0';
        else
            cChar = ChaArray[i]-'A'+10;
        HexSum = 16 * HexSum + cChar;
    }
    return  HexSum;
}

Change icon-bar (?) color in bootstrap

Just one line of coding is enough.. just try this out. and you can adjust even thicknes of icon-bar with this by adding pixels.

HTML

<div class="navbar-header">
  <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#defaultNavbar1" aria-expanded="false"><span class="sr-only">Toggle navigation</span>

  <span class="icon-bar"></span>
  <span class="icon-bar"></span>
  <span class="icon-bar"></span>

  </button>
  <a class="navbar-brand" href="#" <span class="icon-bar"></span><img class="img-responsive brand" src="img/brand.png">
  </a></div>

CSS

    .navbar-toggle, .icon-bar {
    border:1px solid orange;
}

BOOM...

How to convert md5 string to normal text?

The idea of MD5 is that is a one-way hashing, so it can't be once the original value has been passed through the hashing algorithm (if at all).

You could (potentially) create a database table with a pairing of the original and the MD5 values but I guess that's highly impractical and poses a major security risk.

Is there an operator to calculate percentage in Python?

You could just divide your two numbers and multiply by 100. Note that this will throw an error if "whole" is 0, as asking what percentage of 0 a number is does not make sense:

def percentage(part, whole):
  return 100 * float(part)/float(whole)

Or with a % at the end:

 def percentage(part, whole):
  Percentage = 100 * float(part)/float(whole)
  return str(Percentage) + “%”

Or if the question you wanted it to answer was "what is 5% of 20", rather than "what percentage is 5 of 20" (a different interpretation of the question inspired by Carl Smith's answer), you would write:

def percentage(percent, whole):
  return (percent * whole) / 100.0

Correct way to handle conditional styling in React

The best way to handle styling is by using classes with set of css properties.

example:

<Component className={this.getColor()} />

getColor() {
    let class = "badge m2";
    class += this.state.count===0 ? "warning" : danger;
    return class;
}

C++ Double Address Operator? (&&)

This is C++11 code. In C++11, the && token can be used to mean an "rvalue reference".

How do I show the value of a #define at compile-time?

Take a look at the Boost documentation as well, regarding how you are using the macro:

In reference to BOOST_VERSION, from http://www.boost.org/doc/libs/1_37_0/libs/config/doc/html/boost_config/boost_macro_reference.html#boost_config.boost_macro_reference.boost_helper_macros:

Describes the boost version number in XXYYZZ format such that: (BOOST_VERSION % 100) is the sub-minor version, ((BOOST_VERSION / 100) % 1000) is the minor version, and (BOOST_VERSION / 100000) is the major version.

How do I get the value of text input field using JavaScript?

There are various methods to get an input textbox value directly (without wrapping the input element inside a form element):

Method 1:

document.getElementById('textbox_id').value to get the value of desired box

For example, document.getElementById("searchTxt").value;

 

Note: Method 2,3,4 and 6 returns a collection of elements, so use [whole_number] to get the desired occurrence. For the first element, use [0], for the second one use 1, and so on...

Method 2:

Use document.getElementsByClassName('class_name')[whole_number].value which returns a Live HTMLCollection

For example, document.getElementsByClassName("searchField")[0].value; if this is the first textbox in your page.

Method 3:

Use document.getElementsByTagName('tag_name')[whole_number].value which also returns a live HTMLCollection

For example, document.getElementsByTagName("input")[0].value;, if this is the first textbox in your page.

Method 4:

document.getElementsByName('name')[whole_number].value which also >returns a live NodeList

For example, document.getElementsByName("searchTxt")[0].value; if this is the first textbox with name 'searchtext' in your page.

Method 5:

Use the powerful document.querySelector('selector').value which uses a CSS selector to select the element

For example, document.querySelector('#searchTxt').value; selected by id
document.querySelector('.searchField').value; selected by class
document.querySelector('input').value; selected by tagname
document.querySelector('[name="searchTxt"]').value; selected by name

Method 6:

document.querySelectorAll('selector')[whole_number].value which also uses a CSS selector to select elements, but it returns all elements with that selector as a static Nodelist.

For example, document.querySelectorAll('#searchTxt')[0].value; selected by id
document.querySelectorAll('.searchField')[0].value; selected by class
document.querySelectorAll('input')[0].value; selected by tagname
document.querySelectorAll('[name="searchTxt"]')[0].value; selected by name

Support

Browser          Method1   Method2  Method3  Method4    Method5/6
IE6              Y(Buggy)   N        Y        Y(Buggy)   N
IE7              Y(Buggy)   N        Y        Y(Buggy)   N
IE8              Y          N        Y        Y(Buggy)   Y
IE9              Y          Y        Y        Y(Buggy)   Y
IE10             Y          Y        Y        Y          Y
FF3.0            Y          Y        Y        Y          N    IE=Internet Explorer
FF3.5/FF3.6      Y          Y        Y        Y          Y    FF=Mozilla Firefox
FF4b1            Y          Y        Y        Y          Y    GC=Google Chrome
GC4/GC5          Y          Y        Y        Y          Y    Y=YES,N=NO
Safari4/Safari5  Y          Y        Y        Y          Y
Opera10.10/
Opera10.53/      Y          Y        Y        Y(Buggy)   Y
Opera10.60
Opera 12         Y          Y        Y        Y          Y

Useful links

  1. To see the support of these methods with all the bugs including more details click here
  2. Difference Between Static collections and Live collections click Here
  3. Difference Between NodeList and HTMLCollection click Here

CSS: Set a background color which is 50% of the width of the window

This is an example that will work on most browsers.
Basically you use two background colors, the first one starting from 0% and ending at 50% and the second one starting from 51% and ending at 100%

I'm using horizontal orientation:

background: #000000;
background: -moz-linear-gradient(left,  #000000 0%, #000000 50%, #ffffff 51%, #ffffff 100%);
background: -webkit-gradient(linear, left top, right top, color-stop(0%,#000000), color-stop(50%,#000000), color-stop(51%,#ffffff), color-stop(100%,#ffffff));
background: -webkit-linear-gradient(left,  #000000 0%,#000000 50%,#ffffff 51%,#ffffff 100%);
background: -o-linear-gradient(left,  #000000 0%,#000000 50%,#ffffff 51%,#ffffff 100%);
background: -ms-linear-gradient(left,  #000000 0%,#000000 50%,#ffffff 51%,#ffffff 100%);
background: linear-gradient(to right,  #000000 0%,#000000 50%,#ffffff 51%,#ffffff 100%);
filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#000000', endColorstr='#ffffff',GradientType=1 );

For different adjustments you could use http://www.colorzilla.com/gradient-editor/

How to print HTML content on click of a button, but not the page?

I Want See This

Example http://jsfiddle.net/35vAN/

    <html>
<head>
<script type="text/javascript" src="http://jqueryjs.googlecode.com/files/jquery-1.3.1.min.js" > </script> 
<script type="text/javascript">

    function PrintElem(elem)
    {
        Popup($(elem).html());
    }

    function Popup(data) 
    {
        var mywindow = window.open('', 'my div', 'height=400,width=600');
        mywindow.document.write('<html><head><title>my div</title>');
        /*optional stylesheet*/ //mywindow.document.write('<link rel="stylesheet" href="main.css" type="text/css" />');
        mywindow.document.write('</head><body >');
        mywindow.document.write(data);
        mywindow.document.write('</body></html>');

        mywindow.print();
        mywindow.close();

        return true;
    }

</script>
</head>
<body>

<div id="mydiv">
    This will be printed. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque a quam at nibh adipiscing interdum. Nulla vitae accumsan ante. 
</div>

<div>
    This will not be printed.
</div>

<div id="anotherdiv">
    Nor will this.
</div>

<input type="button" value="Print Div" onclick="PrintElem('#mydiv')" />

</body>

</html>

How to add Certificate Authority file in CentOS 7

Complete instruction is as follow:

  1. Extract Private Key from PFX

openssl pkcs12 -in myfile.pfx -nocerts -out private-key.pem -nodes

  1. Extract Certificate from PFX

openssl pkcs12 -in myfile.pfx -nokeys -out certificate.pem

  1. install certificate

yum install -y ca-certificates,

cp your-cert.pem /etc/pki/ca-trust/source/anchors/your-cert.pem ,

update-ca-trust ,

update-ca-trust force-enable

Hope to be useful

how to call an ASP.NET c# method using javascript

PageMethod an easier and faster approach for Asp.Net AJAX We can easily improve user experience and performance of web applications by unleashing the power of AJAX. One of the best things which I like in AJAX is PageMethod.

PageMethod is a way through which we can expose server side page's method in java script. This brings so many opportunities we can perform lots of operations without using slow and annoying post backs.

In this post I am showing the basic use of ScriptManager and PageMethod. In this example I am creating a User Registration form, in which user can register against his email address and password. Here is the markup of the page which I am going to develop:

<body>
    <form id="form1" runat="server">
    <div>
        <fieldset style="width: 200px;">
            <asp:Label ID="lblEmailAddress" runat="server" Text="Email Address"></asp:Label>
            <asp:TextBox ID="txtEmail" runat="server"></asp:TextBox>
            <asp:Label ID="lblPassword" runat="server" Text="Password"></asp:Label>
            <asp:TextBox ID="txtPassword" runat="server"></asp:TextBox>
        </fieldset>
        <div>
        </div>
        <asp:Button ID="btnCreateAccount" runat="server" Text="Signup"  />
    </div>
    </form>
</body>
</html>

To setup page method, first you have to drag a script manager on your page.

<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true">
</asp:ScriptManager>

Also notice that I have changed EnablePageMethods="true".
This will tell ScriptManager that I am going to call PageMethods from client side.

Now next step is to create a Server Side function.
Here is the function which I created, this function validates user's input:

[WebMethod]
public static string RegisterUser(string email, string password)
{
    string result = "Congratulations!!! your account has been created.";
    if (email.Length == 0)//Zero length check
    {
        result = "Email Address cannot be blank";
    }
    else if (!email.Contains(".") || !email.Contains("@")) //some other basic checks
    {
        result = "Not a valid email address";
    }
    else if (!email.Contains(".") || !email.Contains("@")) //some other basic checks
    {
        result = "Not a valid email address";
    }

    else if (password.Length == 0)
    {
        result = "Password cannot be blank";
    }
    else if (password.Length < 5)
    {
        result = "Password cannot be less than 5 chars";
    }

    return result;
}

To tell script manager that this method is accessible through javascript we need to ensure two things:
First: This method should be 'public static'.
Second: There should be a [WebMethod] tag above method as written in above code.

Now I have created server side function which creates account. Now we have to call it from client side. Here is how we can call that function from client side:

<script type="text/javascript">
    function Signup() {
        var email = document.getElementById('<%=txtEmail.ClientID %>').value;
        var password = document.getElementById('<%=txtPassword.ClientID %>').value;

        PageMethods.RegisterUser(email, password, onSucess, onError);

        function onSucess(result) {
            alert(result);
        }

        function onError(result) {
            alert('Cannot process your request at the moment, please try later.');
        }
    }
</script>

To call my server side method Register user, ScriptManager generates a proxy function which is available in PageMethods.
My server side function has two paramaters i.e. email and password, after that parameters we have to give two more function names which will be run if method is successfully executed (first parameter i.e. onSucess) or method is failed (second parameter i.e. result).

Now every thing seems ready, and now I have added OnClientClick="Signup();return false;" on my Signup button. So here complete code of my aspx page :

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true">
        </asp:ScriptManager>
        <fieldset style="width: 200px;">
            <asp:Label ID="lblEmailAddress" runat="server" Text="Email Address"></asp:Label>
            <asp:TextBox ID="txtEmail" runat="server"></asp:TextBox>
            <asp:Label ID="lblPassword" runat="server" Text="Password"></asp:Label>
            <asp:TextBox ID="txtPassword" runat="server"></asp:TextBox>
        </fieldset>
        <div>
        </div>
        <asp:Button ID="btnCreateAccount" runat="server" Text="Signup" OnClientClick="Signup();return false;" />
    </div>
    </form>
</body>
</html>

<script type="text/javascript">
    function Signup() {
        var email = document.getElementById('<%=txtEmail.ClientID %>').value;
        var password = document.getElementById('<%=txtPassword.ClientID %>').value;

        PageMethods.RegisterUser(email, password, onSucess, onError);

        function onSucess(result) {
            alert(result);
        }

        function onError(result) {
            alert('Cannot process your request at the moment, please try later.');
        }
    }
</script>

Best Timer for using in a Windows service

I know this thread is a little old but it came in handy for a specific scenario I had and I thought it worth while to note that there is another reason why System.Threading.Timer might be a good approach. When you have to periodically execute a Job that might take a long time and you want to ensure that the entire waiting period is used between jobs or if you don't want the job to run again before the previous job has finished in the case where the job takes longer than the timer period. You could use the following:

using System;
using System.ServiceProcess;
using System.Threading;

    public partial class TimerExampleService : ServiceBase
    {
        private AutoResetEvent AutoEventInstance { get; set; }
        private StatusChecker StatusCheckerInstance { get; set; }
        private Timer StateTimer { get; set; }
        public int TimerInterval { get; set; }

        public CaseIndexingService()
        {
            InitializeComponent();
            TimerInterval = 300000;
        }

        protected override void OnStart(string[] args)
        {
            AutoEventInstance = new AutoResetEvent(false);
            StatusCheckerInstance = new StatusChecker();

            // Create the delegate that invokes methods for the timer.
            TimerCallback timerDelegate =
                new TimerCallback(StatusCheckerInstance.CheckStatus);

            // Create a timer that signals the delegate to invoke 
            // 1.CheckStatus immediately, 
            // 2.Wait until the job is finished,
            // 3.then wait 5 minutes before executing again. 
            // 4.Repeat from point 2.
            Console.WriteLine("{0} Creating timer.\n",
                DateTime.Now.ToString("h:mm:ss.fff"));
            //Start Immediately but don't run again.
            StateTimer = new Timer(timerDelegate, AutoEventInstance, 0, Timeout.Infinite);
            while (StateTimer != null)
            {
                //Wait until the job is done
                AutoEventInstance.WaitOne();
                //Wait for 5 minutes before starting the job again.
                StateTimer.Change(TimerInterval, Timeout.Infinite);
            }
            //If the Job somehow takes longer than 5 minutes to complete then it wont matter because we will always wait another 5 minutes before running again.
        }

        protected override void OnStop()
        {
            StateTimer.Dispose();
        }
    }

    class StatusChecker
        {

            public StatusChecker()
            {
            }

            // This method is called by the timer delegate.
            public void CheckStatus(Object stateInfo)
            {
                AutoResetEvent autoEvent = (AutoResetEvent)stateInfo;
                Console.WriteLine("{0} Start Checking status.",
                    DateTime.Now.ToString("h:mm:ss.fff"));
                //This job takes time to run. For example purposes, I put a delay in here.
                int milliseconds = 5000;
                Thread.Sleep(milliseconds);
                //Job is now done running and the timer can now be reset to wait for the next interval
                Console.WriteLine("{0} Done Checking status.",
                    DateTime.Now.ToString("h:mm:ss.fff"));
                autoEvent.Set();
            }
        }

Get the value of input text when enter key pressed

$("input").on("keydown",function search(e) {
    if(e.keyCode == 13) {
        alert($(this).val());
    }
});

jsFiddle example : http://jsfiddle.net/NH8K2/1/

Angular - Use pipes in services and components

If you want to use your custom pipe in your components, you can add

@Injectable({
  providedIn: 'root'
})

annotation to your custom pipe. Then, you can use it as a service

How can I solve ORA-00911: invalid character error?

If a special character other than $, _, and # is used in the name of a column or table, the name must be enclosed in double quotations. Link

How to manually deploy artifacts in Nexus Repository Manager OSS 3

You can upload artifacts via their native publishing capabilities (e.g. maven deploy, npm publish).

You can also upload artifacts to "raw" repositories via a simple curl request, e.g.

curl --fail -u admin:admin123 --upload-file foo.jar 'http://my-nexus-server.com:8081/repository/my-raw-repo/'

Best way to remove the last character from a string built with stringbuilder

I recommend, you change your loop algorithm:

  • Add the comma not AFTER the item, but BEFORE
  • Use a boolean variable, that starts with false, do suppress the first comma
  • Set this boolean variable to true after testing it

Map implementation with duplicate keys

If you want iterate about a list of key-value-pairs (as you wrote in the comment), then a List or an array should be better. First combine your keys and values:

public class Pair
{
   public Class1 key;
   public Class2 value;

   public Pair(Class1 key, Class2 value)
   {
      this.key = key;
      this.value = value;
   }

}

Replace Class1 and Class2 with the types you want to use for keys and values.

Now you can put them into an array or a list and iterate over them:

Pair[] pairs = new Pair[10];
...
for (Pair pair : pairs)
{
   ...
}

Accessing a property in a parent Component

Since the parent-child interaction is not an easy task to do. But by having a reference for the parent component in the child component it would be much easier to interact. In my method, you need to first pass a reference of the parent component by calling the function of the child component. Here is the for this method.

The Code For Child Component.

    import { Component, Input,ElementRef,Renderer2 } from '@angular/core';

    import { ParentComponent } from './parent.component';

    @Component({
      selector: 'qb-child',
      template: `<div class="child"><button (click)="parentClickFun()">Show text Of Parent Element</button><button (click)="childClickFun()">Show text Of Child Element</button><ng-content></ng-content></div>`,
      styleUrls: ['./app.component.css']
    })
    export class ChildComponent  {
      constructor(private el: ElementRef,private rend: Renderer2){

      };

      qbParent:ParentComponent; 
      getParent(parentEl):void{
        this.qbParent=parentEl;
        console.log(this.el.nativeElement.innerText);
      }
      @Input() name: string;
      childClickFun():void{
        console.log("Properties of Child Component is Accessed");
      }

      parentClickFun():void{
        this.qbParent.callFun();
      }
    }

This is Code for parent Component

import { Component, Input , AfterViewInit,ContentChild,ElementRef,Renderer2} from '@angular/core';

import { ChildComponent } from './child.component';

@Component({
  selector: 'qb-parent',
  template: `<div class="parent"><ng-content></ng-content></div>`,
  styleUrls: ['./app.component.css']
})
export class ParentComponent implements AfterViewInit {
  constructor(private el: ElementRef,private rend: Renderer2){

  };
  @Input() name: string;
  @ContentChild(ChildComponent,{read:ChildComponent,static:true}) qbChild:ChildComponent;

  ngAfterViewInit():void{
    this.qbChild.getParent(this);
  }

  callFun():void{
    console.log("Properties of Parent Component is Accessed");
  }

}

The Html Code

<qb-parent>
  This is Parent
  <qb-child>
    This is Child
  </qb-child>
</qb-parent>

Here we pass the parent component by calling a function of the child component. The link below is an example of this method. Click here!

Android turn On/Off WiFi HotSpot programmatically

Applies to Oreo+ only...

I made an app with code here on GitHub which uses reflection and DexMaker to 'get at' Oreo's tethering functionality, which is now in ConnectionManager, rather than WifiManager.

The stuff in WifiManager is good only for a closed wifi network (which explained the Closed bit in the class names!).

More explanation https://stackoverflow.com/a/49356255/772333.

Does "\d" in regex mean a digit?

Info regarding .NET / C#:

Decimal digit character: \d \d matches any decimal digit. It is equivalent to the \p{Nd} regular expression pattern, which includes the standard decimal digits 0-9 as well as the decimal digits of a number of other character sets.

If ECMAScript-compliant behavior is specified, \d is equivalent to [0-9]. For information on ECMAScript regular expressions, see the "ECMAScript Matching Behavior" section in Regular Expression Options.

Info: https://docs.microsoft.com/en-us/dotnet/standard/base-types/character-classes-in-regular-expressions#decimal-digit-character-d

Watch multiple $scope attributes

Here's a solution very similar to your original pseudo-code that actually works:

$scope.$watch('[item1, item2] | json', function () { });

EDIT: Okay, I think this is even better:

$scope.$watch('[item1, item2]', function () { }, true);

Basically we're skipping the json step, which seemed dumb to begin with, but it wasn't working without it. They key is the often omitted 3rd parameter which turns on object equality as opposed to reference equality. Then the comparisons between our created array objects actually work right.

Insert PHP code In WordPress Page and Post

You can't use PHP in the WordPress back-end Page editor. Maybe with a plugin you can, but not out of the box.

The easiest solution for this is creating a shortcode. Then you can use something like this

function input_func( $atts ) {
    extract( shortcode_atts( array(
        'type' => 'text',
        'name' => '',
    ), $atts ) );

    return '<input name="' . $name . '" id="' . $name . '" value="' . (isset($_GET\['from'\]) && $_GET\['from'\] ? $_GET\['from'\] : '') . '" type="' . $type . '" />';
}
add_shortcode( 'input', 'input_func' );

See the Shortcode_API.

Error: Cannot pull with rebase: You have unstaged changes

Do git status, this will show you what files have changed. Since you stated that you don't want to keep the changes you can do git checkout -- <file name> or git reset --hard to get rid of the changes.

For the most part, git will tell you what to do about changes. For example, your error message said to git stash your changes. This would be if you wanted to keep them. After pulling, you would then do git stash pop and your changes would be reapplied.

git status also has how to get rid of changes depending on if the file is staged for commit or not.

Access cell value of datatable

string abc= dt.Rows[0]["column name"].ToString();

How to set the DefaultRoute to another Route in React Router

The problem with using <Redirect from="/" to="searchDashboard" /> is if you have a different URL, say /indexDashboard and the user hits refresh or gets a URL sent to them, the user will be redirected to /searchDashboard anyway.

If you wan't users to be able to refresh the site or send URLs use this:

<Route exact path="/" render={() => (
    <Redirect to="/searchDashboard"/>
)}/>

Use this if searchDashboard is behind login:

<Route exact path="/" render={() => (
  loggedIn ? (
    <Redirect to="/searchDashboard"/>
  ) : (
    <Redirect to="/login"/>
  )
)}/>

Why does sudo change the PATH?

Works now using sudo from the karmic repositories. Details from my configuration:

root@sphinx:~# cat /etc/sudoers | grep -v -e '^$' -e '^#'
Defaults    env_reset
Defaults    secure_path="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/opt/grub-1.96/sbin:/opt/grub-1.96/bin"
root    ALL=(ALL) ALL
%admin ALL=(ALL) ALL
root@sphinx:~# cat /etc/apt/sources.list
deb http://au.archive.ubuntu.com/ubuntu/ jaunty main restricted universe
deb-src http://au.archive.ubuntu.com/ubuntu/ jaunty main restricted universe

deb http://au.archive.ubuntu.com/ubuntu/ jaunty-updates main restricted universe
deb-src http://au.archive.ubuntu.com/ubuntu/ jaunty-updates main restricted universe

deb http://security.ubuntu.com/ubuntu jaunty-security main restricted universe
deb-src http://security.ubuntu.com/ubuntu jaunty-security main restricted universe

deb http://au.archive.ubuntu.com/ubuntu/ karmic main restricted universe
deb-src http://au.archive.ubuntu.com/ubuntu/ karmic main restricted universe

deb http://au.archive.ubuntu.com/ubuntu/ karmic-updates main restricted universe
deb-src http://au.archive.ubuntu.com/ubuntu/ karmic-updates main restricted universe

deb http://security.ubuntu.com/ubuntu karmic-security main restricted universe
deb-src http://security.ubuntu.com/ubuntu karmic-security main restricted universe
root@sphinx:~# 

root@sphinx:~# cat /etc/apt/preferences 
Package: sudo
Pin: release a=karmic-security
Pin-Priority: 990

Package: sudo
Pin: release a=karmic-updates
Pin-Priority: 960

Package: sudo
Pin: release a=karmic
Pin-Priority: 930

Package: *
Pin: release a=jaunty-security
Pin-Priority: 900

Package: *
Pin: release a=jaunty-updates
Pin-Priority: 700

Package: *
Pin: release a=jaunty
Pin-Priority: 500

Package: *
Pin: release a=karmic-security
Pin-Priority: 450

Package: *
Pin: release a=karmic-updates
Pin-Priority: 250

Package: *
Pin: release a=karmic
Pin-Priority: 50
root@sphinx:~# apt-cache policy sudo
sudo:
  Installed: 1.7.0-1ubuntu2
  Candidate: 1.7.0-1ubuntu2
  Package pin: 1.7.0-1ubuntu2
  Version table:
 *** 1.7.0-1ubuntu2 930
         50 http://au.archive.ubuntu.com karmic/main Packages
        100 /var/lib/dpkg/status
     1.6.9p17-1ubuntu3 930
        500 http://au.archive.ubuntu.com jaunty/main Packages
root@sphinx:~# echo $PATH
/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/opt/grub-1.96/sbin:/opt/grub-1.96/bin
root@sphinx:~# exit
exit
abolte@sphinx:~$ echo $PATH
/home/abolte/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/opt/grub-1.96/sbin:/opt/grub-1.96/bin:/opt/chromium-17593:/opt/grub-1.96/sbin:/opt/grub-1.96/bin:/opt/xpra-0.0.6/bin
abolte@sphinx:~$ 

It's wonderful to finally have this solved without using a hack.

gnuplot - adjust size of key/legend

To adjust the length of the samples:

set key samplen X

(default is 4)

To adjust the vertical spacing of the samples:

set key spacing X

(default is 1.25)

and (for completeness), to adjust the fontsize:

set key font "<face>,<size>"

(default depends on the terminal)

And of course, all these can be combined into one line:

set key samplen 2 spacing .5 font ",8"

Note that you can also change the position of the key using set key at <position> or any one of the pre-defined positions (which I'll just defer to help key at this point)

download csv file from web api in angular js

I think the best way to download any file generated by REST call is to use window.location example :

_x000D_
_x000D_
    $http({_x000D_
        url: url,_x000D_
        method: 'GET'_x000D_
    })_x000D_
    .then(function scb(response) {_x000D_
        var dataResponse = response.data;_x000D_
        //if response.data for example is : localhost/export/data.csv_x000D_
        _x000D_
        //the following will download the file without changing the current page location_x000D_
        window.location = 'http://'+ response.data_x000D_
    }, function(response) {_x000D_
      showWarningNotification($filter('translate')("global.errorGetDataServer"));_x000D_
    });
_x000D_
_x000D_
_x000D_

How to deal with SettingWithCopyWarning in Pandas

This topic is really confusing with Pandas. Luckily, it has a relatively simple solution.

The problem is that it is not always clear whether data filtering operations (e.g. loc) return a copy or a view of the DataFrame. Further use of such filtered DataFrame could therefore be confusing.

The simple solution is (unless you need to work with very large sets of data):

Whenever you need to update any values, always make sure that you explicitly copy the DataFrame before the assignment.

df  # Some DataFrame
df = df.loc[:, 0:2]  # Some filtering (unsure whether a view or copy is returned)
df = df.copy()  # Ensuring a copy is made
df[df["Name"] == "John"] = "Johny"  # Assignment can be done now (no warning)

Why do people say that Ruby is slow?

Ruby is slower than C++ at a number of easily measurable tasks (e.g., doing code that is heavily dependent on floating point). This is not very surprising, but enough justification for some people to say that “Ruby is Slow” without qualification. They don't count the fact that it is far easier and safer to write Ruby code than C++.

The best fix is to use targeted modules written in another language (e.g., C, C++, Fortran) in your Ruby code. Those can do the heavy lifting and your scripts can focus on higher level coordination issues.

What is the difference between required and ng-required?

The HTML attribute required="required" is a statement telling the browser that this field is required in order for the form to be valid. (required="required" is the XHTML form, just using required is equivalent)

The Angular attribute ng-required="yourCondition" means 'isRequired(yourCondition)' and sets the HTML attribute dynamically for you depending on your condition.

Also note that the HTML version is confusing, it is not possible to write something conditional like required="true" or required="false", only the presence of the attribute matters (present means true) ! This is where Angular helps you out with ng-required.

Oracle database: How to read a BLOB?

If you use the Oracle native data provider rather than the Microsoft driver then you can get at all field types

Dim cn As New Oracle.DataAccess.Client.OracleConnection
Dim cm As New Oracle.DataAccess.Client.OracleCommand
Dim dr As Oracle.DataAccess.Client.OracleDataReader

The connection string does not require a Provider value so you would use something like:

"Data Source=myOracle;UserID=Me;Password=secret"

Open the connection:

cn.ConnectionString = "Data Source=myOracle;UserID=Me;Password=secret"
cn.Open()

Attach the command and set the Sql statement

cm.Connection = cn
cm.CommandText = strCommand

Set the Fetch size. I use 4000 because it's as big as a varchar can be

cm.InitialLONGFetchSize = 4000

Start the reader and loop through the records/columns

dr = cm.ExecuteReader

Do while dr.read()
    strMyLongString = dr(i)
Loop

You can be more specific with the read, eg dr.GetOracleString(i) dr.GetOracleClob(i) etc. if you first identify the data type in the column. If you're reading a LONG datatype then the simple dr(i) or dr.GetOracleString(i) works fine. The key is to ensure that the InitialLONGFetchSize is big enough for the datatype. Note also that the native driver does not support CommandBehavior.SequentialAccess for the data reader but you don't need it and also, the LONG field does not even have to be the last field in the select statement.

Java Programming: call an exe from Java and passing parameters

Below works for me if your exe depend on some dll or certain dependency then you need to set directory path. As mention below exePath mean folder where exe placed along with it's references files.

Exe application creating any temporaray file so it will create in folder mention in processBuilder.directory(...)

**

ProcessBuilder processBuilder = new ProcessBuilder(arguments);
processBuilder.redirectOutput(Redirect.PIPE);
processBuilder.directory(new File(exePath));
process = processBuilder.start();
int waitFlag = process.waitFor();// Wait to finish application execution.
if (waitFlag == 0) {
...
 int returnVal = process.exitValue();
} 

**

Remove final character from string

Simple:

st =  "abcdefghij"
st = st[:-1]

There is also another way that shows how it is done with steps:

list1 = "abcdefghij"
list2 = list(list1)
print(list2)
list3 = list2[:-1]
print(list3)

This is also a way with user input:

list1 = input ("Enter :")
list2 = list(list1)
print(list2)
list3 = list2[:-1]
print(list3)

To make it take away the last word in a list:

list1 = input("Enter :")
list2 = list1.split()
print(list2)
list3 = list2[:-1]
print(list3)

Installing Pandas on Mac OSX

I would recoment using macport or fink to install pandas:

  1. Install XCode from App Store, this will install 3 compilers, clang, gcc ("apple") and gcc ("normal")
  2. Install macports (www.macports.org) or fink (www.finkproject.org)
  3. Never use your mac python again, and install all python modules trough the fink/macport and enjoy it taking care dependencies for you.

Installing pandas in macports is as simple as: sudo port install py27-pandas

you usualy install macport in /opt/local and fink in /sw, I would advice (though this may be bad advice) you to symlink your fink/mac ports python to your system python as follows such that: /usr/bin/python -> /opt/local/Library/Frameworks/Python.framework/Versions/2.7/bin/python2.7

How can I simulate mobile devices and debug in Firefox Browser?

You could use the Firefox add-on User Agent Overrider. With this add-on you can use whatever user agent you want, for examlpe:

Firefox 28/Android: Mozilla/5.0 (Android; Mobile; rv:28.0) Gecko/24.0 Firefox/28.0

If your website detects mobile devices through the user agent then you can test your layout this way.


Update Nov '17:

Due to the release of Firefox 57 and the introduction of web extension this add-on sadly is no longer available. Alternatively you can edit the Firefox preference general.useragent.override in your configuration:

  1. In the address bar type about:config
  2. Search for general.useragent.override
  3. If the preference doesn't exist, right-click on the about:config page, click New, then select String
  4. Name the new preference general.useragent.override
  5. Set the value to the user agent you want

Uncaught Invariant Violation: Too many re-renders. React limits the number of renders to prevent an infinite loop

You must link an event in your onClick. Additionally, the click function must receive the event. See the example

export default function Component(props) {

    function clickEvent (event, variable){
        console.log(variable);
    }

    return (
        <div>
            <IconButton
                key="close"
                aria-label="Close"
                color="inherit"
                onClick={e => clickEvent(e, 10)}
            >
        </div>
    )
}

Working Copy Locked

I am sure It working fine for you

Goto top level SVN folder.

Right Click on folder(that has your svn files) -> TortoiseSVN -> CleanUp

This will surely solve your problem.

Difference in System. exit(0) , System.exit(-1), System.exit(1 ) in Java

As others answer 0 meaning success, otherwise.

If you using bat file (window) System.exit(x) will effect.

Code java (myapp):

if (error < 2){
    help();
    System.exit(-1);    
}
else{
    doSomthing();
    System.exit(0);
}

}

bat file:

java -jar myapp.jar
if %errorlevel% neq 0 exit /b %errorlevel%
rem -- next command if myapp is success --

What's the difference between select_related and prefetch_related in Django ORM?

As Django documentation says:

prefetch_related()

Returns a QuerySet that will automatically retrieve, in a single batch, related objects for each of the specified lookups.

This has a similar purpose to select_related, in that both are designed to stop the deluge of database queries that is caused by accessing related objects, but the strategy is quite different.

select_related works by creating an SQL join and including the fields of the related object in the SELECT statement. For this reason, select_related gets the related objects in the same database query. However, to avoid the much larger result set that would result from joining across a ‘many’ relationship, select_related is limited to single-valued relationships - foreign key and one-to-one.

prefetch_related, on the other hand, does a separate lookup for each relationship, and does the ‘joining’ in Python. This allows it to prefetch many-to-many and many-to-one objects, which cannot be done using select_related, in addition to the foreign key and one-to-one relationships that are supported by select_related. It also supports prefetching of GenericRelation and GenericForeignKey, however, it must be restricted to a homogeneous set of results. For example, prefetching objects referenced by a GenericForeignKey is only supported if the query is restricted to one ContentType.

More information about this: https://docs.djangoproject.com/en/2.2/ref/models/querysets/#prefetch-related

Error message Strict standards: Non-static method should not be called statically in php

return false is usually meant to terminate the object creation with a failure. It is as simple as that.

Regex date validation for yyyy-mm-dd

This will match yyyy-mm-dd and also yyyy-m-d:

^\d{4}\-(0?[1-9]|1[012])\-(0?[1-9]|[12][0-9]|3[01])$

Regular expression visualization

If you're looking for an exact match for yyyy-mm-dd then try this

^\d{4}\-(0[1-9]|1[012])\-(0[1-9]|[12][0-9]|3[01])$

or use this one if you need to find a date inside a string like The date is 2017-11-30

\d{4}\-(0?[1-9]|1[012])\-(0?[1-9]|[12][0-9]|3[01])*

https://regex101.com/r/acvpss/1

Fatal error: Call to undefined function imap_open() in PHP

The Installation Procedure is always the same, but the package-manager and package-name varies, depending which distribution, version and/or repository one uses. In general, the steps are:

a) at first, user privilege escalation is required, either obtained with the commands su or sudo.

b) then one can install the absent PHP module with a package manager.

c) after that, restarting the apache2 HTTP daemon is required to load the module.

d) at last, one can run php -m | grep imap to see if the PHP module is now available.

On Ubuntu the APT package php5-imap (or php-imap) can bei installed with apt-get:

apt-get install php5-imap
service apache2 restart

On Debian, the APT package php5-imap can be installed aptitude (or apt-get):

aptitude install php5-imap
apache2ctl graceful

On CentOS and Fedora the RPM package php-imap can be installed with yum (hint: the name of the package might be something alike php56w-imap or php71w-imap, when using Webtatic repo):

yum install php-imap
service httpd restart

On systemd systems, while using systemd units, the command to restart unit httpd.service is:

systemctl restart httpd.service

The solution stated above has the problem, that when the module was already referenced in:

/etc/php5/apache2/php.ini

It might throw a:

PHP Warning:  Module 'imap' already loaded in Unknown on line 0

That happens, because it is referenced in the default php.ini file (at least on Ubuntu 12.04) and a PHP module must at most be referenced once. Using INI snippets to load modules is suggested, while the the directory /etc/php5/conf.d/ (that path may also vary) is being scanned for INI files:

/etc/php5/conf.d/imap.ini

Ubuntu also features proprietary commands to manage PHP modules, to be executed before restarting the web-server:

php5enmod imap
php5dismod imap

Once the IMAP module is loaded into the server, the PHP IMAP Functions should then become available; best practice may be, to check if a module is even loaded, before attempting to utilize it.

How to make div go behind another div?

One possible could be like this,

HTML

<div class="box-left-mini">
    <div class="front">this div is infront</div>
    <div class="behind">
        this div is behind
    </div>
</div>

CSS

.box-left-mini{
float:left;
background-image:url(website-content/hotcampaign.png);
width:292px;
height:141px;
}
.front{
    background-color:lightgreen;
}
.behind{
    background-color:grey;
    position:absolute;
    width:100%;
    height:100%;
    top:0;
    z-index:-1;
}

http://jsfiddle.net/MgtWS/

But it really depends on the layout of your div elements i.e. if they are floating, or absolute positioned etc.

Convert string to date in bash

This worked for me :

date -d '20121212 7 days'
date -d '12-DEC-2012 7 days'
date -d '2012-12-12 7 days'
date -d '2012-12-12 4:10:10PM 7 days'
date -d '2012-12-12 16:10:55 7 days'

then you can format output adding parameter '+%Y%m%d'

Android, landscape only orientation?

Add this android:screenOrientation="landscape" to your <activity> tag in the manifest for the specific activity that you want to be in landscape.

Edit:

To toggle the orientation from the Activity code, call setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) other parameters can be found in the Android docs for ActivityInfo.

Why do we need to install gulp globally and locally?

The question "Why do we need to install gulp globally and locally?" can be broken down into the following two questions:

  1. Why do I need to install gulp locally if I've already installed it globally?

  2. Why do I need to install gulp globally if I've already installed it locally?

Several others have provided excellent answers to theses questions in isolation, but I thought it would be beneficial to consolidate the information in a unified answer.

Why do I need to install gulp locally if I've already installed it globally?

The rationale for installing gulp locally is comprised of several reasons:

  1. Including the dependencies of your project locally ensures the version of gulp (or other dependencies) used is the originally intended version.
  2. Node doesn't consider global modules by default when using require() (which you need to include gulp within your script). Ultimately, this is because the path to the global modules isn't added to NODE_PATH by default.
  3. According to the Node development team, local modules load faster. I can't say why this is, but this would seem to be more relevant to node's use in production (i.e. run-time dependencies) than in development (i.e. dev dependencies). I suppose this is a legitimate reason as some may care about whatever minor speed advantage is gained loading local vs. global modules, but feel free to raise your eyebrow at this reason.

Why do I need to install gulp globally if I've already installed it locally?

  1. The rationale for installing gulp globally is really just the convenience of having the gulp executable automatically found within your system path.

To avoid installing locally you can use npm link [package], but the link command as well as the install --global command doesn't seem to support the --save-dev option which means there doesn't appear to be an easy way to install gulp globally and then easily add whatever version that is to your local package.json file.

Ultimately, I believe it makes more sense to have the option of using global modules to avoid having to duplicate the installation of common tools across all your projects, especially in the case of development tools such as grunt, gulp, jshint, etc. Unfortunately it seems you end up fighting the tools a bit when you go against the grain.

Design Documents (High Level and Low Level Design Documents)

High-Level Design (HLD) involves decomposing a system into modules, and representing the interfaces & invocation relationships among modules. An HLD is referred to as software architecture.

LLD, also known as a detailed design, is used to design internals of the individual modules identified during HLD i.e. data structures and algorithms of the modules are designed and documented.

Now, HLD and LLD are actually used in traditional Approach (Function-Oriented Software Design) whereas, in OOAD, the system is seen as a set of objects interacting with each other.

As per the above definitions, a high-level design document will usually include a high-level architecture diagram depicting the components, interfaces, and networks that need to be further specified or developed. The document may also depict or otherwise refer to work flows and/or data flows between component systems.

Class diagrams with all the methods and relations between classes come under LLD. Program specs are covered under LLD. LLD describes each and every module in an elaborate manner so that the programmer can directly code the program based on it. There will be at least 1 document for each module. The LLD will contain - a detailed functional logic of the module in pseudo code - database tables with all elements including their type and size - all interface details with complete API references(both requests and responses) - all dependency issues - error message listings - complete inputs and outputs for a module.

How to convert between bytes and strings in Python 3?

The 'mangler' in the above code sample was doing the equivalent of this:

bytesThing = stringThing.encode(encoding='UTF-8')

There are other ways to write this (notably using bytes(stringThing, encoding='UTF-8'), but the above syntax makes it obvious what is going on, and also what to do to recover the string:

newStringThing = bytesThing.decode(encoding='UTF-8')

When we do this, the original string is recovered.

Note, using str(bytesThing) just transcribes all the gobbledegook without converting it back into Unicode, unless you specifically request UTF-8, viz., str(bytesThing, encoding='UTF-8'). No error is reported if the encoding is not specified.

HTTP Error 403.14 - Forbidden - The Web server is configured to not list the contents of this directory

I have one quick remedy for this. In fact I got this error because I had not set my web page as start page. When I did my web page(html /aspx) as set start page as shown below I got this error corrected.enter image description here

I don't know whether this solution will help others.

Getting Gradle dependencies in IntelliJ IDEA using Gradle build

In my case,I was getting error while refreshing gradle ('View'->Tool Windows->Gradle) tab and hit "refresh" and getting this error no such property gradleversion for class jetgradleplugin.

Had to install latest intellij compatible with gradle 5+

How to build and run Maven projects after importing into Eclipse IDE

When you add dependency in pom.xml , do a maven clean , and then maven build , it will add the jars into you project.

You can search dependency artifacts at http://mvnrepository.com/

And if it doesn't add jars it should give you errors which will mean that it is not able to fetch the jar, that could be due to broken repository or connection problems.

Well sometimes if it is one or two jars, better download them and add to build path , but with a lot of dependencies use maven.

How do I load an HTML page in a <div> using JavaScript?

try

async function load_home(){
  content.innerHTML = await (await fetch('home.html')).text();
}

_x000D_
_x000D_
async function load_home() {_x000D_
  let url = 'https://kamil-kielczewski.github.io/fractals/mandelbulb.html'_x000D_
_x000D_
  content.innerHTML = await (await fetch(url)).text();_x000D_
}
_x000D_
<div id="topBar"> <a href="#" onclick="load_home()"> HOME </a> </div>_x000D_
<div id="content"> </div>
_x000D_
_x000D_
_x000D_

Get names of all keys in the collection

Following the thread from @James Cropcho's answer, I landed on the following which I found to be super easy to use. It is a binary tool, which is exactly what I was looking for: mongoeye.

Using this tool it took about 2 minutes to get my schema exported from command line.

SELECT * FROM X WHERE id IN (...) with Dapper ORM

In my case I've used this:

var query = "select * from table where Id IN @Ids";
var result = conn.Query<MyEntity>(query, new { Ids = ids });

my variable "ids" in the second line is an IEnumerable of strings, also they can be integers I guess.

How do I convert a Python 3 byte-string variable into a regular string?

You had it nearly right in the last line. You want

str(bytes_string, 'utf-8')

because the type of bytes_string is bytes, the same as the type of b'abc'.

Why use prefixes on member variables in C++ classes

Some responses focus on refactoring, rather than naming conventions, as the way to improve readability. I don't feel that one can replace the other.

I've known programmers who are uncomfortable with using local declarations; they prefer to place all the declarations at the top of a block (as in C), so they know where to find them. I've found that, where scoping allows for it, declaring variables where they're first used decreases the time that I spend glancing backwards to find the declarations. (This is true for me even for small functions.) That makes it easier for me to understand the code I'm looking at.

I hope it's clear enough how this relates to member naming conventions: When members are uniformly prefixed, I never have to look back at all; I know the declaration won't even be found in the source file.

I'm sure that I didn't start out preferring these styles. Yet over time, working in environments where they were used consistently, I optimized my thinking to take advantage of them. I think it's possible that many folks who currently feel uncomfortable with them would also come to prefer them, given consistent usage.

What is LDAP used for?

Light weight directory access protocal is used to authenticate users to access AD information

RequestDispatcher.forward() vs HttpServletResponse.sendRedirect()

In the web development world, the term "redirect" is the act of sending the client an empty HTTP response with just a Location header containing the new URL to which the client has to send a brand new GET request. So basically:

  • Client sends a HTTP request to some.jsp.
  • Server sends a HTTP response back with Location: other.jsp header
  • Client sends a HTTP request to other.jsp (this get reflected in browser address bar!)
  • Server sends a HTTP response back with content of other.jsp.

You can track it with the web browser's builtin/addon developer toolset. Press F12 in Chrome/IE9/Firebug and check the "Network" section to see it.

Exactly the above is achieved by sendRedirect("other.jsp"). The RequestDispatcher#forward() doesn't send a redirect. Instead, it uses the content of the target page as HTTP response.

  • Client sends a HTTP request to some.jsp.
  • Server sends a HTTP response back with content of other.jsp.

However, as the original HTTP request was to some.jsp, the URL in browser address bar remains unchanged. Also, any request attributes set in the controller behind some.jsp will be available in other.jsp. This does not happen during a redirect because you're basically forcing the client to create a new HTTP request on other.jsp, hereby throwing away the original request on some.jsp including all of its attribtues.


The RequestDispatcher is extremely useful in the MVC paradigm and/or when you want to hide JSP's from direct access. You can put JSP's in the /WEB-INF folder and use a Servlet which controls, preprocesses and postprocesses the requests. The JSPs in the /WEB-INF folder are not directly accessible by URL, but the Servlet can access them using RequestDispatcher#forward().

You can for example have a JSP file in /WEB-INF/login.jsp and a LoginServlet which is mapped on an url-pattern of /login. When you invoke http://example.com/context/login, then the servlet's doGet() will be invoked. You can do any preprocessing stuff in there and finally forward the request like:

request.getRequestDispatcher("/WEB-INF/login.jsp").forward(request, response);

When you submit a form, you normally want to use POST:

<form action="login" method="post">

This way the servlet's doPost() will be invoked and you can do any postprocessing stuff in there (e.g. validation, business logic, login the user, etc).

If there are any errors, then you normally want to forward the request back to the same page and display the errors there next to the input fields and so on. You can use the RequestDispatcher for this.

If a POST is successful, you normally want to redirect the request, so that the request won't be resubmitted when the user refreshes the request (e.g. pressing F5 or navigating back in history).

User user = userDAO.find(username, password);
if (user != null) {
    request.getSession().setAttribute("user", user); // Login user.
    response.sendRedirect("home"); // Redirects to http://example.com/context/home after succesful login.
} else {
    request.setAttribute("error", "Unknown login, please try again."); // Set error.
    request.getRequestDispatcher("/WEB-INF/login.jsp").forward(request, response); // Forward to same page so that you can display error.
}

A redirect thus instructs the client to fire a new GET request on the given URL. Refreshing the request would then only refresh the redirected request and not the initial request. This will avoid "double submits" and confusion and bad user experiences. This is also called the POST-Redirect-GET pattern.

See also:

How do I unlock a SQLite database?

From your previous comments you said a -journal file was present.

This could mean that you have opened and (EXCLUSIVE?) transaction and have not yet committed the data. Did your program or some other process leave the -journal behind??

Restarting the sqlite process will look at the journal file and clean up any uncommitted actions and remove the -journal file.

Depend on a branch or tag using a git URL in a package.json?

If it helps anyone, I tried everything above (https w/token mode) - and still nothing was working. I got no errors, but nothing would be installed in node_modules or package_lock.json. If I changed the token or any letter in the repo name or user name, etc. - I'd get an error. So I knew I had the right token and repo name.

I finally realized it's because the name of the dependency I had in my package.json didn't match the name in the package.json of the repo I was trying to pull. Even npm install --verbose doesn't say there's any problem. It just seems to ignore the dependency w/o error.

How do I install imagemagick with homebrew?

You could try:

brew update && brew install imagemagick

Check if a row exists, otherwise insert

i'm writing my solution. my method doesn't stand 'if' or 'merge'. my method is easy.

INSERT INTO TableName (col1,col2)
SELECT @par1, @par2
   WHERE NOT EXISTS (SELECT col1,col2 FROM TableName
                     WHERE col1=@par1 AND col2=@par2)

For Example:

INSERT INTO Members (username)
SELECT 'Cem'
   WHERE NOT EXISTS (SELECT username FROM Members
                     WHERE username='Cem')

Explanation:

(1) SELECT col1,col2 FROM TableName WHERE col1=@par1 AND col2=@par2 It selects from TableName searched values

(2) SELECT @par1, @par2 WHERE NOT EXISTS It takes if not exists from (1) subquery

(3) Inserts into TableName (2) step values

How to enable native resolution for apps on iPhone 6 and 6 Plus?

You can add a launch screen file that appears to work for multiple screen sizes. I just added the MainStoryboard as a launch screen file and that stopped the app from scaling. I think I will need to add a permanent launch screen later, but that got the native resolution up and working quickly. In Xcode, go to your target, general and add the launch screen file there.

Launch Screen File

Binding value to input in Angular JS

Some times there are problems with funtion/features that do not interact with the DOM

try to change the value sharply and then assign the $scope

document.getElementById ("textWidget") value = "<NewVal>";
$scope.widget.title = "<NewVal>";

Change Placeholder Text using jQuery

You can use following code to update a placeholder by id:

$("#serMemtb").attr("placeholder", "Type a Location").val("").focus().blur();

The iOS Simulator deployment targets is set to 7.0, but the range of supported deployment target version for this platform is 8.0 to 12.1

if anybody is experiencing is issue while updating to the latest react native, try updating your pod file with

  use_flipper!
  post_install do |installer|
    flipper_post_install(installer)
    installer.pods_project.targets.each do |target|
      target.build_configurations.each do |config|
        config.build_settings.delete 'IPHONEOS_DEPLOYMENT_TARGET'
      end
    end
   end

Failed to resolve version for org.apache.maven.archetypes

If you are using eclipse, you can follow the steps here (maven in 5 min not working) for getting your proxy information. Once done follow the steps below:

  1. Go to Maven installation folder C:\apache-maven-3.1.0\conf\
  2. Copy settings.xml to C:\Users\[UserFolder]\.m2
  3. Modify the proxy in settings.xml based on the info that you get from the above link.

    <proxy>
      <active>true</active>
      <protocol>http</protocol>
      <host>your proxy</host>
      <port>your port</port>
    </proxy>
    
  4. Open eclipse

  5. Go to: Windows > Preferences > Maven > User Settings

  6. Browse the settings.xml from .m2 folder

  7. Click Update Settings

  8. Click Reindex

  9. Apply the changes and Click OK

You can now try to create Maven Project in Eclipse

How to align td elements in center

margin:auto; text-align, if this won't work - try adding display:block; and set there width:200px; (in case your TD is too small).

SharePoint 2013 get current user using JavaScript

How about this:

$.getJSON(_spPageContextInfo.webServerRelativeUrl + "/_api/web/currentuser")
.done(function(data){ 
    console.log(data.Title);
})
.fail(function() { console.log("Failed")});

Using GZIP compression with Spring Boot/MVC/JavaConfig with RESTful

To enable GZIP compression, you need to modify the configuration of the embedded Tomcat instance. To do so, you declare a EmbeddedServletContainerCustomizer bean in your Java configuration and then register a TomcatConnectorCustomizer with it.

For example:

@Bean
public EmbeddedServletContainerCustomizer servletContainerCustomizer() {
    return new EmbeddedServletContainerCustomizer() {
        @Override
        public void customize(ConfigurableEmbeddedServletContainerFactory factory) {
            ((TomcatEmbeddedServletContainerFactory) factory).addConnectorCustomizers(new TomcatConnectorCustomizer() {
                @Override
                public void customize(Connector connector) {
                    AbstractHttp11Protocol httpProtocol = (AbstractHttp11Protocol) connector.getProtocolHandler();
                    httpProtocol.setCompression("on");
                    httpProtocol.setCompressionMinSize(64);
                }
            });
        }
    };
}

See the Tomcat documentation for more details on the various compression configuration options that are available.

You say that you want to selectively enable compression. Depending on your selection criteria, then the above approach may be sufficient. It enables you to control compression by the request's user-agent, the response's size, and the response's mime type.

If this doesn't meet your needs then I believe you will have to perform the compression in your controller and return a byte[] response with a gzip content-encoding header.

Ignore parent padding

Your parent is 120px wide - that is 100 width + 20 padding on each side so you need to make your line 120px wide. Here's the code. Next time note that padding adds up to element width.

#parent
{
    width: 100px;
    padding: 10px;
    background-color: Red;
}

hr
{
    width: 120px;
    margin:0 -10px;
    position:relative;
}

Change font-weight of FontAwesome icons?

Another solution I've used to create lighter fontawesome icons, similar to the webkit-text-stroke approach but more portable, is to set the color of the icon to the same as the background (or transparent) and use text-shadow to create an outline:

.fa-outline-dark-gray {
    color: #fff;
    text-shadow: -1px -1px 0 #999,
            1px -1px 0 #999,
           -1px 1px 0 #999,
            1px 1px 0 #999;
}

It doesn't work in ie <10, but at least it's not restricted to webkit browsers.

Send array with Ajax to PHP script

dataString suggests the data is formatted in a string (and maybe delimted by a character).

$data = explode(",", $_POST['data']);
foreach($data as $d){
     echo $d;
}

if dataString is not a string but infact an array (what your question indicates) use JSON.

How to complete the RUNAS command in one line

The runas command does not allow a password on its command line. This is by design (and also the reason you cannot pipe a password to it as input). Raymond Chen says it nicely:

The RunAs program demands that you type the password manually. Why doesn't it accept a password on the command line?

This was a conscious decision. If it were possible to pass the password on the command line, people would start embedding passwords into batch files and logon scripts, which is laughably insecure.

In other words, the feature is missing to remove the temptation to use the feature insecurely.

Item frequency count in Python

If you don't want to use the standard dictionary method (looping through the list incrementing the proper dict. key), you can try this:

>>> from itertools import groupby
>>> myList = words.split() # ['apple', 'banana', 'apple', 'strawberry', 'banana', 'lemon']
>>> [(k, len(list(g))) for k, g in groupby(sorted(myList))]
[('apple', 2), ('banana', 2), ('lemon', 1), ('strawberry', 1)]

It runs in O(n log n) time.

How to do a num_rows() on COUNT query in codeigniter?

As per CI Docs we can use the following,

$this->db->where('account_status', $i); // OTHER CONDITIONS IF ANY
$this->db->from('account_status'); //TABLE NAME
echo $this->db->count_all_results();

If we want to get total rows in the table without any condition, simple use

echo $this->db->count_all_results('table_name'); // returns total_rows presented in the table

How can I check whether Google Maps is fully loaded?

You could check the GMap2.isLoaded() method every n milliseconds to see if the map and all its tiles were loaded (window.setTimeout() or window.setInterval() are your friends).

While this won't give you the exact event of the load completion, it should be good enough to trigger your Javascript.

How to round the double value to 2 decimal points?

I guess that you need a formatted output.

System.out.printf("%.2f",d);

How to change line-ending settings

For me what did the trick was running the command

git config auto.crlf false

inside the folder of the project, I wanted it specifically for one project.

That command changed the file in path {project_name}/.git/config (fyi .git is a hidden folder) by adding the lines

[auto]
    crlf = false

at the end of the file. I suppose changing the file does the same trick as well.

Is it possible to set ENV variables for rails development environment in my code?

As an aside to the solutions here, there are cleaner alternatives if you're using certain development servers.

With Heroku's Foreman, you can create per-project environment variables in a .env file:

ADMIN_PASSOWRD="secret"

With Pow, you can use a .powenv file:

export ADMIN_PASSOWRD="secret"

.Net: How do I find the .NET version?

If you open a command prompt and type the following two commands, all framework versions that are installed on the current machine will be listed (each one is stored in a separate directory within this directory).

cd %systemroot%\Microsoft.NET\Framework

dir /A:D

Java String new line

System.out.println("I\nam\na\nboy");

This works It will give one space character also along before enter character

Angular 2: Get Values of Multiple Checked Checkboxes

Here's a solution without map, 'checked' properties and FormControl.

app.component.html:

<div *ngFor="let item of options">
  <input type="checkbox" 
  (change)="onChange($event.target.checked, item)"
  [checked]="checked(item)"
>
  {{item}}
</div>

app.component.ts:

  options = ["1", "2", "3", "4", "5"]
  selected = ["1", "2", "5"]

  // check if the item are selected
  checked(item){
    if(this.selected.indexOf(item) != -1){
      return true;
    }
  }

  // when checkbox change, add/remove the item from the array
  onChange(checked, item){
    if(checked){
    this.selected.push(item);
    } else {
      this.selected.splice(this.selected.indexOf(item), 1)
    }
  }

DEMO

Multiple actions were found that match the request in Web Api

You can add [Route("api/[controller]/[action]")] to your controller class.

[Route("api/[controller]/[action]")]
[ApiController]
public class MySuperController : ControllerBase
{
 ...
}

How to read pickle file?

The following is an example of how you might write and read a pickle file. Note that if you keep appending pickle data to the file, you will need to continue reading from the file until you find what you want or an exception is generated by reaching the end of the file. That is what the last function does.

import os
import pickle


PICKLE_FILE = 'pickle.dat'


def main():
    # append data to the pickle file
    add_to_pickle(PICKLE_FILE, 123)
    add_to_pickle(PICKLE_FILE, 'Hello')
    add_to_pickle(PICKLE_FILE, None)
    add_to_pickle(PICKLE_FILE, b'World')
    add_to_pickle(PICKLE_FILE, 456.789)
    # load & show all stored objects
    for item in read_from_pickle(PICKLE_FILE):
        print(repr(item))
    os.remove(PICKLE_FILE)


def add_to_pickle(path, item):
    with open(path, 'ab') as file:
        pickle.dump(item, file, pickle.HIGHEST_PROTOCOL)


def read_from_pickle(path):
    with open(path, 'rb') as file:
        try:
            while True:
                yield pickle.load(file)
        except EOFError:
            pass


if __name__ == '__main__':
    main()

Sharing a variable between multiple different threads

Both T1 and T2 can refer to a class containing this variable.
You can then make this variable volatile, and this means that
Changes to that variable are immediately visible in both threads.

See this article for more info.

Volatile variables share the visibility features of synchronized but none of the atomicity features. This means that threads will automatically see the most up-to-date value for volatile variables. They can be used to provide thread safety, but only in a very restricted set of cases: those that do not impose constraints between multiple variables or between a variable's current value and its future values.

And note the pros/cons of using volatile vs more complex means of sharing state.

Salt and hash a password in Python

I don' want to resurrect an old thread, but... anyone who wants to use a modern up to date secure solution, use argon2.

https://pypi.python.org/pypi/argon2_cffi

It won the the password hashing competition. ( https://password-hashing.net/ ) It is easier to use than bcrypt, and it is more secure than bcrypt.

How to upload a project to Github

What you need it an SSH connection and GitHub init into your project. I will explain under Linux machine.

Let's start with some easy stuff: navigate into your project in the terminal, and use:

git init
git add .
git commit 

now let's add SSH into your machine: use ssh-keygen -t rsa -C "[email protected]" and copy the public key, then add it to your GitHub repo Deploy keys -> add one back to your machine project now launch: git push origin master if there is an error config your .github/config by nano .github/config and change the URL to ssh one by url = [email protected]:username/repo.... and that's it

How to overlay image with color in CSS?

You can also add an additional class with such settings. Overlay will not overlap content and no additional tag is needed

.overlay {
  position: relative;
  z-index: 0;
}

.overlay::after {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: red;
    opacity: .6;
    /* !!! */
    z-index: -1;
}

https://codepen.io/zeroox003/pen/yLYbpOB

When do I need a fb:app_id or fb:admins?

To use the Like Button and have the Open Graph inspect your website, you need an application.

So you need to associate the Like Button with a fb:app_id

If you want other users to see the administration page for your website on Facebook you add fb:admins. So if you are the developer of the application and the website owner there is no need to add fb:admins

How to use private Github repo as npm dependency

It can be done via https and oauth or ssh.

https and oauth: create an access token that has "repo" scope and then use this syntax:

"package-name": "git+https://<github_token>:[email protected]/<user>/<repo>.git"

or

ssh: setup ssh and then use this syntax:

"package-name": "git+ssh://[email protected]:<user>/<repo>.git"

(note the use of colon instead of slash before user)

Correct way to write line to file?

One can also use the io module as in:

import io
my_string = "hi there"

with io.open("output_file.txt", mode='w', encoding='utf-8') as f:
    f.write(my_string)

getResources().getColor() is deprecated

I found that the useful getResources().getColor(R.color.color_name) is deprecated.

It is not deprecated in API Level 21, according to the documentation.

It is deprecated in the M Developer Preview. However, the replacement method (a two-parameter getColor() that takes the color resource ID and a Resources.Theme object) is only available in the M Developer Preview.

Hence, right now, continue using the single-parameter getColor() method. Later this year, consider using the two-parameter getColor() method on Android M devices, falling back to the deprecated single-parameter getColor() method on older devices.

yii2 redirect in controller action does not work?

Redirects the browser to the specified URL.

This method adds a "Location" header to the current response. Note that it does not send out the header until send() is called. In a controller action you may use this method as follows:

return Yii::$app->getResponse()->redirect($url);

In other places, if you want to send out the "Location" header immediately, you should use the following code:

Yii::$app->getResponse()->redirect($url)->send();
return;

Laravel Eloquent compare date from datetime field

If you're still wondering how to solve it.

I use

$protected $dates = ['created_at','updated_at','aired'];

In my model and in my where i do

where('aired','>=',time())

So just use the unix to compaire in where.

In views on the otherhand you have to use the date object.

Hope it helps someone!

Redis strings vs Redis hashes to represent JSON: efficiency?

It depends on how you access the data:

Go for Option 1:

  • If you use most of the fields on most of your accesses.
  • If there is variance on possible keys

Go for Option 2:

  • If you use just single fields on most of your accesses.
  • If you always know which fields are available

P.S.: As a rule of the thumb, go for the option which requires fewer queries on most of your use cases.

Error:java: javacTask: source release 8 requires target release 1.8

You need to go to Settings and set under the Java compiler the following: enter image description here

also check the Project Settings

Unable to import path from django.urls

For someone having the same problem -

import name 'path' from 'django.urls' 
(C:\Python38\lib\site-packages\django\urls\__init__.py)

You can also try installing django-urls by

pipenv install django-urls

typecast string to integer - Postgres

Wild guess: If your value is an empty string, you can use NULLIF to replace it for a NULL:

SELECT
    NULLIF(your_value, '')::int

Changing all files' extensions in a folder with one command on Windows

Rename multiple file extensions:

You want to change ringtone1.mp3, ringtone2.mp3 to ringtone1.wav, ringtone2.wav

Here is how to do that: I am in d drive on command prompt (CMD) so I use:

d:\>ren *.* *.wav 

This is just an example of file extensions, you can use any type of file extension like WAV, MP3, JPG, GIF, bmp, PDF, DOC, DOCX, TXT this depends on what your operating system.

And, since you have thousands of files, make sure to wait until the cursor starts blinking again indicating that it's done working.

How can I get query string values in JavaScript?

Here is String prototype implementation:

String.prototype.getParam = function( str ){
    str = str.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
    var regex = new RegExp( "[\\?&]*"+str+"=([^&#]*)" );    
    var results = regex.exec( this );
    if( results == null ){
        return "";
    } else {
        return results[1];
    }
}

Example call:

var status = str.getParam("status")

str can be a query string or url

git stash changes apply to new branch?

If you have some changes on your workspace and you want to stash them into a new branch use this command:

git stash branch branchName

It will make:

  1. a new branch
  2. move changes to this branch
  3. and remove latest stash (Like: git stash pop)

Operator overloading in Java

One can try Java Operator Overloading. It has its own limitations, but it worth trying if you really want to use operator overloading.

Serialize Property as Xml Attribute in Element

You will need wrapper classes:

public class SomeIntInfo
{
    [XmlAttribute]
    public int Value { get; set; }
}

public class SomeStringInfo
{
    [XmlAttribute]
    public string Value { get; set; }
}

public class SomeModel
{
    [XmlElement("SomeStringElementName")]
    public SomeStringInfo SomeString { get; set; }

    [XmlElement("SomeInfoElementName")]
    public SomeIntInfo SomeInfo { get; set; }
}

or a more generic approach if you prefer:

public class SomeInfo<T>
{
    [XmlAttribute]
    public T Value { get; set; }
}

public class SomeModel
{
    [XmlElement("SomeStringElementName")]
    public SomeInfo<string> SomeString { get; set; }

    [XmlElement("SomeInfoElementName")]
    public SomeInfo<int> SomeInfo { get; set; }
}

And then:

class Program
{
    static void Main()
    {
        var model = new SomeModel
        {
            SomeString = new SomeInfo<string> { Value = "testData" },
            SomeInfo = new SomeInfo<int> { Value = 5 }
        };
        var serializer = new XmlSerializer(model.GetType());
        serializer.Serialize(Console.Out, model);
    }
}

will produce:

<?xml version="1.0" encoding="ibm850"?>
<SomeModel xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <SomeStringElementName Value="testData" />
  <SomeInfoElementName Value="5" />
</SomeModel>

How to find out the MySQL root password

you can view mysql root password , well i have tried it on mysql 5.5 so do not know about other new version well work or not

nano ~/.my.cnf

How to see local history changes in Visual Studio Code?

I built an extension called Checkpoints, an alternative to Local History. Checkpoints has support for viewing history for all files (that has checkpoints) in the tree view, not just the currently active file. There are some other minor differences aswell, but overall they are pretty similar.

How do I fix PyDev "Undefined variable from import" errors?

Right click in the project explorer on whichever module is giving errors. Go to PyDev->Remove Error Markers.

How to create a JSON object

Although the other answers posted here work, I find the following approach more natural:

$obj = (object) [
    'aString' => 'some string',
    'anArray' => [ 1, 2, 3 ]
];

echo json_encode($obj);

Send JSON data via POST (ajax) and receive json response from Controller (MVC)

Use JSON.stringify(<data>).

Change your code: data: sendInfo to data: JSON.stringify(sendInfo). Hope this can help you.

How can I make text appear on next line instead of overflowing?

Just add

white-space: initial;

to the text, a line text will come automatically in the next line.

Disable keyboard on EditText

This worked for me. First add this android:windowSoftInputMode="stateHidden" in your android manifest file, under your activity. like below:

<activity ... android:windowSoftInputMode="stateHidden">

Then on onCreate method of youractivity, add the foloowing code:

EditText editText = (EditText)findViewById(R.id.edit_text);
edit_text.setOnTouchListener(new OnTouchListener() {

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        v.onTouchEvent(event);
        InputMethodManager inputMethod = (InputMethodManager)v.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        if (inputMethod!= null) {
            inputMethod.hideSoftInputFromWindow(v.getWindowToken(), 0);
        }                
        return true;
    }
});

Then if you want the pointer to be visible add this on your xml android:textIsSelectable="true".

This will make the pointer visible. In this way the keyboard will not popup when your activity starts and also will be hidden when you click on the edittext.

How can I get the request URL from a Java Filter?

Building on another answer on this page,

public static String getCurrentUrlFromRequest(ServletRequest request)
{
   if (! (request instanceof HttpServletRequest))
       return null;

   return getCurrentUrlFromRequest((HttpServletRequest)request);
}

public static String getCurrentUrlFromRequest(HttpServletRequest request)
{
    StringBuffer requestURL = request.getRequestURL();
    String queryString = request.getQueryString();

    if (queryString == null)
        return requestURL.toString();

    return requestURL.append('?').append(queryString).toString();
}

How to start http-server locally

To start server locally paste the below code in package.json and run npm start in command line.

"scripts": { "start": "http-server -c-1 -p 8081" },

How to use OpenFileDialog to select a folder?

Here is a pure C# version that should work with all versions of .NET (including .NET Core, .NET 5, WPF, Winforms, etc.) and uses Windows Vista (and higher) IFileDialog interface with the FOS_PICKFOLDERS options so it has the nice folder picker Windows standard UI. I have also added WPF's Window type support but this is optional.

usage:

var dlg = new FolderPicker();
dlg.InputPath = @"c:\windows\system32";
if (dlg.ShowDialog() == true)
{
    MessageBox.Show(dlg.ResultPath);
}

code:

    using System;
    using System.Diagnostics;
    using System.Runtime.InteropServices;
    using System.Runtime.InteropServices.ComTypes;
    using System.Windows; // for WPF support
    using System.Windows.Interop;  // for WPF support

    public class FolderPicker
    {
        public virtual string ResultPath { get; protected set; }
        public virtual string ResultName { get; protected set; }
        public virtual string InputPath { get; set; }
        public virtual bool ForceFileSystem { get; set; }
        public virtual string Title { get; set; }
        public virtual string OkButtonLabel { get; set; }
        public virtual string FileNameLabel { get; set; }

        protected virtual int SetOptions(int options)
        {
            if (ForceFileSystem)
            {
                options |= (int)FOS.FOS_FORCEFILESYSTEM;
            }
            return options;
        }

        // for WPF support
        public bool? ShowDialog(Window owner = null, bool throwOnError = false)
        {
            owner ??= Application.Current.MainWindow;
            return ShowDialog(owner != null ? new WindowInteropHelper(owner).Handle : IntPtr.Zero, throwOnError);
        }

        // for all .NET
        public virtual bool? ShowDialog(IntPtr owner, bool throwOnError = false)
        {
            var dialog = (IFileOpenDialog)new FileOpenDialog();
            if (!string.IsNullOrEmpty(InputPath))
            {
                if (CheckHr(SHCreateItemFromParsingName(InputPath, null, typeof(IShellItem).GUID, out var item), throwOnError) != 0)
                    return null;

                dialog.SetFolder(item);
            }

            var options = FOS.FOS_PICKFOLDERS;
            options = (FOS)SetOptions((int)options);
            dialog.SetOptions(options);

            if (Title != null)
            {
                dialog.SetTitle(Title);
            }

            if (OkButtonLabel != null)
            {
                dialog.SetOkButtonLabel(OkButtonLabel);
            }

            if (FileNameLabel != null)
            {
                dialog.SetFileName(FileNameLabel);
            }

            if (owner == IntPtr.Zero)
            {
                owner = Process.GetCurrentProcess().MainWindowHandle;
                if (owner == IntPtr.Zero)
                {
                    owner = GetDesktopWindow();
                }
            }

            var hr = dialog.Show(owner);
            if (hr == ERROR_CANCELLED)
                return null;

            if (CheckHr(hr, throwOnError) != 0)
                return null;

            if (CheckHr(dialog.GetResult(out var result), throwOnError) != 0)
                return null;

            if (CheckHr(result.GetDisplayName(SIGDN.SIGDN_DESKTOPABSOLUTEPARSING, out var path), throwOnError) != 0)
                return null;

            ResultPath = path;

            if (CheckHr(result.GetDisplayName(SIGDN.SIGDN_DESKTOPABSOLUTEEDITING, out path), false) == 0)
            {
                ResultName = path;
            }
            return true;
        }

        private static int CheckHr(int hr, bool throwOnError)
        {
            if (hr != 0)
            {
                if (throwOnError)
                    Marshal.ThrowExceptionForHR(hr);
            }
            return hr;
        }

        [DllImport("shell32")]
        private static extern int SHCreateItemFromParsingName([MarshalAs(UnmanagedType.LPWStr)] string pszPath, IBindCtx pbc, [MarshalAs(UnmanagedType.LPStruct)] Guid riid, out IShellItem ppv);

        [DllImport("user32")]
        private static extern IntPtr GetDesktopWindow();

#pragma warning disable IDE1006 // Naming Styles
        private const int ERROR_CANCELLED = unchecked((int)0x800704C7);
#pragma warning restore IDE1006 // Naming Styles

        [ComImport, Guid("DC1C5A9C-E88A-4dde-A5A1-60F82A20AEF7")] // CLSID_FileOpenDialog
        private class FileOpenDialog
        {
        }

        [ComImport, Guid("42f85136-db7e-439c-85f1-e4075d135fc8"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
        private interface IFileOpenDialog
        {
            [PreserveSig] int Show(IntPtr parent); // IModalWindow
            [PreserveSig] int SetFileTypes();  // not fully defined
            [PreserveSig] int SetFileTypeIndex(int iFileType);
            [PreserveSig] int GetFileTypeIndex(out int piFileType);
            [PreserveSig] int Advise(); // not fully defined
            [PreserveSig] int Unadvise();
            [PreserveSig] int SetOptions(FOS fos);
            [PreserveSig] int GetOptions(out FOS pfos);
            [PreserveSig] int SetDefaultFolder(IShellItem psi);
            [PreserveSig] int SetFolder(IShellItem psi);
            [PreserveSig] int GetFolder(out IShellItem ppsi);
            [PreserveSig] int GetCurrentSelection(out IShellItem ppsi);
            [PreserveSig] int SetFileName([MarshalAs(UnmanagedType.LPWStr)] string pszName);
            [PreserveSig] int GetFileName([MarshalAs(UnmanagedType.LPWStr)] out string pszName);
            [PreserveSig] int SetTitle([MarshalAs(UnmanagedType.LPWStr)] string pszTitle);
            [PreserveSig] int SetOkButtonLabel([MarshalAs(UnmanagedType.LPWStr)] string pszText);
            [PreserveSig] int SetFileNameLabel([MarshalAs(UnmanagedType.LPWStr)] string pszLabel);
            [PreserveSig] int GetResult(out IShellItem ppsi);
            [PreserveSig] int AddPlace(IShellItem psi, int alignment);
            [PreserveSig] int SetDefaultExtension([MarshalAs(UnmanagedType.LPWStr)] string pszDefaultExtension);
            [PreserveSig] int Close(int hr);
            [PreserveSig] int SetClientGuid();  // not fully defined
            [PreserveSig] int ClearClientData();
            [PreserveSig] int SetFilter([MarshalAs(UnmanagedType.IUnknown)] object pFilter);
            [PreserveSig] int GetResults([MarshalAs(UnmanagedType.IUnknown)] out object ppenum);
            [PreserveSig] int GetSelectedItems([MarshalAs(UnmanagedType.IUnknown)] out object ppsai);
        }

        [ComImport, Guid("43826D1E-E718-42EE-BC55-A1E261C37BFE"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
        private interface IShellItem
        {
            [PreserveSig] int BindToHandler(); // not fully defined
            [PreserveSig] int GetParent(); // not fully defined
            [PreserveSig] int GetDisplayName(SIGDN sigdnName, [MarshalAs(UnmanagedType.LPWStr)] out string ppszName);
            [PreserveSig] int GetAttributes();  // not fully defined
            [PreserveSig] int Compare();  // not fully defined
        }

        #pragma warning disable CA1712 // Do not prefix enum values with type name
        private enum SIGDN : uint
        {
            SIGDN_DESKTOPABSOLUTEEDITING = 0x8004c000,
            SIGDN_DESKTOPABSOLUTEPARSING = 0x80028000,
            SIGDN_FILESYSPATH = 0x80058000,
            SIGDN_NORMALDISPLAY = 0,
            SIGDN_PARENTRELATIVE = 0x80080001,
            SIGDN_PARENTRELATIVEEDITING = 0x80031001,
            SIGDN_PARENTRELATIVEFORADDRESSBAR = 0x8007c001,
            SIGDN_PARENTRELATIVEPARSING = 0x80018001,
            SIGDN_URL = 0x80068000
        }

        [Flags]
        private enum FOS
        {
            FOS_OVERWRITEPROMPT = 0x2,
            FOS_STRICTFILETYPES = 0x4,
            FOS_NOCHANGEDIR = 0x8,
            FOS_PICKFOLDERS = 0x20,
            FOS_FORCEFILESYSTEM = 0x40,
            FOS_ALLNONSTORAGEITEMS = 0x80,
            FOS_NOVALIDATE = 0x100,
            FOS_ALLOWMULTISELECT = 0x200,
            FOS_PATHMUSTEXIST = 0x800,
            FOS_FILEMUSTEXIST = 0x1000,
            FOS_CREATEPROMPT = 0x2000,
            FOS_SHAREAWARE = 0x4000,
            FOS_NOREADONLYRETURN = 0x8000,
            FOS_NOTESTFILECREATE = 0x10000,
            FOS_HIDEMRUPLACES = 0x20000,
            FOS_HIDEPINNEDPLACES = 0x40000,
            FOS_NODEREFERENCELINKS = 0x100000,
            FOS_OKBUTTONNEEDSINTERACTION = 0x200000,
            FOS_DONTADDTORECENT = 0x2000000,
            FOS_FORCESHOWHIDDEN = 0x10000000,
            FOS_DEFAULTNOMINIMODE = 0x20000000,
            FOS_FORCEPREVIEWPANEON = 0x40000000,
            FOS_SUPPORTSTREAMABLEITEMS = unchecked((int)0x80000000)
        }
        #pragma warning restore CA1712 // Do not prefix enum values with type name
    }

result:

enter image description here

Twig for loop for arrays with keys

I guess you want to do the "Iterating over Keys and Values"

As the doc here says, just add "|keys" in the variable you want and it will magically happen.

{% for key, user in users %}
    <li>{{ key }}: {{ user.username|e }}</li>
{% endfor %}

It never hurts to search before asking :)

How to create PDF files in Python

You can try this(Python-for-PDF-Generation) or you can try PyQt, which has support for printing to pdf.

Python for PDF Generation

The Portable Document Format (PDF) lets you create documents that look exactly the same on every platform. Sometimes a PDF document needs to be generated dynamically, however, and that can be quite a challenge. Fortunately, there are libraries that can help. This article examines one of those for Python.

Read more at http://www.devshed.com/c/a/Python/Python-for-PDF-Generation/#whoCFCPh3TAks368.99

How to cache data in a MVC application

I will say implementing Singleton on this persisting data issue can be a solution for this matter in case you find previous solutions much complicated

 public class GPDataDictionary
{
    private Dictionary<string, object> configDictionary = new Dictionary<string, object>();

    /// <summary>
    /// Configuration values dictionary
    /// </summary>
    public Dictionary<string, object> ConfigDictionary
    {
        get { return configDictionary; }
    }

    private static GPDataDictionary instance;
    public static GPDataDictionary Instance
    {
        get
        {
            if (instance == null)
            {
                instance = new GPDataDictionary();
            }
            return instance;
        }
    }

    // private constructor
    private GPDataDictionary() { }

}  // singleton

How to stop an app on Heroku?

To add to the answers above: if you want to stop Dyno using admin panel, the current solution on free tier:

  1. Open App
  2. In Overview tab, in "Dyno formation" section click on "Configure Dynos"
  3. In the needed row of "Free Dynos" section, click on the pencil icon on the right
  4. Click on the blue on/off control, and then click on "Confirm"

Hope this helps.

Adding a SVN repository in Eclipse

I doubt that Subclipse and then SVN can use your Eclipse proxy settings. You'll probably need to set the proxy for your SVN program itself. Trying to check out the files using SVN from the command line should tell you if that works.

If SVN can't connect either then put the proxy settings in your servers file in your Subversion settings folder (in your home folder).

If it can't do it even with the proxy settings set, then your firewall is probably blocking the methods and protocols that Subversion needs to use to download the files.

Add default value of datetime field in SQL Server to a timestamp

In SQLPlus while creating a table it is be like as

SQL> create table Test

 ( Test_ID number not null,
   Test_Date date default sysdate not null );

SQL> insert into Test(id) values (1);

 Test_ID Test_Date
       1 08-MAR-19

Clear input fields on form submit

Still using empty strings you can use:

document.getElementById("name").value = '';
document.getElementById("review").value = '';

How to pass boolean parameter value in pipeline to downstream jobs?

like Jesse Jesse Glick and abguy said you can enumerate string into Boolean type:

Boolean.valueOf(string_variable)

or the opposite Boolean into string:

String.valueOf(boolean_variable)

in my case I had to to downstream Boolean parameter to another job. So for this you will need the use the class BooleanParameterValue :

build job: 'downstream_job_name', parameters:
[
[$class: 'BooleanParameterValue', name: 'parameter_name', value: false],
], wait: true

How to compare two colors for similarity/difference

For quick and dirty, you can do

import java.awt.Color;
private Color dropPrecision(Color c,int threshold){
    return new Color((c.getRed()/threshold),
                     (c.getGreen()/threshold),
                     (c.getBlue()/threshold));
}
public boolean inThreshold(Color _1,Color _2,int threshold){
    return dropPrecision(_1,threshold)==dropPrecision(_2,threshold);
}

making use of integer division to quantize the colors.

Create HTML table using Javascript

This beautiful code here creates a table with each td having array values. Not my code, but it helped me!

var rows = 6, cols = 7;

for(var i = 0; i < rows; i++) {
  $('table').append('<tr></tr>');
  for(var j = 0; j < cols; j++) {
    $('table').find('tr').eq(i).append('<td></td>');
    $('table').find('tr').eq(i).find('td').eq(j).attr('data-row', i).attr('data-col', j);
  }
}

How to write text in ipython notebook?

Adding to Matt's answer above (as I don't have comment privileges yet), one mouse-free workflow would be:

Esc then m then Enter so that you gain focus again and can start typing.

Without the last Enter you would still be in Escape mode and would otherwise have to use your mouse to activate text input in the cell.

Another way would be to add a new cell, type out your markdown in "Code" mode and then change to markdown once you're done typing everything you need, thus obviating the need to refocus.

You can then move on to your next cells. :)

Visual Studio 2013 License Product Key

I solved this, without having to completely reinstall Visual Studio 2013.

For those who may come across this in the future, the following steps worked for me:

  1. Run the ISO (or vs_professional.exe).
  2. If you get the error below, you need to update the Windows Registry to trick the installer into thinking you still have the base version. If you don't get this error, skip to step 3 "The product version that you are trying to set up is earlier than the version already installed on this computer."

    • Click the link for 'examine the log file' and look near the bottom of the log, for this line: Detected related bundle ... operation: Downgrade

    • open regedit.exe and do an Edit > Find... for that GUID. In my case it was {6dff50d0-3bc3-4a92-b724-bf6d6a99de4f}. This was found in:

      HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall{6dff50d0-3bc3-4a92-b724-bf6d6a99de4f}

    • Edit the BundleVersion value and change it to a lower version. I changed mine from 12.0.21005.13 to 12.0.21000.13: BundleVersion for Visual Studio lower the version for BundleVersion

    • Exit the registry

  3. Run the ISO (or vs_professional.exe) again. If it has a repair button like the image below, you can skip to step 4.

    Visual Studio Repair button

    • Otherwise you have to let the installer fix the registry. I did this by "installing" at least one feature, even though I think I already had all features (they were not detected). This took about 20 minutes.
  4. Run the ISO (or vs_professional.exe) again. This time repair should be visible.

  5. Click Repair and let it update your installation and apply its embedded license key. This took about 20 minutes.


Now when you run Visual Studio 2013, it should indicate that a license key was applied, under Help > Register Product:

License: Product key applied

Hope this helps somebody in the future!

Reference blog 'story'

Remove Top Line of Text File with PowerShell

skip` didn't work, so my workaround is

$LinesCount = $(get-content $file).Count
get-content $file |
    select -Last $($LinesCount-1) | 
    set-content "$file-temp"
move "$file-temp" $file -Force

How do I change the data type for a column in MySQL?

If you want to change all columns of a certain type to another type, you can generate queries using a query like this:

select distinct concat('alter table ',
                       table_name,
                       ' modify ',
                       column_name,
                       ' <new datatype> ',
                       if(is_nullable = 'NO', ' NOT ', ''),
                       ' NULL;')
  from information_schema.columns
  where table_schema = '<your database>' 
    and column_type = '<old datatype>';

For instance, if you want to change columns from tinyint(4) to bit(1), run it like this:

select distinct concat('alter table ',
                       table_name,
                       ' modify ',
                       column_name,
                       ' bit(1) ',
                       if(is_nullable = 'NO', ' NOT ', ''),
                       ' NULL;')
  from information_schema.columns
  where table_schema = 'MyDatabase' 
    and column_type = 'tinyint(4)';

and get an output like this:

alter table table1 modify finished bit(1)  NOT  NULL;
alter table table2 modify canItBeTrue bit(1)  NOT  NULL;
alter table table3 modify canBeNull bit(1)  NULL;

!! Does not keep unique constraints, but should be easily fixed with another if-parameter to concat. I'll leave it up to the reader to implement that if needed..

ls command: how can I get a recursive full-path listing, one line per file?

Here is a partial answer that shows the directory names.

ls -mR * | sed -n 's/://p'

Explanation:

ls -mR * lists the full directory names ending in a ':', then lists the files in that directory separately

sed -n 's/://p' finds lines that end in a colon, strip off the colon and print the line

By iterating over the list of directories, we should be able to find the directories as well. Still workin on it. It is a challenge to get the wildcards through xargs.

Removing object from array in Swift 3

Try this in Swift 3

array.remove(at: Index)

Instead of

array.removeAtIndex(index)

Update

"Declaration is only valid at file scope".

Make sure the object is in scope. You can give scope "internal", which is default.

index(of:<Object>) to work, class should conform to Equatable

What's the shebang/hashbang (#!) in Facebook and new Twitter URLs for?

This technique is now deprecated.

This used to tell Google how to index the page.

https://developers.google.com/webmasters/ajax-crawling/

This technique has mostly been supplanted by the ability to use the JavaScript History API that was introduced alongside HTML5. For a URL like www.example.com/ajax.html#!key=value, Google will check the URL www.example.com/ajax.html?_escaped_fragment_=key=value to fetch a non-AJAX version of the contents.

Convenient way to parse incoming multipart/form-data parameters in a Servlet

Not always there's a servlet before of an upload (I could use a filter for example). Or could be that the same controller ( again a filter or also a servelt ) can serve many actions, so I think that rely on that servlet configuration to use the getPart method (only for Servlet API >= 3.0), I don't know, I don't like.

In general, I prefer independent solutions, able to live alone, and in this case http://commons.apache.org/proper/commons-fileupload/ is one of that.

List<FileItem> multiparts = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
    for (FileItem item : multiparts) {
        if (!item.isFormField()) {
            //your operations on file
        } else {
            String name = item.getFieldName();
            String value = item.getString();
            //you operations on paramters
        }
}

How can I check if a string is null or empty in PowerShell?

An extension of the answer from Keith Hill (to account for whitespace):

$str = "     "
if ($str -and $version.Trim()) { Write-Host "Not Empty" } else { Write-Host "Empty" }

This returns "Empty" for nulls, empty strings, and strings with whitespace, and "Not Empty" for everything else.

How to underline a UILabel in swift?

I have algorithm that used in my app. In this algorithm you can underline substring even that have space between words

extension NSMutableAttributedString{

    static func  findSubStringAndUnderlineIt(subStringToBeFound : String,totalString : String)->  NSMutableAttributedString?{
        
        let attributedString = NSMutableAttributedString(string: totalString)

        var spaceCount = 0
        
        if subStringToBeFound.contains(" "){
            spaceCount = subStringToBeFound.components(separatedBy:" ").count-1
        }

        
        if  let range = attributedString.string.range(of: subStringToBeFound, options: .caseInsensitive){
        
            attributedString.addAttribute(NSAttributedString.Key.underlineStyle, value: NSUnderlineStyle.single.rawValue, range: NSMakeRange((range.lowerBound.utf16Offset(in: subStringToBeFound)) ,(range.upperBound.utf16Offset(in: subStringToBeFound)) +
            spaceCount))
                return attributedString
        }
        return attributedString
        
    }
    
}

in used section

 lblWarning.attributedText = NSMutableAttributedString.findSubStringAndUnderlineIt(subStringToBeFound:"Not: Sadece uygulamanin reklamlari kaldirilacaktir.", totalString: lblWarning.text!)

Convert absolute path into relative path given a current directory using Bash

This script gives correct results only for inputs that are absolute paths or relative paths without . or ..:

#!/bin/bash

# usage: relpath from to

if [[ "$1" == "$2" ]]
then
    echo "."
    exit
fi

IFS="/"

current=($1)
absolute=($2)

abssize=${#absolute[@]}
cursize=${#current[@]}

while [[ ${absolute[level]} == ${current[level]} ]]
do
    (( level++ ))
    if (( level > abssize || level > cursize ))
    then
        break
    fi
done

for ((i = level; i < cursize; i++))
do
    if ((i > level))
    then
        newpath=$newpath"/"
    fi
    newpath=$newpath".."
done

for ((i = level; i < abssize; i++))
do
    if [[ -n $newpath ]]
    then
        newpath=$newpath"/"
    fi
    newpath=$newpath${absolute[i]}
done

echo "$newpath"

Jquery Date picker Default Date

interesting, datepicker default date is current date as I found,

but you can set date by

$("#yourinput").datepicker( "setDate" , "7/11/2011" );

don't forget to check you system date :)

How to find length of a string array?

I think you are looking for this

String[] car = new String[10];
int size = car.length;

SSRS expression to format two decimal places does not show zeros

Please try the following code snippet,

IIF(Round(Avg(Fields!Vision_Score.Value)) = Avg(Fields!Vision_Score.Value), 
Format(Avg(Fields!Vision_Score.Value)), 
FORMAT(Avg(Fields!Vision_Score.Value),"##.##"))

hope it will help, Thank-you.

From io.Reader to string in Go

var b bytes.Buffer
b.ReadFrom(r)

// b.String()