Programs & Examples On #Fire and forget

Where does error CS0433 "Type 'X' already exists in both A.dll and B.dll " come from?

I ended up changing how the MasterType is referenced in the page mark up.

I changed: <%@ MasterType VirtualPath="~/x/y/MyMaster.Master" %> to <%@ MasterType TypeName="FullyQualifiedNamespace.MyMaster" %>

See here for details.

Hope this helps someone out.

href image link download on click

If you are Using HTML5 you can add the attribute 'download' to your links.

<a href="/test.pdf" download>

http://www.w3schools.com/tags/att_a_download.asp

The Completest Cocos2d-x Tutorial & Guide List

Here you got complementaries discussions about the topic, it can be interesting.

discussion1

discussion2

Changing the size of a column referenced by a schema-bound view in SQL Server

Check the column collation. This script might change the collation to the table default. Add the current collation to the script.

How to find server name of SQL Server Management Studio

Typing sp_helpserver will give you a list. As others have noted, there are multiple ways, some with alias' and such. This stored proc may return multiple lines but could get you closer to your answer.

Environment variables in Eclipse

You can set the Hadoop home directory by sending a -Dhadoop.home.dir to the VM. To send this parameters to all your application that you execute inside eclipse, you can set them in Window->Preferences->Java->Installed JREs-> (select your JRE installation) -> Edit.. -> (set the value in the "Default VM arguments:" textbox). You can replace ${HADOOP_HOME} with the path to your Hadoop installation.

Select the JRE you use for running programs in Eclipse

Sending the value for hadoop.home.dir property as a VM argument

Using UPDATE in stored procedure with optional parameters

UPDATE tbl_ClientNotes 
SET ordering=@ordering, title=@title, content=@content 
WHERE id=@id 
AND @ordering IS NOT NULL
AND @title IS NOT NULL
AND @content IS NOT NULL

Or if you meant you only want to update individual columns you would use the post above mine. I read it as do not update if any values are null

How to compare types

You can compare for exactly the same type using:

class A {
}
var a = new A();
var typeOfa = a.GetType();
if (typeOfa == typeof(A)) {
}

typeof returns the Type object from a given class.

But if you have a type B, that inherits from A, then this comparison is false. And you are looking for IsAssignableFrom.

class B : A {
}
var b = new B();
var typeOfb = b.GetType();

if (typeOfb == typeof(A)) { // false
}

if (typeof(A).IsAssignableFrom(typeOfb)) { // true
}

Trim a string in C

Not the best way but it works

char* Trim(char* str)
{
    int len = strlen(str);
    char* buff = new char[len];
    int i = 0;
    memset(buff,0,len*sizeof(char));
    do{
        if(isspace(*str)) continue;
        buff[i] = *str; ++i;
    } while(*(++str) != '\0');
    return buff;
}

Golang read request body

Inspecting and mocking request body

When you first read the body, you have to store it so once you're done with it, you can set a new io.ReadCloser as the request body constructed from the original data. So when you advance in the chain, the next handler can read the same body.

One option is to read the whole body using ioutil.ReadAll(), which gives you the body as a byte slice.

You may use bytes.NewBuffer() to obtain an io.Reader from a byte slice.

The last missing piece is to make the io.Reader an io.ReadCloser, because bytes.Buffer does not have a Close() method. For this you may use ioutil.NopCloser() which wraps an io.Reader, and returns an io.ReadCloser, whose added Close() method will be a no-op (does nothing).

Note that you may even modify the contents of the byte slice you use to create the "new" body. You have full control over it.

Care must be taken though, as there might be other HTTP fields like content-length and checksums which may become invalid if you modify only the data. If subsequent handlers check those, you would also need to modify those too!

Inspecting / modifying response body

If you also want to read the response body, then you have to wrap the http.ResponseWriter you get, and pass the wrapper on the chain. This wrapper may cache the data sent out, which you can inspect either after, on on-the-fly (as the subsequent handlers write to it).

Here's a simple ResponseWriter wrapper, which just caches the data, so it'll be available after the subsequent handler returns:

type MyResponseWriter struct {
    http.ResponseWriter
    buf *bytes.Buffer
}

func (mrw *MyResponseWriter) Write(p []byte) (int, error) {
    return mrw.buf.Write(p)
}

Note that MyResponseWriter.Write() just writes the data to a buffer. You may also choose to inspect it on-the-fly (in the Write() method) and write the data immediately to the wrapped / embedded ResponseWriter. You may even modify the data. You have full control.

Care must be taken again though, as the subsequent handlers may also send HTTP response headers related to the response data –such as length or checksums– which may also become invalid if you alter the response data.

Full example

Putting the pieces together, here's a full working example:

func loginmw(handler http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        body, err := ioutil.ReadAll(r.Body)
        if err != nil {
            log.Printf("Error reading body: %v", err)
            http.Error(w, "can't read body", http.StatusBadRequest)
            return
        }

        // Work / inspect body. You may even modify it!

        // And now set a new body, which will simulate the same data we read:
        r.Body = ioutil.NopCloser(bytes.NewBuffer(body))

        // Create a response wrapper:
        mrw := &MyResponseWriter{
            ResponseWriter: w,
            buf:            &bytes.Buffer{},
        }

        // Call next handler, passing the response wrapper:
        handler.ServeHTTP(mrw, r)

        // Now inspect response, and finally send it out:
        // (You can also modify it before sending it out!)
        if _, err := io.Copy(w, mrw.buf); err != nil {
            log.Printf("Failed to send out response: %v", err)
        }
    })
}

What are alternatives to ExtJS?

Nothing compares to in terms of community size and presence on StackOverflow. Despite previous controversy, Ext JS now has a GPLv3 open source license. Its learning curve is long, but it can be quite rewarding once learned. Ext JS lacks a Material Design theme, and the team has repeatedly refused to release the source code on GitHub. For mobile, one must use the separate Sencha Touch library.

Have in mind also that,

large JavaScript libraries, such as YUI, have been receiving less attention from the community. Many developers today look at large JavaScript libraries as walled gardens they don’t want to be locked into.

-- Announcement of YUI development being ceased

That said, below are a number of Ext JS alternatives currently available.

Leading client widget libraries

  1. Blueprint is a React-based UI toolkit developed by big data analytics company Palantir in TypeScript, and "optimized for building complex data-dense interfaces for desktop applications". Actively developed on GitHub as of May 2019, with comprehensive documentation. Components range from simple (chips, toast, icons) to complex (tree, data table, tag input with autocomplete, date range picker. No accordion or resizer.

    Blueprint targets modern browsers (Chrome, Firefox, Safari, IE 11, and Microsoft Edge) and is licensed under a modified Apache license.

    Sandbox / demoGitHubDocs

  2. Webix - an advanced, easy to learn, mobile-friendly, responsive and rich free&open source JavaScript UI components library. Webix spun off from DHTMLX Touch (a project with 8 years of development behind it - see below) and went on to become a standalone UI components framework. The GPL3 edition allows commercial use and lets non-GPL applications using Webix keep their license, e.g. MIT, via a license exemption for FLOSS. Webix has 55 UI widgets, including trees, grids, treegrids and charts. Funding comes from a commercial edition with some advanced widgets (Pivot, Scheduler, Kanban, org chart etc.). Webix has an extensive list of free and commercial widgets, and integrates with most popular frameworks (React, Vue, Meteor, etc) and UI components.

    Webix

    Skins look modern, and include a Material Design theme. The Touch theme also looks quite Material Design-ish. See also the Skin Builder.

    Minimal GitHub presence, but includes the library code, and the documentation (which still needs major improvements). Webix suffers from a having a small team and a lack of marketing. However, they have been responsive to user feedback, both on GitHub and on their forum.

    The library was lean (128Kb gzip+minified for all 55 widgets as of ~2015), faster than ExtJS, dojo and others, and the design is pleasant-looking. The current version of Webix (v6, as of Nov 2018) got heavier (400 - 676kB minified but NOT gzipped).

    The demos on Webix.com look and function great. The developer, XB Software, uses Webix in solutions they build for paying customers, so there's likely a good, funded future ahead of it.

    Webix aims for backwards compatibility down to IE8, and as a result carries some technical debt.

    WikipediaGitHubPlayground/sandboxAdmin dashboard demoDemosWidget samples

  3. react-md - MIT-licensed Material Design UI components library for React. Responsive, accessible. Implements components from simple (buttons, cards) to complex (sortable tables, autocomplete, tags input, calendars). One lead author, ~1900 GitHub stars.

  4. - jQuery-based UI toolkit with 40+ basic open-source widgets, plus commercial professional widgets (grids, trees, charts etc.). Responsive&mobile support. Works with Bootstrap and AngularJS. Modern, with Material Design themes. The documentation is available on GitHub, which has enabled numerous contributions from users (4500+ commits, 500+ PRs as of Jan 2015).

    enter image description here

    Well-supported commercially, claiming millions of developers, and part of a large family of developer tools. Telerik has received many accolades, is a multi-national company (Bulgaria, US), was acquired by Progress Software, and is a thought leader.

    A Kendo UI Professional developer license costs $700 and posting access to most forums is conditioned upon having a license or being in the trial period.

    [Wikipedia] • GitHub/TelerikDemosPlaygroundTools

  5. OpenUI5 - jQuery-based UI framework with 180 widgets, Apache 2.0-licensed and fully-open sourced and funded by German software giant SAP SE.

    OpenUI5

    The community is much larger than that of Webix, SAP is hiring developers to grow OpenUI5, and they presented OpenUI5 at OSCON 2014.

    The desktop themes are rather lackluster, but the Fiori design for web and mobile looks clean and neat.

    WikipediaGitHubMobile-first controls demosDesktop controls demosSO

  6. DHTMLX - JavaScript library for building rich Web and Mobile apps. Looks most like ExtJS - check the demos. Has been developed since 2005 but still looks modern. All components except TreeGrid are available under GPLv2 but advanced features for many components are only available in the commercial PRO edition - see for example the tree. Claims to be used by many Fortune 500 companies.

    DHTMLX

    Minimal presence on GitHub (the main library code is missing) and StackOverflow but active forum. The documentation is not available on GitHub, which makes it difficult to improve by the community.

  7. Polymer, a Web Components polyfill, plus Polymer Paper, Google's implementation of the Material design. Aimed at web and mobile apps. Doesn't have advanced widgets like trees or even grids but the controls it provides are mobile-first and responsive. Used by many big players, e.g. IBM or USA Today.

    Polymer Paper Elements

  8. Ant Design claims it is "a design language for background applications", influenced by "nature" and helping designers "create low-entropy atmosphere for developer team". That's probably a poor translation from Chinese for "UI components for enterprise web applications". It's a React UI library written in TypeScript, with many components, from simple (buttons, cards) to advanced (autocomplete, calendar, tag input, table).

    The project was born in China, is popular with Chinese companies, and parts of the documentation are available only in Chinese. Quite popular on GitHub, yet it makes the mistake of splitting the community into Chinese and English chat rooms. The design looks Material-ish, but fonts are small and the information looks lost in a see of whitespace.

  9. PrimeUI - collection of 45+ rich widgets based on jQuery UI. Apache 2.0 license. Small GitHub community. 35 premium themes available.

  10. qooxdoo - "a universal JavaScript framework with a coherent set of individual components", developed and funded by German hosting provider 1&1 (see the contributors, one of the world's largest hosting companies. GPL/EPL (a business-friendly license).

    Mobile themes look modern but desktop themes look old (gradients).

    Qooxdoo

    WikipediaGitHubWeb/Mobile/Desktop demosWidgets Demo browserWidget browserSOPlaygroundCommunity

  11. jQuery UI - easy to pick up; looks a bit dated; lacks advanced widgets. Of course, you can combine it with independent widgets for particular needs, e.g. trees or other UI components, but the same can be said for any other framework.

  12. + Angular UI. While Angular is backed by Google, it's being radically revamped in the upcoming 2.0 version, and "users will need to get to grips with a new kind of architecture. It's also been confirmed that there will be no migration path from Angular 1.X to 2.0". Moreover, the consensus seems to be that Angular 2 won't really be ready for use until a year or two from now. Angular UI has relatively few widgets (no trees, for example).

  13. DojoToolkit and their powerful Dijit set of widgets. Completely open-sourced and actively developed on GitHub, but development is now (Nov 2018) focused on the new dojo.io framework, which has very few basic widgets. BSD/AFL license. Development started in 2004 and the Dojo Foundation is being sponsored by IBM, Google, and others - see Wikipedia. 7500 questions here on SO.

    Dojo Dijit

    Themes look desktop-oriented and dated - see the theme tester in dijit. The official theme previewer is broken and only shows "Claro". A Bootstrap theme exists, which looks a lot like Bootstrap, but doesn't use Bootstrap classes. In Jan 2015, I started a thread on building a Material Design theme for Dojo, which got quite popular within the first hours. However, there are questions regarding building that theme for the current Dojo 1.10 vs. the next Dojo 2.0. The response to that thread shows an active and wide community, covering many time zones.

    Unfortunately, Dojo has fallen out of popularity and fewer companies appear to use it, despite having (had?) a strong foothold in the enterprise world. In 2009-2012, its learning curve was steep and the documentation needed improvements; while the documentation has substantially improved, it's unclear how easy it is to pick up Dojo nowadays.

    With a Material Design theme, Dojo (2.0?) might be the killer UI components framework.

    WikipediaGitHubThemesDemosDesktop widgetsSO

  14. Enyo - front-end library aimed at mobile and TV apps (e.g. large touch-friendly controls). Developed by LG Electronix and Apache-licensed on GitHub.

  15. The radical Cappuccino - Objective-J (a superset of JavaScript) instead of HTML+CSS+DOM

  16. Mochaui, MooTools UI Library User Interface Library. <300 GitHub stars.

  17. CrossUI - cross-browser JS framework to develop and package the exactly same code and UI into Web Apps, Native Desktop Apps (Windows, OS X, Linux) and Mobile Apps (iOS, Android, Windows Phone, BlackBerry). Open sourced LGPL3. Featured RAD tool (form builder etc.). The UI looks desktop-, not web-oriented. Actively developed, small community. No presence on GitHub.

  18. ZinoUI - simple widgets. The DataTable, for instance, doesn't even support sorting.

  19. Wijmo - good-looking commercial widgets, with old (jQuery UI) widgets open-sourced on GitHub (their development stopped in 2013). Developed by ComponentOne, a division of GrapeCity. See Wijmo Complete vs. Open.

  20. CxJS - commercial JS framework based on React, Babel and webpack offering form elements, form validation, advanced grid control, navigational elements, tooltips, overlays, charts, routing, layout support, themes, culture dependent formatting and more.

CxJS

Widgets - Demo Apps - Examples - GitHub

Full-stack frameworks

  1. SproutCore - developed by Apple for web applications with native performance, handling large data sets on the client. Powers iCloud.com. Not intended for widgets.

  2. Wakanda: aimed at business/enterprise web apps - see What is Wakanda?. Architecture:

  3. Servoy - "a cross platform frontend development and deployment environment for SQL databases". Boasts a "full WYSIWIG (What You See Is What You Get) UI designer for HTML5 with built-in data-binding to back-end services", responsive design, support for HTML6 Web Components, Websockets and mobile platforms. Written in Java and generates JavaScript code using various JavaBeans.

  4. SmartClient/SmartGWT - mobile and cross-browser HTML5 UI components combined with a Java server. Aimed at building powerful business apps - see demos.

  5. Vaadin - full-stack Java/GWT + JavaScript/HTML3 web app framework

  6. Backbase - portal software

  7. Shiny - front-end library on top R, with visualization, layout and control widgets

  8. ZKOSS: Java+jQuery+Bootstrap framework for building enterprise web and mobile apps.

CSS libraries + minimal widgets

These libraries don't implement complex widgets such as tables with sorting/filtering, autocompletes, or trees.

  1. Bootstrap

  2. Foundation for Apps - responsive front-end framework on top of AngularJS; more of a grid/layout/navigation library

  3. UI Kit - similar to Bootstrap, with fewer widgets, but with official off-canvas.

Libraries using HTML Canvas

Using the canvas elements allows for complete control over the UI, and great cross-browser compatibility, but comes at the cost of missing native browser functionality, e.g. page search via Ctrl/Cmd+F.

  1. Zebra - demos

No longer developed as of Dec 2014

  1. Yahoo! User Interface - YUI, launched in 2005, but no longer maintained by the core contributors - see the announcement, which highlights reasons why large UI widget libraries are perceived as walled gardens that developers don't want to be locked into.
  2. echo3, GitHub. Supports writing either server-side Java applications that don't require developer knowledge of HTML, HTTP, or JavaScript, or client-side JavaScript-based applications do not require a server, but can communicate with one via AJAX. Last update: July 2013.
  3. ampleSDK
  4. Simpler widgets livepipe.net
  5. JxLib
  6. rialto
  7. Simple UI kit
  8. Prototype-ui

Other lists

When and where to use GetType() or typeof()?

typeof is applied to a name of a type or generic type parameter known at compile time (given as identifier, not as string). GetType is called on an object at runtime. In both cases the result is an object of the type System.Type containing meta-information on a type.

Example where compile-time and run-time types are equal

string s = "hello";

Type t1 = typeof(string);
Type t2 = s.GetType();

t1 == t2 ==> true

Example where compile-time and run-time types are different

object obj = "hello";

Type t1 = typeof(object); // ==> object
Type t2 = obj.GetType();  // ==> string!

t1 == t2 ==> false

i.e., the compile time type (static type) of the variable obj is not the same as the runtime type of the object referenced by obj.


Testing types

If, however, you only want to know whether mycontrol is a TextBox then you can simply test

if (mycontrol is TextBox)

Note that this is not completely equivalent to

if (mycontrol.GetType() == typeof(TextBox))    

because mycontrol could have a type that is derived from TextBox. In that case the first comparison yields true and the second false! The first and easier variant is OK in most cases, since a control derived from TextBox inherits everything that TextBox has, probably adds more to it and is therefore assignment compatible to TextBox.

public class MySpecializedTextBox : TextBox
{
}

MySpecializedTextBox specialized = new MySpecializedTextBox();
if (specialized is TextBox)       ==> true

if (specialized.GetType() == typeof(TextBox))        ==> false

Casting

If you have the following test followed by a cast and T is nullable ...

if (obj is T) {
    T x = (T)obj; // The casting tests, whether obj is T again!
    ...
}

... you can change it to ...

T x = obj as T;
if (x != null) {
    ...
}

Testing whether a value is of a given type and casting (which involves this same test again) can both be time consuming for long inheritance chains. Using the as operator followed by a test for null is more performing.

Starting with C# 7.0 you can simplify the code by using pattern matching:

if (obj is T t) {
    // t is a variable of type T having a non-null value.
    ...
}

Btw.: this works for value types as well. Very handy for testing and unboxing. Note that you cannot test for nullable value types:

if (o is int? ni) ===> does NOT compile!

This is because either the value is null or it is an int. This works for int? o as well as for object o = new Nullable<int>(x);:

if (o is int i) ===> OK!

I like it, because it eliminates the need to access the Nullable<T>.Value property.

Clear screen in shell

import curses
stdscr = curses.initscr()
stdscr.clear()

Two statements next to curly brace in an equation

That can be achieve in plain LaTeX without any specific package.

\documentclass{article}
\begin{document}
This is your only binary choices
\begin{math}
  \left\{
    \begin{array}{l}
      0\\
      1
    \end{array}
  \right.
\end{math}
\end{document}

This code produces something which looks what you seems to need.

curly braces in front of two lines

The same example as in the @Tombart can be obtained with similar code.

\documentclass{article}

\begin{document}

\begin{math}
  f(x)=\left\{
    \begin{array}{ll}
      1, & \mbox{if $x<0$}.\\
      0, & \mbox{otherwise}.
    \end{array}
  \right.
\end{math}

\end{document}

This code produces very similar results.

enter image description here

Android Studio - Device is connected but 'offline'

To fix this, use USB2 instead of USB3

Photoshop text tool adds punctuation to the beginning of text

You can try : go to edit>preferencec>type.. select type > choose text engine options select east asian. Restart photoshop. Create new peroject. Try text tool again.

(if you want to use your project created with other text engine type) copy /paste all layers to new project.

Re-run Spring Boot Configuration Annotation Processor to update generated metadata

Having included a dependency on spring-boot-configuration-processor in build.gradle:

annotationProcessor "org.springframework.boot:spring-boot-configuration-processor:2.4.1"

the only thing that worked for me, besides invalidating caches of IntelliJ and restarting, is

  1. Refresh button in side panel Reload All Gradle Projects
  2. Gradle task Clean
  3. Gradle task Build

What is a method group in C#?

A method group is the name for a set of methods (that might be just one) - i.e. in theory the ToString method may have multiple overloads (plus any extension methods): ToString(), ToString(string format), etc - hence ToString by itself is a "method group".

It can usually convert a method group to a (typed) delegate by using overload resolution - but not to a string etc; it doesn't make sense.

Once you add parentheses, again; overload resolution kicks in and you have unambiguously identified a method call.

How do I read / convert an InputStream into a String in Java?

Summarize other answers I found 11 main ways to do this (see below). And I wrote some performance tests (see results below):

Ways to convert an InputStream to a String:

  1. Using IOUtils.toString (Apache Utils)

     String result = IOUtils.toString(inputStream, StandardCharsets.UTF_8);
    
  2. Using CharStreams (Guava)

     String result = CharStreams.toString(new InputStreamReader(
           inputStream, Charsets.UTF_8));
    
  3. Using Scanner (JDK)

     Scanner s = new Scanner(inputStream).useDelimiter("\\A");
     String result = s.hasNext() ? s.next() : "";
    
  4. Using Stream API (Java 8). Warning: This solution converts different line breaks (like \r\n) to \n.

     String result = new BufferedReader(new InputStreamReader(inputStream))
       .lines().collect(Collectors.joining("\n"));
    
  5. Using parallel Stream API (Java 8). Warning: This solution converts different line breaks (like \r\n) to \n.

     String result = new BufferedReader(new InputStreamReader(inputStream))
        .lines().parallel().collect(Collectors.joining("\n"));
    
  6. Using InputStreamReader and StringBuilder (JDK)

     int bufferSize = 1024;
     char[] buffer = new char[bufferSize];
     StringBuilder out = new StringBuilder();
     Reader in = new InputStreamReader(stream, StandardCharsets.UTF_8);
     for (int numRead; (numRead = in.read(buffer, 0, buffer.length)) > 0; ) {
         out.append(buffer, 0, numRead);
     }
     return out.toString();
    
  7. Using StringWriter and IOUtils.copy (Apache Commons)

     StringWriter writer = new StringWriter();
     IOUtils.copy(inputStream, writer, "UTF-8");
     return writer.toString();
    
  8. Using ByteArrayOutputStream and inputStream.read (JDK)

     ByteArrayOutputStream result = new ByteArrayOutputStream();
     byte[] buffer = new byte[1024];
     for (int length; (length = inputStream.read(buffer)) != -1; ) {
         result.write(buffer, 0, length);
     }
     // StandardCharsets.UTF_8.name() > JDK 7
     return result.toString("UTF-8");
    
  9. Using BufferedReader (JDK). Warning: This solution converts different line breaks (like \n\r) to line.separator system property (for example, in Windows to "\r\n").

     String newLine = System.getProperty("line.separator");
     BufferedReader reader = new BufferedReader(
             new InputStreamReader(inputStream));
     StringBuilder result = new StringBuilder();
     for (String line; (line = reader.readLine()) != null; ) {
         if (result.length() > 0) {
             result.append(newLine);
         }
         result.append(line);
     }
     return result.toString();
    
  10. Using BufferedInputStream and ByteArrayOutputStream (JDK)

    BufferedInputStream bis = new BufferedInputStream(inputStream);
    ByteArrayOutputStream buf = new ByteArrayOutputStream();
    for (int result = bis.read(); result != -1; result = bis.read()) {
        buf.write((byte) result);
    }
    // StandardCharsets.UTF_8.name() > JDK 7
    return buf.toString("UTF-8");
    
  11. Using inputStream.read() and StringBuilder (JDK). Warning: This solution has problems with Unicode, for example with Russian text (works correctly only with non-Unicode text)

    StringBuilder sb = new StringBuilder();
    for (int ch; (ch = inputStream.read()) != -1; ) {
        sb.append((char) ch);
    }
    return sb.toString();
    

Warning:

  1. Solutions 4, 5 and 9 convert different line breaks to one.

  2. Solution 11 can't work correctly with Unicode text

Performance tests

Performance tests for small String (length = 175), url in github (mode = Average Time, system = Linux, score 1,343 is the best):

              Benchmark                         Mode  Cnt   Score   Error  Units
 8. ByteArrayOutputStream and read (JDK)        avgt   10   1,343 ± 0,028  us/op
 6. InputStreamReader and StringBuilder (JDK)   avgt   10   6,980 ± 0,404  us/op
10. BufferedInputStream, ByteArrayOutputStream  avgt   10   7,437 ± 0,735  us/op
11. InputStream.read() and StringBuilder (JDK)  avgt   10   8,977 ± 0,328  us/op
 7. StringWriter and IOUtils.copy (Apache)      avgt   10  10,613 ± 0,599  us/op
 1. IOUtils.toString (Apache Utils)             avgt   10  10,605 ± 0,527  us/op
 3. Scanner (JDK)                               avgt   10  12,083 ± 0,293  us/op
 2. CharStreams (guava)                         avgt   10  12,999 ± 0,514  us/op
 4. Stream Api (Java 8)                         avgt   10  15,811 ± 0,605  us/op
 9. BufferedReader (JDK)                        avgt   10  16,038 ± 0,711  us/op
 5. parallel Stream Api (Java 8)                avgt   10  21,544 ± 0,583  us/op

Performance tests for big String (length = 50100), url in github (mode = Average Time, system = Linux, score 200,715 is the best):

               Benchmark                        Mode  Cnt   Score        Error  Units
 8. ByteArrayOutputStream and read (JDK)        avgt   10   200,715 ±   18,103  us/op
 1. IOUtils.toString (Apache Utils)             avgt   10   300,019 ±    8,751  us/op
 6. InputStreamReader and StringBuilder (JDK)   avgt   10   347,616 ±  130,348  us/op
 7. StringWriter and IOUtils.copy (Apache)      avgt   10   352,791 ±  105,337  us/op
 2. CharStreams (guava)                         avgt   10   420,137 ±   59,877  us/op
 9. BufferedReader (JDK)                        avgt   10   632,028 ±   17,002  us/op
 5. parallel Stream Api (Java 8)                avgt   10   662,999 ±   46,199  us/op
 4. Stream Api (Java 8)                         avgt   10   701,269 ±   82,296  us/op
10. BufferedInputStream, ByteArrayOutputStream  avgt   10   740,837 ±    5,613  us/op
 3. Scanner (JDK)                               avgt   10   751,417 ±   62,026  us/op
11. InputStream.read() and StringBuilder (JDK)  avgt   10  2919,350 ± 1101,942  us/op

Graphs (performance tests depending on Input Stream length in Windows 7 system)
enter image description here

Performance test (Average Time) depending on Input Stream length in Windows 7 system:

 length  182    546     1092    3276    9828    29484   58968

 test8  0.38    0.938   1.868   4.448   13.412  36.459  72.708
 test4  2.362   3.609   5.573   12.769  40.74   81.415  159.864
 test5  3.881   5.075   6.904   14.123  50.258  129.937 166.162
 test9  2.237   3.493   5.422   11.977  45.98   89.336  177.39
 test6  1.261   2.12    4.38    10.698  31.821  86.106  186.636
 test7  1.601   2.391   3.646   8.367   38.196  110.221 211.016
 test1  1.529   2.381   3.527   8.411   40.551  105.16  212.573
 test3  3.035   3.934   8.606   20.858  61.571  118.744 235.428
 test2  3.136   6.238   10.508  33.48   43.532  118.044 239.481
 test10 1.593   4.736   7.527   20.557  59.856  162.907 323.147
 test11 3.913   11.506  23.26   68.644  207.591 600.444 1211.545

How do you dynamically add elements to a ListView on Android?

Create an XML layout first in your project's res/layout/main.xml folder:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >
    <Button
        android:id="@+id/addBtn"
        android:text="Add New Item"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:onClick="addItems"/>
    <ListView
        android:id="@android:id/list"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:drawSelectorOnTop="false"
    />
</LinearLayout>

This is a simple layout with a button on the top and a list view on the bottom. Note that the ListView has the id @android:id/list which defines the default ListView a ListActivity can use.

public class ListViewDemo extends ListActivity {
    //LIST OF ARRAY STRINGS WHICH WILL SERVE AS LIST ITEMS
    ArrayList<String> listItems=new ArrayList<String>();

    //DEFINING A STRING ADAPTER WHICH WILL HANDLE THE DATA OF THE LISTVIEW
    ArrayAdapter<String> adapter;

    //RECORDING HOW MANY TIMES THE BUTTON HAS BEEN CLICKED
    int clickCounter=0;

    @Override
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        setContentView(R.layout.main);
        adapter=new ArrayAdapter<String>(this,
            android.R.layout.simple_list_item_1,
            listItems);
        setListAdapter(adapter);
    }

    //METHOD WHICH WILL HANDLE DYNAMIC INSERTION
    public void addItems(View v) {
        listItems.add("Clicked : "+clickCounter++);
        adapter.notifyDataSetChanged();
    }
}

android.R.layout.simple_list_item_1 is the default list item layout supplied by Android, and you can use this stock layout for non-complex things.

listItems is a List which holds the data shown in the ListView. All the insertion and removal should be done on listItems; the changes in listItems should be reflected in the view. That's handled by ArrayAdapter<String> adapter, which should be notified using:

adapter.notifyDataSetChanged();

An Adapter is instantiated with 3 parameters: the context, which could be your activity/listactivity; the layout of your individual list item; and lastly, the list, which is the actual data to be displayed in the list.

npm command to uninstall or prune unused packages in Node.js

You can use npm-prune to remove extraneous packages.

npm prune [[<@scope>/]<pkg>...] [--production] [--dry-run] [--json]

This command removes "extraneous" packages. If a package name is provided, then only packages matching one of the supplied names are removed.

Extraneous packages are packages that are not listed on the parent package's dependencies list.

If the --production flag is specified or the NODE_ENV environment variable is set to production, this command will remove the packages specified in your devDependencies. Setting --no-production will negate NODE_ENV being set to production.

If the --dry-run flag is used then no changes will actually be made.

If the --json flag is used then the changes npm prune made (or would have made with --dry-run) are printed as a JSON object.

In normal operation with package-locks enabled, extraneous modules are pruned automatically when modules are installed and you'll only need this command with the --production flag.

If you've disabled package-locks then extraneous modules will not be removed and it's up to you to run npm prune from time-to-time to remove them.

Use npm-dedupe to reduce duplication

npm dedupe
npm ddp

Searches the local package tree and attempts to simplify the overall structure by moving dependencies further up the tree, where they can be more effectively shared by multiple dependent packages.

For example, consider this dependency graph:

a
+-- b <-- depends on [email protected]
|    `-- [email protected]
`-- d <-- depends on c@~1.0.9
     `-- [email protected]

In this case, npm-dedupe will transform the tree to:

 a
 +-- b
 +-- d
 `-- [email protected]

Because of the hierarchical nature of node's module lookup, b and d will both get their dependency met by the single c package at the root level of the tree.

The deduplication algorithm walks the tree, moving each dependency as far up in the tree as possible, even if duplicates are not found. This will result in both a flat and deduplicated tree.

How to get a list of all valid IP addresses in a local network?

Install nmap,

sudo apt-get install nmap

then

nmap -sP 192.168.1.*

or more commonly

nmap -sn 192.168.1.0/24

will scan the entire .1 to .254 range

This does a simple ping scan in the entire subnet to see which hosts are online.

What are some uses of template template parameters?

I use it for versioned types.

If you have a type versioned through a template such as MyType<version>, you can write a function in which you can capture the version number:

template<template<uint8_t> T, uint8_t Version>
Foo(const T<Version>& obj)
{
    assert(Version > 2 && "Versions older than 2 are no longer handled");
    ...
    switch (Version)
    {
    ...
    }
}

So you can do different things depending on the version of the type being passed in instead of having an overload for each type. You can also have conversion functions which take in MyType<Version> and return MyType<Version+1>, in a generic way, and even recurse them to have a ToNewest() function which returns the latest version of a type from any older version (very useful for logs that might have been stored a while back but need to be processed with today's newest tool).

Creating a mock HttpServletRequest out of a url string?

for those looking for a way to mock POST HttpServletRequest with Json payload, the below is in Kotlin, but the key take away here is the DelegatingServetInputStream when you want to mock the request.getInputStream from the HttpServletRequest

@Mock
private lateinit var request: HttpServletRequest

@Mock
private lateinit var response: HttpServletResponse

@Mock
private lateinit var chain: FilterChain

@InjectMocks
private lateinit var filter: ValidationFilter


@Test
fun `continue filter chain with valid json payload`() {
    val payload = """{
      "firstName":"aB",
      "middleName":"asdadsa",
      "lastName":"asdsada",
      "dob":null,
      "gender":"male"
    }""".trimMargin()

    whenever(request.requestURL).
        thenReturn(StringBuffer("/profile/personal-details"))
    whenever(request.method).
        thenReturn("PUT")
    whenever(request.inputStream).
        thenReturn(DelegatingServletInputStream(ByteArrayInputStream(payload.toByteArray())))

    filter.doFilter(request, response, chain)

    verify(chain).doFilter(request, response)
}

Moving uncommitted changes to a new branch

Just move to the new branch. The uncommited changes get carried over.

git checkout -b ABC_1

git commit -m <message>

How to link external javascript file onclick of button

If you want your button to call the routine you have written in filename.js you have to edit filename.js so that the code you want to run is the body of a function. For you can call a function, not a source file. (A source file has no entry point)

If the current content of your filename.js is:

_x000D_
_x000D_
alert('Hello world');
_x000D_
_x000D_
_x000D_

you have to change it to:

_x000D_
_x000D_
function functionName(){_x000D_
 alert('Hello world');_x000D_
}
_x000D_
_x000D_
_x000D_

Then you have to load filename.js in the header of your html page by the line:

_x000D_
_x000D_
<head>_x000D_
 <script type="text/javascript" src="Public/Scripts/filename.js"></script>_x000D_
</head>
_x000D_
_x000D_
_x000D_

so that you can call the function contained in filename.js by your button:

_x000D_
_x000D_
<button onclick="functionName()">Call the function</button>
_x000D_
_x000D_
_x000D_

I have made a little working example. A simple HTML page asks the user to input her name, and when she clicks the button, the function inside Public/Scripts/filename.js is called passing the inserted string as a parameter so that a popup says "Hello, <insertedName>!".

Here is the calling HTML page:

_x000D_
_x000D_
<html>_x000D_
_x000D_
 <head>_x000D_
  <script type="text/javascript" src="Public/Scripts/filename.js"></script>_x000D_
 </head>_x000D_
_x000D_
 <body>_x000D_
  What's your name? <input  id="insertedName" />_x000D_
  <button onclick="functionName(insertedName.value)">Say hello</button>_x000D_
 </body>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_

And here is Public/Scripts/filename.js

_x000D_
_x000D_
function functionName( s ){_x000D_
 alert('Hello, ' + s + '!');_x000D_
}
_x000D_
_x000D_
_x000D_

How to get Text BOLD in Alert or Confirm box?

Maybe you coul'd use UTF8 bold chars.

For examples: https://yaytext.com/bold-italic/

It works on Chromium 80.0, I don't know on other browsers...

Multiple conditions in if statement shell script

if using /bin/sh you can use:

if [ <condition> ] && [ <condition> ]; then
    ...
fi

if using /bin/bash you can use:

if [[ <condition> && <condition> ]]; then
    ...
fi

How to detect the swipe left or Right in Android?

Left to Right and Right to Left Swipe Detector

Firstly, declare two variable of float datatype.

private float x1, x2;

Secondly, wireup your xml view in java. Like I have ImageView

ImageView img = (ImageView) findViewById(R.id.imageView);

Thirdly, setOnTouchListener on your ImageView.

img.setOnTouchListener(
                    new View.OnTouchListener() {
                    @Override
                    public boolean onTouch(View v, MotionEvent event) {
                        // TODO Auto-generated method stub
                        switch (event.getAction()) {
                        case MotionEvent.ACTION_DOWN:
                            x1 = event.getX();
                            break;
                        case MotionEvent.ACTION_UP:
                            x2 = event.getX();
                            float deltaX = x2 - x1;
                            if (deltaX < 0) {
                                Toast.makeText(MainActivity.this,
                                        "Right to Left swipe",
                                        Toast.LENGTH_SHORT).show();
                            }else if(deltaX >0){
                                Toast.makeText(MainActivity.this,
                                        "Left to Right swipe",
                                        Toast.LENGTH_SHORT).show();
                            }
                            break;
                        }

                        return false;
                    }
                });

Android Studio - ADB Error - "...device unauthorized. Please check the confirmation dialog on your device."

In my case the problem was about permissions. I use Ubuntu 19.04 When running Android Studio in root user it would prompt my phone about permission requirements. But with normal user it won't do this.

So the problem was about adb not having enough permission. I made my user owner of Android folder on home directory.

sudo chown -R orkhan ~/Android

WARNING: Exception encountered during context initialization - cancelling refresh attempt

In my case, I'm using j-hipster and I had to do ./mvnw clean to overcome this warning.

MySQL: determine which database is selected?

Just use mysql_query (or mysqli_query, even better, or use PDO, best of all) with:

SELECT DATABASE() FROM DUAL;

Addendum:

There is much discussion over whether or not FROM DUAL should be included in this or not. On a technical level, it is a holdover from Oracle and can safely be removed. If you are inclined, you can use the following instead:

SELECT DATABASE();

That said, it is perhaps important to note, that while FROM DUAL does not actually do anything, it is valid MySQL syntax. From a strict perspective, including braces in a single line conditional in JavaScript also does not do anything, but it is still a valid practice.

In Visual Studio Code How do I merge between two local branches?

Actually you can do with VS Code the following:

Merge Local Branch with VS Code

Android change SDK version in Eclipse? Unable to resolve target android-x

This can happen when you mistakenly import an Android project into your Eclipse workspace as a Java project. The solution in this case: delete the project from the workspace in the Package Explorer, then go to File -> Import -> Android -> Existing Android code into workspace.

How do I set log4j level on the command line?

In my pretty standard setup I've been seeing the following work well when passed in as VM Option (commandline before class in Java, or VM Option in an IDE):

-Droot.log.level=TRACE

ERROR : [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified

Perform the following steps:

  1. Start the Registry Editor by typing regedit in the Run window.
  2. Select the following key in the registry: HKEY_LOCAL_MACHINE\SOFTWARE\ODBC.
  3. In the Security menu, click Permissions.
  4. Grant Full Permission to the account which is being used for making connections.
  5. Quit the Registry Editor.

jQuery Ajax simple call

please set dataType config property in your ajax call and give it another try!

another point is you are using ajax call setup configuration properties as string and it is wrong as reference site

$.ajax({

    url : 'http://voicebunny.comeze.com/index.php',
    type : 'GET',
    data : {
        'numberOfWords' : 10
    },
    dataType:'json',
    success : function(data) {              
        alert('Data: '+data);
    },
    error : function(request,error)
    {
        alert("Request: "+JSON.stringify(request));
    }
});

I hope be helpful!

MySQL count occurrences greater than 2

SELECT count(word) as count 
FROM words 
GROUP BY word
HAVING count >= 2;

Invert colors of an image in CSS or JavaScript

For inversion from 0 to 1 and back you can use this library InvertImages, which provides support for IE 10. I also tested with IE 11 and it should work.

Ubuntu, how do you remove all Python 3 but not 2

EDIT: As pointed out in recent comments, this solution may BREAK your system.

You most likely don't want to remove python3.

Please refer to the other answers for possible solutions.

Outdated answer (not recommended)

sudo apt-get remove 'python3.*'

How to do INSERT into a table records extracted from another table

Remove both VALUES and the parenthesis.

INSERT INTO Table2 (LongIntColumn2, CurrencyColumn2)
SELECT LongIntColumn1, Avg(CurrencyColumn) FROM Table1 GROUP BY LongIntColumn1

What is unit testing and how do you do it?

On the "How to do it" part:

I think the introduction to ScalaTest does good job of illustrating different styles of unit tests.

On the "When to do it" part:

Unit testing is not only for testing. By doing unit testing you also force the design of the software into something that is unit testable. Many people are of the opinion that this design is for the most part Good Design(TM) regardless of other benefits from testing.

So one reason to do unit test is to force your design into something that hopefully will be easier to maintain that what it would be had you not designed it for unit testing.

How to require a controller in an angularjs directive

There is a good stackoverflow answer here by Mark Rajcok:

AngularJS directive controllers requiring parent directive controllers?

with a link to this very clear jsFiddle: http://jsfiddle.net/mrajcok/StXFK/

<div ng-controller="MyCtrl">
    <div screen>
        <div component>
            <div widget>
                <button ng-click="widgetIt()">Woo Hoo</button>
            </div>
        </div>
    </div>
</div>

JavaScript

var myApp = angular.module('myApp',[])

.directive('screen', function() {
    return {
        scope: true,
        controller: function() {
            this.doSomethingScreeny = function() {
                alert("screeny!");
            }
        }
    }
})

.directive('component', function() {
    return {
        scope: true,
        require: '^screen',
        controller: function($scope) {
            this.componentFunction = function() {
                $scope.screenCtrl.doSomethingScreeny();
            }
        },
        link: function(scope, element, attrs, screenCtrl) {
            scope.screenCtrl = screenCtrl
        }
    }
})

.directive('widget', function() {
    return {
        scope: true,
        require: "^component",
        link: function(scope, element, attrs, componentCtrl) {
            scope.widgetIt = function() {
                componentCtrl.componentFunction();
            };
        }
    }
})


//myApp.directive('myDirective', function() {});
//myApp.factory('myService', function() {});

function MyCtrl($scope) {
    $scope.name = 'Superhero';
}

How To change the column order of An Existing Table in SQL Server 2008

I tried this and dont see any way of doing it.

here is my approach for it.

  1. Right click on table and Script table for Create and have this on one of the SQL Query window,
  2. EXEC sp_rename 'Employee', 'Employee1' -- Original table name is Employee
  3. Execute the Employee create script, make sure you arrange the columns in the way you need.
  4. INSERT INTO TABLE2 SELECT * FROM TABLE1. -- Insert into Employee select Name, Company from Employee1
  5. DROP table Employee1.

How to send a POST request in Go?

I know this is old but this answer came up in search results. For the next guy - the proposed and accepted answer works, however the code initially submitted in the question is lower-level than it needs to be. Nobody got time for that.

//one-line post request/response...
response, err := http.PostForm(APIURL, url.Values{
    "ln": {c.ln},
    "ip": {c.ip},
    "ua": {c.ua}})

//okay, moving on...
if err != nil {
  //handle postform error
}

defer response.Body.Close()
body, err := ioutil.ReadAll(response.Body)

if err != nil {
  //handle read response error
}

fmt.Printf("%s\n", string(body))

https://golang.org/pkg/net/http/#pkg-overview

AngularJS - How to use $routeParams in generating the templateUrl?

templateUrl can be use as function with returning generated URL. We can manipulate url with passing argument which takes routeParams.

See the example.

.when('/:screenName/list',{
    templateUrl: function(params){
         return params.screenName +'/listUI'
    }
})

Hope this help.

How do you check if a variable is an array in JavaScript?

This is an old question but having the same problem i found a very elegant solution that i want to share.

Adding a prototype to Array makes it very simple

Array.prototype.isArray = true;

Now once if you have an object you want to test to see if its an array all you need is to check for the new property

var box = doSomething();

if (box.isArray) {
    // do something
}

isArray is only available if its an array

curl POST format for CURLOPT_POSTFIELDS

It depends on the content-type

url-encoded or multipart/form-data

To send data the standard way, as a browser would with a form, just pass an associative array. As stated by PHP's manual:

This parameter can either be passed as a urlencoded string like 'para1=val1&para2=val2&...' or as an array with the field name as key and field data as value. If value is an array, the Content-Type header will be set to multipart/form-data.

JSON encoding

Neverthless, when communicating with JSON APIs, content must be JSON encoded for the API to understand our POST data.

In such cases, content must be explicitely encoded as JSON :

CURLOPT_POSTFIELDS => json_encode(['param1' => $param1, 'param2' => $param2]),

When communicating in JSON, we also usually set accept and content-type headers accordingly:

CURLOPT_HTTPHEADER => [
    'accept: application/json',
    'content-type: application/json'
]

Different ways of loading a file as an InputStream

All these answers around here, as well as the answers in this question, suggest that loading absolute URLs, like "/foo/bar.properties" treated the same by class.getResourceAsStream(String) and class.getClassLoader().getResourceAsStream(String). This is NOT the case, at least not in my Tomcat configuration/version (currently 7.0.40).

MyClass.class.getResourceAsStream("/foo/bar.properties"); // works!  
MyClass.class.getClassLoader().getResourceAsStream("/foo/bar.properties"); // does NOT work!

Sorry, I have absolutely no satisfying explanation, but I guess that tomcat does dirty tricks and his black magic with the classloaders and cause the difference. I always used class.getResourceAsStream(String) in the past and haven't had any problems.

PS: I also posted this over here

No connection could be made because the target machine actively refused it 127.0.0.1

If you have this while Fiddler is running -> in Fiddler, go to 'Rules' and disable 'Automatically Authenticate' and it should work again.

Linq : select value in a datatable column

Use linq and set the data table as Enumerable and select the fields from the data table field that matches what you are looking for.

Example

I want to get the currency Id and currency Name from the currency table where currency is local currency, and assign the currency id and name to a text boxes on the form:

DataTable dt = curData.loadCurrency();
            var curId = from c in dt.AsEnumerable()
                        where c.Field<bool>("LocalCurrency") == true
                        select c.Field<int>("CURID");

            foreach (int cid in curId)
            {
                txtCURID.Text = cid.ToString();
            }
            var curName = from c in dt.AsEnumerable()
                          where c.Field<bool>("LocalCurrency") == true
                          select c.Field<string>("CurName");
            foreach (string cName in curName)
            {
                txtCurrency.Text = cName.ToString();
            }

What's the difference between django OneToOneField and ForeignKey?

Also OneToOneField is useful to be used as primary key to avoid key duplication. One may do not have implicit / explicit autofield

models.AutoField(primary_key=True)

but use OneToOneField as primary key instead (imagine UserProfile model for example):

user = models.OneToOneField(
    User, null=False, primary_key=True, verbose_name='Member profile')

How can one check to see if a remote file exists using PHP?

You should issue HEAD requests, not GET one, because you don't need the URI contents at all. As Pies said above, you should check for status code (in 200-299 ranges, and you may optionally follow 3xx redirects).

The answers question contain a lot of code examples which may be helpful: PHP / Curl: HEAD Request takes a long time on some sites

Adding an arbitrary line to a matplotlib plot in ipython notebook

Rather than abusing plot or annotate, which will be inefficient for many lines, you can use matplotlib.collections.LineCollection:

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.collections import LineCollection

np.random.seed(5)
x = np.arange(1, 101)
y = 20 + 3 * x + np.random.normal(0, 60, 100)
plt.plot(x, y, "o")

# Takes list of lines, where each line is a sequence of coordinates
l1 = [(70, 100), (70, 250)]
l2 = [(70, 90), (90, 200)]
lc = LineCollection([l1, l2], color=["k","blue"], lw=2)

plt.gca().add_collection(lc)

plt.show()

Figure with two lines plotted via LineCollection

It takes a list of lines [l1, l2, ...], where each line is a sequence of N coordinates (N can be more than two).

The standard formatting keywords are available, accepting either a single value, in which case the value applies to every line, or a sequence of M values, in which case the value for the ith line is values[i % M].

can't multiply sequence by non-int of type 'float'

You're multipling your "1 + 0.01" times the growthRate list, not the item in the list you're iterating through. I've renamed i to rate and using that instead. See the updated code below:

def nestEgVariable(salary, save, growthRates):
    SavingsRecord = []
    fund = 0
    depositPerYear = salary * save * 0.01
    #    V-- rate is a clearer name than i here, since you're iterating through the rates contained in the growthRates list
    for rate in growthRates:  
        #                           V-- Use the `rate` item in the growthRate list you're iterating through rather than multiplying by the `growthRate` list itself.
        fund = fund * (1 + 0.01 * rate) + depositPerYear
        SavingsRecord += [fund,]
    return SavingsRecord 


print nestEgVariable(10000,10,[3,4,5,0,3])

How to reference Microsoft.Office.Interop.Excel dll?

Building off of Mulfix's answer, if you have Visual Studio Community 2015, try Add Reference... -> COM -> Type Libraries -> 'Microsoft Excel 15.0 Object Library'.

Can regular JavaScript be mixed with jQuery?

Of course you can, but why do this? You have to include a <script></script>pair of tags that link to the jQuery web page, i.e.: <script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script> . Then you will load the whole jQuery object just to use one single function, and because jQuery is a JavaScript library which will take time for the computer to upload, it will execute slower than just JavaScript.

How to restore the dump into your running mongodb

Dump DB by mongodump

mongodump --host <database-host> -d <database-name> --port <database-port> --out directory

Restore DB by mongorestore

With Index Restore

mongorestore --host <database-host> -d <database-name> --port <database-port> foldername

Without Index Restore

mongorestore --noIndexRestore --host <database-host> -d <database-name> --port <database-port> foldername

Import Single Collection from CSV [1st Column will be treat as Col/Key Name]

mongoimport --db <database-name> --port <database-port> --collection <collection-name> --type csv --headerline --file /path/to/myfile.csv

Import Single Collection from JSON

mongoimport --db <database-name> --port <database-port> --collection <collection-name> --file input.json

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.

When to use an interface instead of an abstract class and vice versa?

An abstract class can have implementations.

An interface doesn't have implementations, it simply defines a kind of contract.

There can also be some language-dependent differences: for example C# does not have multiple inheritance, but multiple interfaces can be implemented in a class.

Redirect with CodeIgniter

If your directory structure is like this,

site
  application
         controller
                folder_1
                   first_controller.php
                   second_controller.php
                folder_2
                   first_controller.php
                   second_controller.php

And when you are going to redirect it in same controller in which you are working then just write the following code.

 $this->load->helper('url');
    if ($some_value === FALSE/TRUE) //You may give 0/1 as well,its up to your logic
    {
         redirect('same_controller/method', 'refresh');
    }

And if you want to redirect to another control then use the following code.

$this->load->helper('url');
if ($some_value === FALSE/TRUE) //You may give 0/1 as well,its up to your logic
{
     redirect('folder_name/any_controller_name/method', 'refresh');
}

Display Image On Text Link Hover CSS Only

CSS isn't going to be able to call other elements like that, you'll need to use JavaScript to reach beyond a child or sibling selector.

You could try something like this:

<a>Some Link
<div><img src="/you/image" /></div>
</a>

then...

a>div { display: none; }
a:hover>div { display: block; }

Differences between utf8 and latin1

UTF-8 is prepared for world domination, Latin1 isn't.

If you're trying to store non-Latin characters like Chinese, Japanese, Hebrew, Russian, etc using Latin1 encoding, then they will end up as mojibake. You may find the introductory text of this article useful (and even more if you know a bit Java).

Note that full 4-byte UTF-8 support was only introduced in MySQL 5.5. Before that version, it only goes up to 3 bytes per character, not 4 bytes per character. So, it supported only the BMP plane and not e.g. the Emoji plane. If you want full 4-byte UTF-8 support, upgrade MySQL to at least 5.5 or go for another RDBMS like PostgreSQL. In MySQL 5.5+ it's called utf8mb4.

Java: convert List<String> to a String

Java 8 does bring the

Collectors.joining(CharSequence delimiter, CharSequence prefix, CharSequence suffix)

method, that is nullsafe by using prefix + suffix for null values.

It can be used in the following manner:

String s = stringList.stream().collect(Collectors.joining(" and ", "prefix_", "_suffix"))

The Collectors.joining(CharSequence delimiter) method just calls joining(delimiter, "", "") internally.

Java string to date conversion

Source Link

For Android

Calendar.getInstance().getTime() gives

Thu Jul 26 15:54:13 GMT+05:30 2018

Use

String oldDate = "Thu Jul 26 15:54:13 GMT+05:30 2018";
DateFormat format = new SimpleDateFormat("EEE LLL dd HH:mm:ss Z yyyy");
Date updateLast = format.parse(oldDate);

Difference between window.location.href=window.location.href and window.location.reload()

As said, modifying the href when there is a hash (#) in the url would not reload the page. Thus, I use this to reload it instead of regular expressions:

if (!window.location.hash) {
    window.location.href = window.location.href;
} else {
    window.location.reload();
}

Change Text Color of Selected Option in a Select Box

<html>
  <style>
.selectBox{
 color:White;
}
.optionBox{
  color:black;
}

</style>
<body>
<select class = "selectBox">
  <option class = "optionBox">One</option>
  <option class = "optionBox">Two</option>
  <option class = "optionBox">Three</option>
</select>

Laravel update model with unique validation rule for attribute

or what you could do in your Form Request is (for Laravel 5.3+)

public function rules()
    {
        return [

            'email' => 'required|email|unique:users,email,'.$this->user, //here user is users/{user} from resource's route url
               ];
    }

i've done it in Laravel 5.6 and it worked.

How do you exit from a void function in C++?

void foo() {
  /* do some stuff */
  if (!condition) {
    return;
  }
}

You can just use the return keyword just like you would in any other function.

How to access parameters in a RESTful POST method

Your @POST method should be accepting a JSON object instead of a string. Jersey uses JAXB to support marshaling and unmarshaling JSON objects (see the jersey docs for details). Create a class like:

@XmlRootElement
public class MyJaxBean {
    @XmlElement public String param1;
    @XmlElement public String param2;
}

Then your @POST method would look like the following:

@POST @Consumes("application/json")
@Path("/create")
public void create(final MyJaxBean input) {
    System.out.println("param1 = " + input.param1);
    System.out.println("param2 = " + input.param2);
}

This method expects to receive JSON object as the body of the HTTP POST. JAX-RS passes the content body of the HTTP message as an unannotated parameter -- input in this case. The actual message would look something like:

POST /create HTTP/1.1
Content-Type: application/json
Content-Length: 35
Host: www.example.com

{"param1":"hello","param2":"world"}

Using JSON in this way is quite common for obvious reasons. However, if you are generating or consuming it in something other than JavaScript, then you do have to be careful to properly escape the data. In JAX-RS, you would use a MessageBodyReader and MessageBodyWriter to implement this. I believe that Jersey already has implementations for the required types (e.g., Java primitives and JAXB wrapped classes) as well as for JSON. JAX-RS supports a number of other methods for passing data. These don't require the creation of a new class since the data is passed using simple argument passing.


HTML <FORM>

The parameters would be annotated using @FormParam:

@POST
@Path("/create")
public void create(@FormParam("param1") String param1,
                   @FormParam("param2") String param2) {
    ...
}

The browser will encode the form using "application/x-www-form-urlencoded". The JAX-RS runtime will take care of decoding the body and passing it to the method. Here's what you should see on the wire:

POST /create HTTP/1.1
Host: www.example.com
Content-Type: application/x-www-form-urlencoded;charset=UTF-8
Content-Length: 25

param1=hello&param2=world

The content is URL encoded in this case.

If you do not know the names of the FormParam's you can do the following:

@POST @Consumes("application/x-www-form-urlencoded")
@Path("/create")
public void create(final MultivaluedMap<String, String> formParams) {
    ...
}

HTTP Headers

You can using the @HeaderParam annotation if you want to pass parameters via HTTP headers:

@POST
@Path("/create")
public void create(@HeaderParam("param1") String param1,
                   @HeaderParam("param2") String param2) {
    ...
}

Here's what the HTTP message would look like. Note that this POST does not have a body.

POST /create HTTP/1.1
Content-Length: 0
Host: www.example.com
param1: hello
param2: world

I wouldn't use this method for generalized parameter passing. It is really handy if you need to access the value of a particular HTTP header though.


HTTP Query Parameters

This method is primarily used with HTTP GETs but it is equally applicable to POSTs. It uses the @QueryParam annotation.

@POST
@Path("/create")
public void create(@QueryParam("param1") String param1,
                   @QueryParam("param2") String param2) {
    ...
}

Like the previous technique, passing parameters via the query string does not require a message body. Here's the HTTP message:

POST /create?param1=hello&param2=world HTTP/1.1
Content-Length: 0
Host: www.example.com

You do have to be particularly careful to properly encode query parameters on the client side. Using query parameters can be problematic due to URL length restrictions enforced by some proxies as well as problems associated with encoding them.


HTTP Path Parameters

Path parameters are similar to query parameters except that they are embedded in the HTTP resource path. This method seems to be in favor today. There are impacts with respect to HTTP caching since the path is what really defines the HTTP resource. The code looks a little different than the others since the @Path annotation is modified and it uses @PathParam:

@POST
@Path("/create/{param1}/{param2}")
public void create(@PathParam("param1") String param1,
                   @PathParam("param2") String param2) {
    ...
}

The message is similar to the query parameter version except that the names of the parameters are not included anywhere in the message.

POST /create/hello/world HTTP/1.1
Content-Length: 0
Host: www.example.com

This method shares the same encoding woes that the query parameter version. Path segments are encoded differently so you do have to be careful there as well.


As you can see, there are pros and cons to each method. The choice is usually decided by your clients. If you are serving FORM-based HTML pages, then use @FormParam. If your clients are JavaScript+HTML5-based, then you will probably want to use JAXB-based serialization and JSON objects. The MessageBodyReader/Writer implementations should take care of the necessary escaping for you so that is one fewer thing that can go wrong. If your client is Java based but does not have a good XML processor (e.g., Android), then I would probably use FORM encoding since a content body is easier to generate and encode properly than URLs are. Hopefully this mini-wiki entry sheds some light on the various methods that JAX-RS supports.

Note: in the interest of full disclosure, I haven't actually used this feature of Jersey yet. We were tinkering with it since we have a number of JAXB+JAX-RS applications deployed and are moving into the mobile client space. JSON is a much better fit that XML on HTML5 or jQuery-based solutions.

installing JDK8 on Windows XP - advapi32.dll error

With JRE 8 on XP there is another way - to use MSI to deploy package.

  • Install JRE 8 x86 on a PC with supported OS
  • Copy c:\Users[USER]\AppData\LocalLow\Sun\Java\jre1.8.0\jre1.8.0.msi and Data1.cab to XP PC and run jre1.8.0.msi

or (silent way, usable in batch file etc..)

for %%I in ("*.msi") do if exist "%%I" msiexec.exe /i %%I /qn EULA=0 SKIPLICENSE=1 PROG=0 ENDDIALOG=0

Difference between Git and GitHub

In plain English:

  1. They are all source control as we all know.
  2. In an analogy, if Git is a standalone computer, then GitHub is a network of computers connected by web with bells and whistlers.
  3. So unless you open a GitHub acct and specifically tell VSC or any editor to use GitHub, you'll see your source code up-there otherwise they are only down here, - your local machine.

React: why child component doesn't update when prop changes

You should probably make the Child as functional component if it does not maintain any state and simply renders the props and then call it from the parent. Alternative to this is that you can use hooks with the functional component (useState) which will cause stateless component to re-render.

Also you should not alter the propas as they are immutable. Maintain state of the component.

Child = ({bar}) => (bar);

php - push array into array - key issue

I think you have to go for

$arrayname[indexname] = $value;

Transfer data between databases with PostgreSQL

Databases are isolated in PostgreSQL; when you connect to a PostgreSQL server you connect to just one database, you can't copy data from one database to another using a SQL query.

If you come from MySQL: what MySQL calls (loosely) "databases" are "schemas" in PostgreSQL - sort of namespaces. A PostgreSQL database can have many schemas, each one with its tables and views, and you can copy from one schema to another with the schema.table syntax.

If you really have two distinct PostgreSQL databases, the common way of transferring data from one to another would be to export your tables (with pg_dump -t ) to a file, and import them into the other database (with psql).

If you really need to get data from a distinct PostgreSQL database, another option - mentioned in Grant Johnson's answer - is dblink, which is an additional module (in contrib/).

Update:

Postgres introduced "foreign data wrapper" in 9.1 (which was released after the question was asked). Foreign data wrappers allow the creation of foreign tables through the Postgres FDW which makes it possible to access a remote table (on a different server and database) as if it was a local table.

NuGet Package Restore Not Working

In my case, an aborted Nuget restore-attempt had corrupted one of the packages.configfiles in the solution. I did not discover this before checking my git working tree. After reverting the changes in the file, Nuget restore was working again.

Validate that end date is greater than start date with jQuery

I like what Franz said, because is what I'm using :P

var date_ini = new Date($('#id_date_ini').val()).getTime();
var date_end = new Date($('#id_date_end').val()).getTime();
if (isNaN(date_ini)) {
// error date_ini;
}
if (isNaN(date_end)) {
// error date_end;
}
if (date_ini > date_end) {
// do something;
}

jQuery remove all list items from an unordered list

$("ul").empty() works fine. Is there some other error?

_x000D_
_x000D_
$('input').click(function() {_x000D_
  $('ul').empty()_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<ul>_x000D_
  <li>test</li>_x000D_
  <li>test</li>_x000D_
</ul>_x000D_
_x000D_
<input type="button" value="click me" />
_x000D_
_x000D_
_x000D_

http://jsfiddle.net/infernalbadger/D5ss8/

How to get the nth element of a python list or a default if not available

A cheap solution is to really make a dict with enumerate and use .get() as usual, like

 dict(enumerate(l)).get(7, my_default)

Problems with installation of Google App Engine SDK for php in OS X

It's likely that the download was corrupted if you are getting an error with the disk image. Go back to the downloads page at https://developers.google.com/appengine/downloads and look at the SHA1 checksum. Then, go to your Terminal app on your mac and run the following:

openssl sha1 [put the full path to the file here without brackets] 

For example:

openssl sha1 /Users/me/Desktop/myFile.dmg 

If you get a different value than the one on the Downloads page, you know your file is not properly downloaded and you should try again.

How do I make a list of data frames?

This may be a little late but going back to your example I thought I would extend the answer just a tad.

 D1 <- data.frame(Y1=c(1,2,3), Y2=c(4,5,6))
 D2 <- data.frame(Y1=c(3,2,1), Y2=c(6,5,4))
 D3 <- data.frame(Y1=c(6,5,4), Y2=c(3,2,1))
 D4 <- data.frame(Y1=c(9,9,9), Y2=c(8,8,8))

Then you make your list easily:

mylist <- list(D1,D2,D3,D4)

Now you have a list but instead of accessing the list the old way such as

mylist[[1]] # to access 'd1'

you can use this function to obtain & assign the dataframe of your choice.

GETDF_FROMLIST <- function(DF_LIST, ITEM_LOC){
   DF_SELECTED <- DF_LIST[[ITEM_LOC]]
   return(DF_SELECTED)
}

Now get the one you want.

D1 <- GETDF_FROMLIST(mylist, 1)
D2 <- GETDF_FROMLIST(mylist, 2)
D3 <- GETDF_FROMLIST(mylist, 3)
D4 <- GETDF_FROMLIST(mylist, 4)

Hope that extra bit helps.

Cheers!

Oracle SQL escape character (for a '&')

SELECT 'Free &' || ' Clear' FROM DUAL;

Android SeekBar setOnSeekBarChangeListener

Seekbar called onProgressChanged method when we initialize first time. We can skip by using below code We need to check boolean it return false when initialize automatically

volumeManager.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
                if(b){
                    mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, i, 0);
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });

font size in html code

<html>        
    <table>
        <tr>
            <td style="padding-left: 5px;padding-bottom:3px; font-size:35px;"> <b>Datum:</b><br/>
            November 2010 </td>
    </table>
</html>

Calling method using JavaScript prototype

function MyClass() {}

MyClass.prototype.myMethod = function() {
  alert( "doing original");
};
MyClass.prototype.myMethod_original = MyClass.prototype.myMethod;
MyClass.prototype.myMethod = function() {
  MyClass.prototype.myMethod_original.call( this );
  alert( "doing override");
};

myObj = new MyClass();
myObj.myMethod();

Selenium IDE - Command to wait for 5 seconds

Your best bet is probably waitForCondition and writing a javascript function that returns true when the map is loaded.

Fatal error: [] operator not supported for strings

Such behavior is described in Migrating from PHP 7.0.x to PHP 7.1.x/

The empty index operator is not supported for strings anymore Applying the empty index operator to a string (e.g. $str[] = $x) throws a fatal error instead of converting silently to array.

In my case it was a mere initialization. I fixed it by replacing $foo='' with $foo=[].

$foo='';
$foo[]='test';
print_r($foo);

How to convert date format to milliseconds?

beginupd.getTime() will give you time in milliseconds since January 1, 1970, 00:00:00 GMT till the time you have specified in Date object

'Missing contentDescription attribute on image' in XML

Updated:

As pointed out in the comments, setting the description to null indicates that the image is purely decorative and is understood as that by screen readers like TalkBack.

Old answer, I no longer support this answer:

For all the people looking how to avoid the warning:

I don't think android:contentDescription="@null" is the best solution.

I'm using tools:ignore="ContentDescription" that is what is meant to be.

Make sure you include xmlns:tools="http://schemas.android.com/tools" in your root layout.

Insert auto increment primary key to existing table

In order to make the existing primary key as auto_increment, you may use:

ALTER TABLE table_name MODIFY id INT AUTO_INCREMENT;

How does MySQL CASE work?

CASE in MySQL is both a statement and an expression, where each usage is slightly different.

As a statement, CASE works much like a switch statement and is useful in stored procedures, as shown in this example from the documentation (linked above):

DELIMITER |

CREATE PROCEDURE p()
  BEGIN
    DECLARE v INT DEFAULT 1;

    CASE v
      WHEN 2 THEN SELECT v;
      WHEN 3 THEN SELECT 0;
      ELSE
        BEGIN -- Do other stuff
        END;
    END CASE;
  END;
  |

However, as an expression it can be used in clauses:

SELECT *
  FROM employees
  ORDER BY
    CASE title
      WHEN "President" THEN 1
      WHEN "Manager" THEN 2
      ELSE 3
    END, surname

Additionally, both as a statement and as an expression, the first argument can be omitted and each WHEN must take a condition.

SELECT *
  FROM employees
  ORDER BY
    CASE 
      WHEN title = "President" THEN 1
      WHEN title = "Manager" THEN 2
      ELSE 3
    END, surname

I provided this answer because the other answer fails to mention that CASE can function both as a statement and as an expression. The major difference between them is that the statement form ends with END CASE and the expression form ends with just END.

C# cannot convert method to non delegate type

As mentioned you need to use obj.getTile()

But, in this case I think you are looking to use a Property.

public class Pin
{
    private string title;

    public Pin() { }

    public setTitle(string title) {
        this.title = title;
    }

    public String Title
    {
        get { return title; }
    }
}

This will allow you to use

foreach (Pin obj in ClassListPin.pins)
{
     string t = obj.Title;
}

Links in <select> dropdown options

Maybe this will help:

<select onchange="location = this.value;">
 <option value="home.html">Home</option>
 <option value="contact.html">Contact</option>
 <option value="about.html">About</option>
</select>

Android studio Error "Unsupported Modules Detected: Compilation is not supported for following modules"

  1. save .idea folder somewhere else (for backup)
  2. remove .idea folder
  3. start AndroidStudio
  4. select project
  5. [there may be an error, ignore that]
  6. click File -> Invalidate Caches/ Restart
  7. click button: Invalidate Caches/ Restart
  8. resolved

How to change font size on part of the page in LaTeX?

\begingroup
    \fontsize{10pt}{12pt}\selectfont
    \begin{verbatim}  
        % how to set font size here to 10 px ?  
    \end{verbatim}  
\endgroup

Shell equality operators (=, ==, -eq)

== is a bash-specific alias for = and it performs a string (lexical) comparison instead of a numeric comparison. eq being a numeric comparison of course.

Finally, I usually prefer to use the form if [ "$a" == "$b" ]

string in namespace std does not name a type

Nouns.h doesn't include <string>, but it needs to. You need to add

#include <string>

at the top of that file, otherwise the compiler doesn't know what std::string is when it is encountered for the first time.

Find JavaScript function definition in Chrome

You can print the function by evaluating the name of it in the console, like so

> unknownFunc
function unknownFunc(unknown) {
    alert('unknown seems to be ' + unknown);
}

this won't work for built-in functions, they will only display [native code] instead of the source code.

EDIT: this implies that the function has been defined within the current scope.

Check if table exists without using "select from"

You can query the INFORMATION_SCHEMA tables system view:

SELECT table_name
FROM information_schema.tables
WHERE table_schema = 'databasename'
AND table_name = 'testtable';

If no rows returned, then the table doesn't exist.

Checking Date format from a string in C#

https://msdn.microsoft.com/es-es/library/h9b85w22(v=vs.110).aspx

string[] formats= {"M/d/yyyy h:mm:ss tt", "M/d/yyyy h:mm tt", 
                     "MM/dd/yyyy hh:mm:ss", "M/d/yyyy h:mm:ss", 
                     "M/d/yyyy hh:mm tt", "M/d/yyyy hh tt", 
                     "M/d/yyyy h:mm", "M/d/yyyy h:mm", 
                     "MM/dd/yyyy hh:mm", "M/dd/yyyy hh:mm"};
  string[] dateStrings = {"5/1/2009 6:32 PM", "05/01/2009 6:32:05 PM", 
                          "5/1/2009 6:32:00", "05/01/2009 06:32", 
                          "05/01/2009 06:32:00 PM", "05/01/2009 06:32:00"}; 
  DateTime dateValue;

  foreach (string dateString in dateStrings)
  {
     if (DateTime.TryParseExact(dateString, formats, 
                                new CultureInfo("en-US"), 
                                DateTimeStyles.None, 
                                out dateValue))
        Console.WriteLine("Converted '{0}' to {1}.", dateString, dateValue);
     else
        Console.WriteLine("Unable to convert '{0}' to a date.", dateString);
  }

Django Cookies, how can I set them?

UPDATE : check Peter's answer below for a builtin solution :

This is a helper to set a persistent cookie:

import datetime

def set_cookie(response, key, value, days_expire=7):
    if days_expire is None:
        max_age = 365 * 24 * 60 * 60  # one year
    else:
        max_age = days_expire * 24 * 60 * 60
    expires = datetime.datetime.strftime(
        datetime.datetime.utcnow() + datetime.timedelta(seconds=max_age),
        "%a, %d-%b-%Y %H:%M:%S GMT",
    )
    response.set_cookie(
        key,
        value,
        max_age=max_age,
        expires=expires,
        domain=settings.SESSION_COOKIE_DOMAIN,
        secure=settings.SESSION_COOKIE_SECURE or None,
    )

Use the following code before sending a response.

def view(request):
    response = HttpResponse("hello")
    set_cookie(response, 'name', 'jujule')
    return response

UPDATE : check Peter's answer below for a builtin solution :

Removing elements from array Ruby

Not very simple but:

a = [1,1,1,2,2,3]
b = a.group_by {|n| n}.each {|k,v| v.pop [1,3].count(k)}.values.flatten
=> [1, 1, 2, 2]

Also handles the case for multiples in the 'subtrahend':

a = [1,1,1,2,2,3]
b = a.group_by {|n| n}.each {|k,v| v.pop [1,1,3].count(k)}.values.flatten
=> [1, 2, 2]

EDIT: this is more an enhancement combining Norm212 and my answer to make a "functional" solution.

b = [1,1,3].each.with_object( a ) { |del| a.delete_at( a.index( del ) ) }

Put it in a lambda if needed:

subtract = lambda do |minuend, subtrahend|
  subtrahend.each.with_object( minuend ) { |del| minuend.delete_at( minuend.index( del ) ) }
end

then:

subtract.call a, [1,1,3]

Two decimal places using printf( )

Use: "%.2f" or variations on that.

See the POSIX spec for an authoritative specification of the printf() format strings. Note that it separates POSIX extras from the core C99 specification. There are some C++ sites which show up in a Google search, but some at least have a dubious reputation, judging from comments seen elsewhere on SO.

Since you're coding in C++, you should probably be avoiding printf() and its relatives.

How to terminate a python subprocess launched with shell=True

Use a process group so as to enable sending a signal to all the process in the groups. For that, you should attach a session id to the parent process of the spawned/child processes, which is a shell in your case. This will make it the group leader of the processes. So now, when a signal is sent to the process group leader, it's transmitted to all of the child processes of this group.

Here's the code:

import os
import signal
import subprocess

# The os.setsid() is passed in the argument preexec_fn so
# it's run after the fork() and before  exec() to run the shell.
pro = subprocess.Popen(cmd, stdout=subprocess.PIPE, 
                       shell=True, preexec_fn=os.setsid) 

os.killpg(os.getpgid(pro.pid), signal.SIGTERM)  # Send the signal to all the process groups

How can I check if a MySQL table exists with PHP?

$res = mysql_query("SELECT table_name FROM information_schema.tables WHERE table_schema = '$databasename' AND table_name = '$tablename';");

If no records are returned then it doesn't exist.

WCF Service Client: The content type text/html; charset=utf-8 of the response message does not match the content type of the binding

Even if you don't use network proxy, turning 'Automatically detect settings' in proxy dialog makes this exception go off.

enter image description here

Program to find largest and second largest number in array

#include<stdio.h>

int main()
{
    int a[10];
    int i,b,c;

    printf("Enter ten values : \n");
    for(i=0; i<10; i++)
    {
        scanf("%d",&a[i]);
    }

    b=a[0];

    for(i=0; i<10; i++)
    {
        if(a[i]>b)
        {
            b=a[i];
        }

        else
        {
            b=b;
        }
    }

    if(b==a[1])
    {
        c=a[2];
    }
    else 
    {
        c=a[1];
    }

    for(i=0; i<10; i++)
    {
        if(a[i]>c && a[i]!=b)
        {
            c=a[i];
        }

        else if (b>c)
        {
            c=c;
        }

    }




    printf("Largest number is %d\nSecond largest number is %d",b,c);

}

From ND to 1D arrays

I wanted to see a benchmark result of functions mentioned in answers including unutbu's.

Also want to point out that numpy doc recommend to use arr.reshape(-1) in case view is preferable. (even though ravel is tad faster in the following result)


TL;DR: np.ravel is the most performant (by very small amount).

Benchmark

Functions:

numpy version: '1.18.0'

Execution times on different ndarray sizes

+-------------+----------+-----------+-----------+-------------+
|  function   |   10x10  |  100x100  | 1000x1000 | 10000x10000 |
+-------------+----------+-----------+-----------+-------------+
| ravel       | 0.002073 |  0.002123 |  0.002153 |    0.002077 |
| reshape(-1) | 0.002612 |  0.002635 |  0.002674 |    0.002701 |
| flatten     | 0.000810 |  0.007467 |  0.587538 |  107.321913 |
| flat        | 0.000337 |  0.000255 |  0.000227 |    0.000216 |
+-------------+----------+-----------+-----------+-------------+

Conclusion

ravel and reshape(-1)'s execution time was consistent and independent from ndarray size. However, ravel is tad faster, but reshape provides flexibility in reshaping size. (maybe that's why numpy doc recommend to use it instead. Or there could be some cases where reshape returns view and ravel doesn't).
If you are dealing with large size ndarray, using flatten can cause a performance issue. Recommend not to use it. Unless you need a copy of the data to do something else.

Used code

import timeit
setup = '''
import numpy as np
nd = np.random.randint(10, size=(10, 10))
'''

timeit.timeit('nd = np.reshape(nd, -1)', setup=setup, number=1000)
timeit.timeit('nd = np.ravel(nd)', setup=setup, number=1000)
timeit.timeit('nd = nd.flatten()', setup=setup, number=1000)
timeit.timeit('nd.flat', setup=setup, number=1000)

Find all stored procedures that reference a specific column in some table

try this..

SELECT Name
FROM sys.procedures
WHERE OBJECT_DEFINITION(OBJECT_ID) LIKE '%CreatedDate%'
GO

or you can generate a scripts of all procedures and search from there.

How to solve java.lang.NullPointerException error?

A NullPointerException means that one of the variables you are passing is null, but the code tries to use it like it is not.

For example, If I do this:

Integer myInteger = null;
int n = myInteger.intValue();

The code tries to grab the intValue of myInteger, but since it is null, it does not have one: a null pointer exception happens.

What this means is that your getTask method is expecting something that is not a null, but you are passing a null. Figure out what getTask needs and pass what it wants!

Mysql service is missing

I also face the same problem. do the simple steps

  1. Go to bin directory copy the path and set it as a environment variable.
  2. Run the command prompt as admin and cd to bin directory:
  3. Run command : mysqld –install
  4. Now the services are successfully installed
  5. Start the service in service windows of os
  6. Type mysql and go

What does "app.run(host='0.0.0.0') " mean in Flask

To answer to your second question. You can just hit the IP address of the machine that your flask app is running, e.g. 192.168.1.100 in a browser on different machine on the same network and you are there. Though, you will not be able to access it if you are on a different network. Firewalls or VLans can cause you problems with reaching your application. If that computer has a public IP, then you can hit that IP from anywhere on the planet and you will be able to reach the app. Usually this might impose some configuration, since most of the public servers are behind some sort of router or firewall.

LINQ Group By and select collection

you may also like this

var Grp = Model.GroupBy(item => item.Order.Customer)
      .Select(group => new 
        { 
             Customer = Model.First().Customer, 
             CustomerId= group.Key,  
             Orders= group.ToList() 
       })
      .ToList();

Adding new files to a subversion repository

Probably svn import would be the best option around. Check out Getting Data into Your Repository (in Version Control with Subversion, For Subversion).

The svn import command is a quick way to copy an unversioned tree of files into a repository, creating intermediate directories as necessary. svn import doesn't require a working copy, and your files are immediately committed to the repository. You typically use this when you have an existing tree of files that you want to begin tracking in your Subversion repository. For example:

$ svn import /path/to/mytree \
             http://svn.example.com/svn/repo/some/project \
             -m "Initial import"
Adding         mytree/foo.c
Adding         mytree/bar.c
Adding         mytree/subdir
Adding         mytree/subdir/quux.h

Committed revision 1.
$

The previous example copied the contents of the local directory mytree into the directory some/project in the repository. Note that you didn't have to create that new directory first—svn import does that for you. Immediately after the commit, you can see your data in the repository:

$ svn list http://svn.example.com/svn/repo/some/project
bar.c
foo.c
subdir/
$

Note that after the import is finished, the original local directory is not converted into a working copy. To begin working on that data in a versioned fashion, you still need to create a fresh working copy of that tree.

Note: if you are on the same machine as the Subversion repository you can use the file:// specifier with a path rather than the https:// with a URL specifier.

Server.Mappath in C# classlibrary

You can get the base path by using the following code and append your needed path with that.

string  path = System.AppDomain.CurrentDomain.BaseDirectory;

How to wrap text in textview in Android

This should fix your problem: android:layout_weight="1".

Add objects to an array of objects in Powershell

To append to an array, just use the += operator.

$Target += $TargetObject

Also, you need to declare $Target = @() before your loop because otherwise, it will empty the array every loop.

Can someone explain how to implement the jQuery File Upload plugin?

I was looking for a similar functionality some days back and came across a good tutorial on tutorialzine. Here is an working example. Complete tutorial can be found here.

Simple form to hold the file upload dialogue:

<form id="upload" method="post" action="upload.php" enctype="multipart/form-data">
  <input type="file" name="uploadctl" multiple />
  <ul id="fileList">
    <!-- The file list will be shown here -->
  </ul>
</form>

And here is the jQuery code to upload the files:

$('#upload').fileupload({

  // This function is called when a file is added to the queue
  add: function (e, data) {
    //This area will contain file list and progress information.
    var tpl = $('<li class="working">'+
                '<input type="text" value="0" data-width="48" data-height="48" data-fgColor="#0788a5" data-readOnly="1" data-bgColor="#3e4043" />'+
                '<p></p><span></span></li>' );

    // Append the file name and file size
    tpl.find('p').text(data.files[0].name)
                 .append('<i>' + formatFileSize(data.files[0].size) + '</i>');

    // Add the HTML to the UL element
    data.context = tpl.appendTo(ul);

    // Initialize the knob plugin. This part can be ignored, if you are showing progress in some other way.
    tpl.find('input').knob();

    // Listen for clicks on the cancel icon
    tpl.find('span').click(function(){
      if(tpl.hasClass('working')){
              jqXHR.abort();
      }
      tpl.fadeOut(function(){
              tpl.remove();
      });
    });

    // Automatically upload the file once it is added to the queue
    var jqXHR = data.submit();
  },
  progress: function(e, data){

        // Calculate the completion percentage of the upload
        var progress = parseInt(data.loaded / data.total * 100, 10);

        // Update the hidden input field and trigger a change
        // so that the jQuery knob plugin knows to update the dial
        data.context.find('input').val(progress).change();

        if(progress == 100){
            data.context.removeClass('working');
        }
    }
});
//Helper function for calculation of progress
function formatFileSize(bytes) {
    if (typeof bytes !== 'number') {
        return '';
    }

    if (bytes >= 1000000000) {
        return (bytes / 1000000000).toFixed(2) + ' GB';
    }

    if (bytes >= 1000000) {
        return (bytes / 1000000).toFixed(2) + ' MB';
    }
    return (bytes / 1000).toFixed(2) + ' KB';
}

And here is the PHP code sample to process the data:

if($_POST) {
    $allowed = array('jpg', 'jpeg');

    if(isset($_FILES['uploadctl']) && $_FILES['uploadctl']['error'] == 0){

        $extension = pathinfo($_FILES['uploadctl']['name'], PATHINFO_EXTENSION);

        if(!in_array(strtolower($extension), $allowed)){
            echo '{"status":"error"}';
            exit;
        }

        if(move_uploaded_file($_FILES['uploadctl']['tmp_name'], "/yourpath/." . $extension)){
            echo '{"status":"success"}';
            exit;
        }
        echo '{"status":"error"}';
    }
    exit();
}

The above code can be added to any existing form. This program automatically uploads images, once they are added. This functionality can be changed and you can submit the image, while you are submitting your existing form.

Updated my answer with actual code. All credits to original author of the code.

Source: http://tutorialzine.com/2013/05/mini-ajax-file-upload-form/

Better way to check variable for null or empty string?

empty() used to work for this, but the behavior of empty() has changed several times. As always, the php docs are always the best source for exact behavior and the comments on those pages usually provide a good history of the changes over time. If you want to check for a lack of object properties, a very defensive method at the moment is:

if (is_object($theObject) && (count(get_object_vars($theObject)) > 0)) {

parseInt with jQuery

var test = parseInt($("#testid").val(), 10);

You have to tell it you want the value of the input you are targeting.

And also, always provide the second argument (radix) to parseInt. It tries to be too clever and autodetect it if not provided and can lead to unexpected results.

Providing 10 assumes you are wanting a base 10 number.

How to get history on react-router v4?

Basing on this answer if you need history object only in order to navigate to other component:

import { useHistory } from "react-router-dom";

function HomeButton() {
  const history = useHistory();

  function handleClick() {
    history.push("/home");
  }

  return (
    <button type="button" onClick={handleClick}>
      Go home
    </button>
  );
}

Service has zero application (non-infrastructure) endpoints

To prepare the configration for WCF is hard, and sometimes a service type definition go unnoticed.

I wrote only the namespace in the service tag, so I got the same error.

<service name="ServiceNameSpace">

Do not forget, the service tag needs a fully-qualified service class name.

<service name="ServiceNameSpace.ServiceClass">

For the other folks who are like me.

How to check null objects in jQuery

What about using "undefined"?

if (value != undefined){ // do stuff } 

Change tab bar item selected color in a storyboard

You can also set selected image bar tint color by key path:

enter image description here

Hope this will help you!! Thanks

How to show DatePickerDialog on Button click?

enter image description here

I. In your build.gradle add latest appcompat library, at the time 24.2.1

dependencies {  
    compile 'com.android.support:appcompat-v7:X.X.X' 
    // where X.X.X version
}

II. Make your activity extend android.support.v7.app.AppCompatActivity and implement the DatePickerDialog.OnDateSetListener interface.

public class MainActivity extends AppCompatActivity  
    implements DatePickerDialog.OnDateSetListener {

III. Create your DatePickerDialog setting a context, the implementation of the listener and the start year, month and day of the date picker.

DatePickerDialog datePickerDialog = new DatePickerDialog(  
    context, MainActivity.this, startYear, starthMonth, startDay);

IV. Show your dialog on the click event listener of your button

((Button) findViewById(R.id.myButton))
    .setOnClickListener(new OnClickListener() {
    @Override
    public void onClick(View v) {
        datePickerDialog.show();
    }
});

C++ compile time error: expected identifier before numeric constant

Initializations with (...) in the class body is not allowed. Use {..} or = .... Unfortunately since the respective constructor is explicit and vector has an initializer list constructor, you need a functional cast to call the wanted constructor

vector<string> name = decltype(name)(5);
vector<int> val = decltype(val)(5,0);

As an alternative you can use constructor initializer lists

 Attribute():name(5), val(5, 0) {}

How to find/identify large commits in git history?

Step 1 Write all file SHA1s to a text file:

git rev-list --objects --all | sort -k 2 > allfileshas.txt

Step 2 Sort the blobs from biggest to smallest and write results to text file:

git gc && git verify-pack -v .git/objects/pack/pack-*.idx | egrep "^\w+ blob\W+[0-9]+ [0-9]+ [0-9]+$" | sort -k 3 -n -r > bigobjects.txt

Step 3a Combine both text files to get file name/sha1/size information:

for SHA in `cut -f 1 -d\  < bigobjects.txt`; do
echo $(grep $SHA bigobjects.txt) $(grep $SHA allfileshas.txt) | awk '{print $1,$3,$7}' >> bigtosmall.txt
done;

Step 3b If you have file names or path names containing spaces try this variation of Step 3a. It uses cut instead of awk to get the desired columns incl. spaces from column 7 to end of line:

for SHA in `cut -f 1 -d\  < bigobjects.txt`; do
echo $(grep $SHA bigobjects.txt) $(grep $SHA allfileshas.txt) | cut -d ' ' -f'1,3,7-' >> bigtosmall.txt
done;

Now you can look at the file bigtosmall.txt in order to decide which files you want to remove from your Git history.

Step 4 To perform the removal (note this part is slow since it's going to examine every commit in your history for data about the file you identified):

git filter-branch --tree-filter 'rm -f myLargeFile.log' HEAD

Source

Steps 1-3a were copied from Finding and Purging Big Files From Git History

EDIT

The article was deleted sometime in the second half of 2017, but an archived copy of it can still be accessed using the Wayback Machine.

Download File to server from URL

Simple solution:

<?php 
exec('wget http://someurl/file.zip');

Font-awesome, input type 'submit'

Well, technically it's not possible to get :before and :after pseudo elements work on input elements

From W3C:

12.1 The :before and :after pseudo-elements

Authors specify the style and location of generated content with the :before and :after pseudo-elements. As their names indicate, the :before and :after pseudo-elements specify the location of content before and after an element's document tree content. The 'content' property, in conjunction with these pseudo-elements, specifies what is inserted.


So I had a project where I had submit buttons in the form of input tags and for some reason the other developers restricted me to use <button> tags instead of the usual input submit buttons, so I came up with another solution, of wrapping the buttons inside a span set to position: relative; and then absolutely positioning the icon using :after pseudo.

Note: The demo fiddle uses the content code for FontAwesome 3.2.1 so you may need to change the value of content property accordingly.

HTML

<span><input type="submit" value="Send" class="btn btn-default" /></span>

CSS

input[type="submit"] {
    margin: 10px;
    padding-right: 30px;
}

span {
    position: relative;
}

span:after {
    font-family: FontAwesome;
    content: "\f004"; /* Value may need to be changed in newer version of font awesome*/
    font-size: 13px;
    position: absolute;
    right: 20px;
    top: 1px;
    pointer-events: none;
}

Demo

Now here everything is self explanatory here, about one property i.e pointer-events: none;, I've used that because on hovering over the :after pseudo generated content, your button won't click, so using the value of none will force the click action to go pass through that content.

From Mozilla Developer Network :

In addition to indicating that the element is not the target of mouse events, the value none instructs the mouse event to go "through" the element and target whatever is "underneath" that element instead.

Hover the heart font/icon Demo and see what happens if you DON'T use pointer-events: none;

Is there a way to provide named parameters in a function call in JavaScript?

There is another way. If you're passing an object by reference, that object's properties will appear in the function's local scope. I know this works for Safari (haven't checked other browsers) and I don't know if this feature has a name, but the below example illustrates its use.

Although in practice I don't think that this offers any functional value beyond the technique you're already using, it's a little cleaner semantically. And it still requires passing a object reference or an object literal.

function sum({ a:a, b:b}) {
    console.log(a+'+'+b);
    if(a==undefined) a=0;
    if(b==undefined) b=0;
    return (a+b);
}

// will work (returns 9 and 3 respectively)
console.log(sum({a:4,b:5}));
console.log(sum({a:3}));

// will not work (returns 0)
console.log(sum(4,5));
console.log(sum(4));

What is Node.js' Connect, Express and "middleware"?

node.js

Node.js is a javascript motor for the server side.
In addition to all the js capabilities, it includes networking capabilities (like HTTP), and access to the file system.
This is different from client-side js where the networking tasks are monopolized by the browser, and access to the file system is forbidden for security reasons.

node.js as a web server: express

Something that runs in the server, understands HTTP and can access files sounds like a web server. But it isn't one.
To make node.js behave like a web server one has to program it: handle the incoming HTTP requests and provide the appropriate responses.
This is what Express does: it's the implementation of a web server in js.
Thus, implementing a web site is like configuring Express routes, and programming the site's specific features.

Middleware and Connect

Serving pages involves a number of tasks. Many of those tasks are well known and very common, so node's Connect module (one of the many modules available to run under node) implements those tasks.
See the current impressing offering:

  • logger request logger with custom format support
  • csrf Cross-site request forgery protection
  • compress Gzip compression middleware
  • basicAuth basic http authentication
  • bodyParser extensible request body parser
  • json application/json parser
  • urlencoded application/x-www-form-urlencoded parser
  • multipart multipart/form-data parser
  • timeout request timeouts
  • cookieParser cookie parser
  • session session management support with bundled MemoryStore
  • cookieSession cookie-based session support
  • methodOverride faux HTTP method support
  • responseTime calculates response-time and exposes via X-Response-Time
  • staticCache memory cache layer for the static() middleware
  • static streaming static file server supporting Range and more
  • directory directory listing middleware
  • vhost virtual host sub-domain mapping middleware
  • favicon efficient favicon server (with default icon)
  • limit limit the bytesize of request bodies
  • query automatic querystring parser, populating req.query
  • errorHandler flexible error handler

Connect is the framework and through it you can pick the (sub)modules you need.
The Contrib Middleware page enumerates a long list of additional middlewares.
Express itself comes with the most common Connect middlewares.

What to do?

Install node.js.
Node comes with npm, the node package manager.
The command npm install -g express will download and install express globally (check the express guide).
Running express foo in a command line (not in node) will create a ready-to-run application named foo. Change to its (newly created) directory and run it with node with the command node <appname>, then open http://localhost:3000 and see. Now you are in.

How to write a unit test for a Spring Boot Controller endpoint

The new testing improvements that debuted in Spring Boot 1.4.M2 can help reduce the amount of code you need to write situation such as these.

The test would look like so:

import static org.springframework.test.web.servlet.request.MockMvcRequestB??uilders.get; 
import static org.springframework.test.web.servlet.result.MockMvcResultMat??chers.content; 
import static org.springframework.test.web.servlet.result.MockMvcResultMat??chers.status;

    @RunWith(SpringRunner.class)
    @WebMvcTest(HelloWorld.class)
    public class UserVehicleControllerTests {

        @Autowired
        private MockMvc mockMvc;

        @Test
        public void testSayHelloWorld() throws Exception {
            this.mockMvc.perform(get("/").accept(MediaType.parseMediaType("application/json;charset=UTF-8")))
                    .andExpect(status().isOk())
                    .andExpect(content().contentType("application/json"));

        }

    }

See this blog post for more details as well as the documentation

Exporting to .xlsx using Microsoft.Office.Interop.Excel SaveAs Error

    public static void ExportToExcel(DataGridView dgView)
    {
        Microsoft.Office.Interop.Excel.Application excelApp = null;
        try
        {
            // instantiating the excel application class
            excelApp = new Microsoft.Office.Interop.Excel.Application();
            Microsoft.Office.Interop.Excel.Workbook currentWorkbook = excelApp.Workbooks.Add(Type.Missing);
            Microsoft.Office.Interop.Excel.Worksheet currentWorksheet = (Microsoft.Office.Interop.Excel.Worksheet)currentWorkbook.ActiveSheet;
            currentWorksheet.Columns.ColumnWidth = 18;


            if (dgView.Rows.Count > 0)
            {
                currentWorksheet.Cells[1, 1] = DateTime.Now.ToString("s");
                int i = 1;
                foreach (DataGridViewColumn dgviewColumn in dgView.Columns)
                {
                    // Excel work sheet indexing starts with 1
                    currentWorksheet.Cells[2, i] = dgviewColumn.Name;
                    ++i;
                }
                Microsoft.Office.Interop.Excel.Range headerColumnRange = currentWorksheet.get_Range("A2", "G2");
                headerColumnRange.Font.Bold = true;
                headerColumnRange.Font.Color = 0xFF0000;
                //headerColumnRange.EntireColumn.AutoFit();
                int rowIndex = 0;
                for (rowIndex = 0; rowIndex < dgView.Rows.Count; rowIndex++)
                {
                    DataGridViewRow dgRow = dgView.Rows[rowIndex];
                    for (int cellIndex = 0; cellIndex < dgRow.Cells.Count; cellIndex++)
                    {
                        currentWorksheet.Cells[rowIndex + 3, cellIndex + 1] = dgRow.Cells[cellIndex].Value;
                    }
                }
                Microsoft.Office.Interop.Excel.Range fullTextRange = currentWorksheet.get_Range("A1", "G" + (rowIndex + 1).ToString());
                fullTextRange.WrapText = true;
                fullTextRange.HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignLeft;
            }
            else
            {
                string timeStamp = DateTime.Now.ToString("s");
                timeStamp = timeStamp.Replace(':', '-');
                timeStamp = timeStamp.Replace("T", "__");
                currentWorksheet.Cells[1, 1] = timeStamp;
                currentWorksheet.Cells[1, 2] = "No error occured";
            }
            using (SaveFileDialog exportSaveFileDialog = new SaveFileDialog())
            {
                exportSaveFileDialog.Title = "Select Excel File";
                exportSaveFileDialog.Filter = "Microsoft Office Excel Workbook(*.xlsx)|*.xlsx";

                if (DialogResult.OK == exportSaveFileDialog.ShowDialog())
                {
                    string fullFileName = exportSaveFileDialog.FileName;
                   // currentWorkbook.SaveCopyAs(fullFileName);
                    // indicating that we already saved the workbook, otherwise call to Quit() will pop up
                    // the save file dialogue box

                    currentWorkbook.SaveAs(fullFileName, Microsoft.Office.Interop.Excel.XlFileFormat.xlOpenXMLWorkbook, System.Reflection.Missing.Value, Missing.Value, false, false, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange, Microsoft.Office.Interop.Excel.XlSaveConflictResolution.xlUserResolution, true, Missing.Value, Missing.Value, Missing.Value);
                    currentWorkbook.Saved = true;
                    MessageBox.Show("Error memory exported successfully", "Exported to Excel", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message, "Exception", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
        finally
        {
            if (excelApp != null)
            {
                excelApp.Quit();
            }
        }



    }

DataAnnotations validation (Regular Expression) in asp.net mvc 4 - razor view

UPDATE 9 July 2012 - Looks like this is fixed in RTM.

  1. We already imply ^ and $ so you don't need to add them. (It doesn't appear to be a problem to include them, but you don't need them)
  2. This appears to be a bug in ASP.NET MVC 4/Preview/Beta. I've opened a bug

View source shows the following:

data-val-regex-pattern="([a-zA-Z0-9 .&amp;&#39;-]+)"                  <-- MVC 3
data-val-regex-pattern="([a-zA-Z0-9&#32;.&amp;amp;&amp;#39;-]+)"      <-- MVC 4/Beta

It looks like we're double encoding.

Escaping quotation marks in PHP

Use htmlspecialchars(). Then quote and less / greater than symbols don't break your HTML tags~

Execute curl command within a Python script

If you are not tweaking the curl command too much you can also go and call the curl command directly

import shlex
cmd = '''curl -X POST -d  '{"nw_src": "10.0.0.1/32", "nw_dst": "10.0.0.2/32", "nw_proto": "ICMP", "actions": "ALLOW", "priority": "10"}' http://localhost:8080/firewall/rules/0000000000000001'''
args = shlex.split(cmd)
process = subprocess.Popen(args, shell=False, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout, stderr = process.communicate()

Send values from one form to another form

I've worked on various winform projects and as the applications gets more complex (more dialogs and interactions between them) then i've started to use some eventing system to help me out, because management of opening and closing windows manually will be hard to maintain and develope further.

I've used CAB for my applications, it has an eventing system but it might be an overkill in your case :) You could write your own events for simpler applications

How to perform runtime type checking in Dart?

object.runtimeType returns the type of object

For example:

print("HELLO".runtimeType); //prints String
var x=0.0;
print(x.runtimeType); //prints double

How to get all count of mongoose model?

Using mongoose.js you can count documents,

  • count all
const count = await Schema.countDocuments();
  • count specific
const count = await Schema.countDocuments({ key: value });

implement addClass and removeClass functionality in angular2

If you want to due this in component.ts

HTML:

<button class="class1 class2" (click)="clicked($event)">Click me</button>

Component:

clicked(event) {
  event.target.classList.add('class3'); // To ADD
  event.target.classList.remove('class1'); // To Remove
  event.target.classList.contains('class2'); // To check
  event.target.classList.toggle('class4'); // To toggle
}

For more options, examples and browser compatibility visit this link.

Using a Python subprocess call to invoke a Python script

If 'somescript.py' isn't something you could normally execute directly from the command line (I.e., $: somescript.py works), then you can't call it directly using call.

Remember that the way Popen works is that the first argument is the program that it executes, and the rest are the arguments passed to that program. In this case, the program is actually python, not your script. So the following will work as you expect:

subprocess.call(['python', 'somescript.py', somescript_arg1, somescript_val1,...]).

This correctly calls the Python interpreter and tells it to execute your script with the given arguments.

Note that this is different from the above suggestion:

subprocess.call(['python somescript.py'])

That will try to execute the program called python somscript.py, which clearly doesn't exist.

call('python somescript.py', shell=True)

Will also work, but using strings as input to call is not cross platform, is dangerous if you aren't the one building the string, and should generally be avoided if at all possible.

gnuplot plotting multiple line graphs

I think your problem is your version numbers. Try making 8.1 --> 8.01, and so forth. That should put the points in the right order.

Alternatively, you could plot using X, where X is the column number you want, instead of using 1:X. That will plot those values on the y axis and integers on the x axis. Try:

plot "ls.dat" using 2 title 'Removed' with lines, \
     "ls.dat" using 3 title 'Added' with lines, \
     "ls.dat" using 4 title 'Modified' with lines

VBA copy rows that meet criteria to another sheet

After formatting the previous answer to my own code, I have found an efficient way to copy all necessary data if you are attempting to paste the values returned via AutoFilter to a separate sheet.

With .Range("A1:A" & LastRow)
    .Autofilter Field:=1, Criteria1:="=*" & strSearch & "*"
    .Offset(1,0).SpecialCells(xlCellTypeVisible).Cells.Copy
    Sheets("Sheet2").activate
    DestinationRange.PasteSpecial
End With

In this block, the AutoFilter finds all of the rows that contain the value of strSearch and filters out all of the other values. It then copies the cells (using offset in case there is a header), opens the destination sheet and pastes the values to the specified range on the destination sheet.

How do I use Wget to download all images into a single folder, from a URL?

I wrote a shellscript that solves this problem for multiple websites: https://github.com/eduardschaeli/wget-image-scraper

(Scrapes images from a list of urls with wget)

Get the current year in JavaScript

You can simply use javascript like this. Otherwise you can use momentJs Plugin which helps in large application.

new Date().getDate()          // Get the day as a number (1-31)
new Date().getDay()           // Get the weekday as a number (0-6)
new Date().getFullYear()      // Get the four digit year (yyyy)
new Date().getHours()         // Get the hour (0-23)
new Date().getMilliseconds()  // Get the milliseconds (0-999)
new Date().getMinutes()       // Get the minutes (0-59)
new Date().getMonth()         // Get the month (0-11)
new Date().getSeconds()       // Get the seconds (0-59)
new Date().getTime()          // Get the time (milliseconds since January 1, 1970)

_x000D_
_x000D_
function generate(type,element)_x000D_
{_x000D_
 var value = "";_x000D_
 var date = new Date();_x000D_
 switch (type) {_x000D_
  case "Date":_x000D_
   value = date.getDate();  // Get the day as a number (1-31)_x000D_
   break;_x000D_
  case "Day":_x000D_
   value = date.getDay();  // Get the weekday as a number (0-6)_x000D_
   break;_x000D_
  case "FullYear":_x000D_
   value = date.getFullYear(); // Get the four digit year (yyyy)_x000D_
   break;_x000D_
  case "Hours":_x000D_
   value = date.getHours(); // Get the hour (0-23)_x000D_
   break;_x000D_
  case "Milliseconds":_x000D_
   value = date.getMilliseconds(); // Get the milliseconds (0-999)_x000D_
   break;_x000D_
  case "Minutes":_x000D_
   value = date.getMinutes();     // Get the minutes (0-59)_x000D_
   break;_x000D_
  case "Month":_x000D_
   value = date.getMonth(); // Get the month (0-11)_x000D_
   break;_x000D_
  case "Seconds":_x000D_
   value = date.getSeconds(); // Get the seconds (0-59)_x000D_
   break;_x000D_
  case "Time":_x000D_
   value = date.getTime();  // Get the time (milliseconds since January 1, 1970)_x000D_
   break;_x000D_
 }_x000D_
_x000D_
 $(element).siblings('span').text(value);_x000D_
}
_x000D_
li{_x000D_
  list-style-type: none;_x000D_
  padding: 5px;_x000D_
}_x000D_
_x000D_
button{_x000D_
  width: 150px;_x000D_
}_x000D_
_x000D_
span{_x000D_
  margin-left: 100px;_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
_x000D_
_x000D_
<ul>_x000D_
 <li>_x000D_
  <button type="button" onclick="generate('Date',this)">Get Date</button>_x000D_
  <span></span>_x000D_
 </li>_x000D_
 <li>_x000D_
  <button type="button" onclick="generate('Day',this)">Get Day</button>_x000D_
  <span></span>_x000D_
 </li>_x000D_
 <li>_x000D_
  <button type="button" onclick="generate('FullYear',this)">Get Full Year</button>_x000D_
  <span></span>_x000D_
 </li>_x000D_
 <li>_x000D_
  <button type="button" onclick="generate('Hours',this)">Get Hours</button>_x000D_
  <span></span>_x000D_
 </li>_x000D_
 <li>_x000D_
  <button type="button" onclick="generate('Milliseconds',this)">Get Milliseconds</button>_x000D_
  <span></span>_x000D_
 </li>_x000D_
_x000D_
 <li>_x000D_
  <button type="button" onclick="generate('Minutes',this)">Get Minutes</button>_x000D_
  <span></span>_x000D_
 </li>_x000D_
 <li>_x000D_
  <button type="button" onclick="generate('Month',this)">Get Month</button>_x000D_
  <span></span>_x000D_
 </li>_x000D_
 <li>_x000D_
  <button type="button" onclick="generate('Seconds',this)">Get Seconds</button>_x000D_
  <span></span>_x000D_
 </li>_x000D_
 <li>_x000D_
  <button type="button" onclick="generate('Time',this)">Get Time</button>_x000D_
  <span></span>_x000D_
 </li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

Query to select data between two dates with the format m/d/yyyy

DateTime dt1 = this.dateTimePicker1.Value.Date;
DateTime dt2 = this.dateTimePicker2.Value.Date.AddMinutes(1440);
String query = "SELECT * FROM student WHERE sdate BETWEEN '" + dt1 + "' AND '" + dt2 + "'";

Why do we need C Unions?

Low level system programming is a reasonable example.

IIRC, I've used unions to breakdown hardware registers into the component bits. So, you can access an 8-bit register (as it was, in the day I did this ;-) into the component bits.

(I forget the exact syntax but...) This structure would allow a control register to be accessed as a control_byte or via the individual bits. It would be important to ensure the bits map on to the correct register bits for a given endianness.

typedef union {
    unsigned char control_byte;
    struct {
        unsigned int nibble  : 4;
        unsigned int nmi     : 1;
        unsigned int enabled : 1;
        unsigned int fired   : 1;
        unsigned int control : 1;
    };
} ControlRegister;

Convert Mongoose docs to json

You may also try mongoosejs's lean() :

UserModel.find().lean().exec(function (err, users) {
    return res.end(JSON.stringify(users));
}

How to Add Date Picker To VBA UserForm

In Access 2013. Drop a "Text Box" control onto your form. On the Property Sheet for the control under the Format tab find the Format property. Set this to one of the date format options. Job's done.

HTML checkbox onclick called in Javascript

You can also extract the event code from the HTML, like this :

<input type="checkbox" id="check_all_1" name="check_all_1" title="Select All" />
<label for="check_all_1">Select All</label>

<script>
function selectAll(frmElement, chkElement) {
    // ...
}
document.getElementById("check_all_1").onclick = function() {
    selectAll(document.wizard_form, this);
}
</script>

In Flask, What is request.args and how is it used?

@martinho as a newbie using Flask and Python myself, I think the previous answers here took for granted that you had a good understanding of the fundamentals. In case you or other viewers don't know the fundamentals, I'll give more context to understand the answer...

... the request.args is bringing a "dictionary" object for you. The "dictionary" object is similar to other collection-type of objects in Python, in that it can store many elements in one single object. Therefore the answer to your question

And how many parameters request.args.get() takes.

It will take only one object, a "dictionary" type of object (as stated in the previous answers). This "dictionary" object, however, can have as many elements as needed... (dictionaries have paired elements called Key, Value).

Other collection-type of objects besides "dictionaries", would be "tuple", and "list"... you can run a google search on those and "data structures" in order to learn other Python fundamentals. This answer is based Python; I don't have an idea if the same applies to other programming languages.

how to display a div triggered by onclick event

function showstuff(boxid){
   document.getElementById(boxid).style.visibility="visible";
}
<button onclick="showstuff('id_to_show');" />

This will help you, I think.

How to add java plugin for Firefox on Linux?

you should add plug in to your local setting of firefox in your user home

 vladimir@shinsengumi ~/.mozilla/plugins $ pwd
 /home/vladimir/.mozilla/plugins 
 vladimir@shinsengumi ~/.mozilla/plugins $ ls -ltr
 lrwxrwxrwx 1 vladimir vladimir 60 Jan  1 23:06 libnpjp2.so -> /home/vladimir/Install/jdk1.6.0_32/jre/lib/amd64/libnpjp2.so

How to add and get Header values in WebApi

You need to get the HttpRequestMessage from the current OperationContext. Using OperationContext you can do it like so

OperationContext context = OperationContext.Current;
MessageProperties messageProperties = context.IncomingMessageProperties;

HttpRequestMessageProperty requestProperty = messageProperties[HttpRequestMessageProperty.Name] as HttpRequestMessageProperty;

string customHeaderValue = requestProperty.Headers["Custom"];

Using Linq to get the last N elements of a collection?

If using a third-party library is an option, MoreLinq defines TakeLast() which does exactly this.

How to show a GUI message box from a bash script in linux?

if nothing else is present. you can launch an xterm and echo in it, like this:

 xterm -e bash -c 'echo "this is the message";echo;echo -n "press enter to continue "; stty sane -echo;answer=$( while ! head -c 1;do true ;done);'

Android Studio SDK location

create a new folder in your android studio parent directory folder. Name it sdk or whatever you want. Select that folder from the drop down list when asked. Thats what solves it for me.

Unknown version of Tomcat was specified in Eclipse

It may be due to the access of the tomcat installation path(C:\Program Files\Apache Software Foundation\Tomcat 9.0) wasn't available with the current user.

Getting a Request.Headers value

Firstly you don't do this in your view. You do it in the controller and return a view model to the view so that the view doesn't need to care about custom HTTP headers but just displaying data on the view model:

public ActionResult Index()
{
    var xyzComponent = Request.Headers["xyzComponent"];
    var model = new MyModel 
    {
        IsCustomHeaderSet = (xyzComponent != null)
    }
    return View(model);
}

Error in Python IOError: [Errno 2] No such file or directory: 'data.csv'

It's looking for the file in the current directory.

First, go to that directory

cd /users/gcameron/Desktop/map

And then try to run it

python colorize_svg.py

Is there an equivalent to background-size: cover and contain for image elements?

We can take ZOOM approach. We can assume that max 30% (or more upto 100%) can be the zooming effect if aspect image height OR width is less than the desired height OR width. We can hide the rest not needed area with overflow: hidden.

.image-container {
  width: 200px;
  height: 150px;
  overflow: hidden;
}
.stage-image-gallery a img {
  max-height: 130%;
  max-width: 130%;
  position: relative;
  top: 50%;
  left: 50%;
  transform: translateX(-50%) translateY(-50%);
}

This will adjust images with different width OR height.

How to implement __iter__(self) for a container object (Python)

usually __iter__() just return self if you have already define the next() method (generator object):

here is a Dummy example of a generator :

class Test(object):

    def __init__(self, data):
       self.data = data

    def next(self):
        if not self.data:
           raise StopIteration
        return self.data.pop()

    def __iter__(self):
        return self

but __iter__() can also be used like this: http://mail.python.org/pipermail/tutor/2006-January/044455.html

Android Activity without ActionBar

Considering everyone is posting older ways of hiding the ActionBar here is the proper way of implementing it within styles for AppCompat support library. Which I highly suggest moving toward if you haven't already.

Simply removing the ActionBar

<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
</style>

If you are using the appcompat support libraries, this is the easiest and recommended way of hiding the ActionBar to make full screen or start implementing to toolbar within your layouts.

<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
    <!-- Your Toolbar Color-->
    <item name="colorPrimary">@color/primary</item>

    <!-- colorPrimaryDark is used for the status bar -->
    <item name="colorPrimaryDark">@color/primary_dark</item>

    <!-- colorAccent is used as the default value for colorControlActivated,
     which is used to tint widgets -->
    <item name="colorAccent">@color/accent</item>

    <!-- You can also set colorControlNormal, colorControlActivated
     colorControlHighlight, and colorSwitchThumbNormal. -->
</style>

Then to change your toolbar color

<android.support.v7.widget.Toolbar
    android:id=”@+id/my_awesome_toolbar”
    android:layout_height=”wrap_content”
    android:layout_width=”match_parent”
    android:minHeight=”?attr/actionBarSize”
    android:background=”?attr/primary” />

Last note: Your Activity class should extend AppCompatActivity

public class MainActivity extends AppCompatActivity {

<!--Activity Items -->

}

Check if a div exists with jquery

If you are simply checking for the existence of an ID, there is no need to go into jQuery, you could simply:

if(document.getElementById("yourid") !== null)
{
}

getElementById returns null if it can't be found.

Reference.

If however you plan to use the jQuery object later i'd suggest:

$(document).ready(function() {
    var $myDiv = $('#DivID');

    if ( $myDiv.length){
        //you can now reuse  $myDiv here, without having to select it again.
    }


});

A selector always returns a jQuery object, so there shouldn't be a need to check against null (I'd be interested if there is an edge case where you need to check for null - but I don't think there is).

If the selector doesn't find anything then length === 0 which is "falsy" (when converted to bool its false). So if it finds something then it should be "truthy" - so you don't need to check for > 0. Just for it's "truthyness"

Convert int to string?

string s = "" + 2;

and you can do nice things like:

string s = 2 + 2 + "you" 

The result will be:

"4 you"

What are some examples of commonly used practices for naming git branches?

Why does it take three branches/merges for every task? Can you explain more about that?

If you use a bug tracking system you can use the bug number as part of the branch name. This will keep the branch names unique, and you can prefix them with a short and descriptive word or two to keep them human readable, like "ResizeWindow-43523". It also helps make things easier when you go to clean up branches, since you can look up the associated bug. This is how I usually name my branches.

Since these branches are eventually getting merged back into master, you should be safe deleting them after you merge. Unless you're merging with --squash, the entire history of the branch will still exist should you ever need it.

ElasticSearch, Sphinx, Lucene, Solr, Xapian. Which fits for which usage?

I have used Sphinx, Solr and Elasticsearch. Solr/Elasticsearch are built on top of Lucene. It adds many common functionality: web server api, faceting, caching, etc.

If you want to just have a simple full text search setup, Sphinx is a better choice.

If you want to customize your search at all, Elasticsearch and Solr are the better choices. They are very extensible: you can write your own plugins to adjust result scoring.

Some example usages:

  • Sphinx: craigslist.org
  • Solr: Cnet, Netflix, digg.com
  • Elasticsearch: Foursquare, Github

Open new popup window without address bars in firefox & IE

Workaround - Open a modal popup window and embed the external URL as an iframe.

Referencing Row Number in R

This is probably the simplest way:

data$rownumber = 1:dim(data)[1]

It's probably worth noting that if you want to select a row by its row index, you can do this with simple bracket notation

data[3,]

vs.

data[data$rownumber==3,]

So I'm not really sure what this new column accomplishes.

Android Whatsapp/Chat Examples

Check out yowsup
https://github.com/tgalal/yowsup

Yowsup is a python library that allows you to do all the previous in your own app. Yowsup allows you to login and use the Whatsapp service and provides you with all capabilities of an official Whatsapp client, allowing you to create a full-fledged custom Whatsapp client.

A solid example of Yowsup's usage is Wazapp. Wazapp is full featured Whatsapp client that is being used by hundreds of thousands of people around the world. Yowsup is born out of the Wazapp project. Before becoming a separate project, it was only the engine powering Wazapp. Now that it matured enough, it was separated into a separate project, allowing anyone to build their own Whatsapp client on top of it. Having such a popular client as Wazapp, built on Yowsup, helped bring the project into a much advanced, stable and mature level, and ensures its continuous development and maintaince.

Yowsup also comes with a cross platform command-line frontend called yowsup-cli. yowsup-cli allows you to jump into connecting and using Whatsapp service directly from command line.

Installing NumPy and SciPy on 64-bit Windows (with Pip)

Best solution for this is to download and install VCforPython2.7 from https://www.microsoft.com/en-us/download/details.aspx?id=44266

Then try pip install numpy

Classes cannot be accessed from outside package

Let me guess

Your initial declaration of class PUBLICClass was not public, then you made it `Public', can you try to clean and rebuild your project ?

Cannot refer to a non-final variable inside an inner class defined in a different method

You can only access final variables from the containing class when using an anonymous class. Therefore you need to declare the variables being used final (which is not an option for you since you are changing lastPrice and price), or don't use an anonymous class.

So your options are to create an actual inner class, in which you can pass in the variables and use them in a normal fashion

or:

There is a quick (and in my opinion ugly) hack for your lastPrice and price variable which is to declare it like so

final double lastPrice[1];
final double price[1];

and in your anonymous class you can set the value like this

price[0] = priceObject.getNextPrice(lastPrice[0]);
System.out.println();
lastPrice[0] = price[0];

How to center text vertically with a large font-awesome icon?

Simply define vertical-align property for the icon element:

div .icon {
   vertical-align: middle;
}

Rotating videos with FFmpeg

If you don't want to re-encode your video AND your player can handle rotation metadata you can just change the rotation in the metadata using ffmpeg:

ffmpeg -i input.m4v -map_metadata 0 -metadata:s:v rotate="90" -codec copy output.m4v

Add jars to a Spark Job - spark-submit

Other configurable Spark option relating to jars and classpath, in case of yarn as deploy mode are as follows
From the spark documentation,

spark.yarn.jars

List of libraries containing Spark code to distribute to YARN containers. By default, Spark on YARN will use Spark jars installed locally, but the Spark jars can also be in a world-readable location on HDFS. This allows YARN to cache it on nodes so that it doesn't need to be distributed each time an application runs. To point to jars on HDFS, for example, set this configuration to hdfs:///some/path. Globs are allowed.

spark.yarn.archive

An archive containing needed Spark jars for distribution to the YARN cache. If set, this configuration replaces spark.yarn.jars and the archive is used in all the application's containers. The archive should contain jar files in its root directory. Like with the previous option, the archive can also be hosted on HDFS to speed up file distribution.

Users can configure this parameter to specify their jars, which inturn gets included in Spark driver's classpath.

Javascript - Regex to validate date format

The suggested regex will not validate the date, only the pattern.

So 99.99.9999 will pass the regex.

You later specified that you only need to validate the pattern but I still think it is more useful to create a date object

_x000D_
_x000D_
function isDate(str) {    _x000D_
  var parms = str.split(/[\.\-\/]/);_x000D_
  var yyyy = parseInt(parms[2],10);_x000D_
  var mm   = parseInt(parms[1],10);_x000D_
  var dd   = parseInt(parms[0],10);_x000D_
  var date = new Date(yyyy,mm-1,dd,0,0,0,0);_x000D_
  return mm === (date.getMonth()+1) && dd === date.getDate() && yyyy === date.getFullYear();_x000D_
}_x000D_
var dates = [_x000D_
    "13-09-2011", _x000D_
    "13.09.2011",_x000D_
    "13/09/2011",_x000D_
    "08-08-1991",_x000D_
    "29/02/2011"_x000D_
]_x000D_
_x000D_
for (var i=0;i<dates.length;i++) {_x000D_
    console.log(dates[i]+':'+isDate(dates[i]));_x000D_
}    
_x000D_
_x000D_
_x000D_

subsetting a Python DataFrame

I've found that you can use any subset condition for a given column by wrapping it in []. For instance, you have a df with columns ['Product','Time', 'Year', 'Color']

And let's say you want to include products made before 2014. You could write,

df[df['Year'] < 2014]

To return all the rows where this is the case. You can add different conditions.

df[df['Year'] < 2014][df['Color' == 'Red']

Then just choose the columns you want as directed above. For instance, the product color and key for the df above,

df[df['Year'] < 2014][df['Color'] == 'Red'][['Product','Color']]

Set iframe content height to auto resize dynamically

Simple solution:

<iframe onload="this.style.height=this.contentWindow.document.body.scrollHeight + 'px';" ...></iframe>

This works when the iframe and parent window are in the same domain. It does not work when the two are in different domains.

How do you install Boost on MacOS?

In order to avoid troubles compiling third party libraries that need boost installed in your system, run this:

sudo port install boost +universal

What is the scope of variables in JavaScript?

Variables declared globally have a global scope. Variables declared within a function are scoped to that function, and shadow global variables of the same name.

(I'm sure there are many subtleties that real JavaScript programmers will be able to point out in other answers. In particular I came across this page about what exactly this means at any time. Hopefully this more introductory link is enough to get you started though.)

How to set root password to null

SET PASSWORD FOR 'root'@'localhost' = PASSWORD('');

NSURLConnection Using iOS Swift

Swift 3.0

AsynchonousRequest

let urlString = "http://heyhttp.org/me.json"
var request = URLRequest(url: URL(string: urlString)!)
let session = URLSession.shared

session.dataTask(with: request) {data, response, error in
  if error != nil {
    print(error!.localizedDescription)
    return
  }

  do {
    let jsonResult: NSDictionary? = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.mutableContainers) as? NSDictionary
    print("Synchronous\(jsonResult)")
  } catch {
    print(error.localizedDescription)
  }
}.resume()

Find all files in a folder

You can try with Directory.GetFiles and fix your pattern

 string[] files = Directory.GetFiles(@"c:\", "*.txt");

 foreach (string file in files)
 {
    File.Copy(file, "....");
 }

 Or Move

 foreach (string file in files)
 {
    File.Move(file, "....");
 }     

http://msdn.microsoft.com/en-us/library/wz42302f

Retrieving parameters from a URL

There is a nice library w3lib.url

from w3lib.url import url_query_parameter
url = "/abc?def=ghi"
print url_query_parameter(url, 'def')
ghi

Get the current URL with JavaScript?

Firstly check for page is loaded completely in

browser,window.location.toString();

window.location.href

then call a function which takes url, URL variable and prints on console,

$(window).load(function(){
   var url = window.location.href.toString();
   var URL = document.URL;
   var wayThreeUsingJQuery = $(location).attr('href');
   console.log(url);
   console.log(URL);
   console.log(wayThreeUsingJQuery );
});

Chmod 777 to a folder and all contents

You can give permission to folder and all its contents using option -R i.e Recursive permissions.

But I would suggest not to give 777 permission to all folder and it's all contents. You should give specific permission to each sub-folder in www directory folders.

Ideally, give 755 permission for security reasons to the web folder.

sudo chmod -R 755 /www/store

Each number has meaning in permission. Do not give full permission.

N   Description                      ls   binary    
0   No permissions at all            ---  000
1   Only execute                     --x  001
2   Only write                       -w-  010
3   Write and execute                -wx  011
4   Only read                        r--  100
5   Read and execute                 r-x  101
6   Read and write                   rw-  110
7   Read, write, and execute         rwx  111
  • First Number 7 - Read, write, and execute for the user.
  • Second Number 5 - Read and execute for the group.
  • Third Number 5 - Read and execute for others.

If your production web folder has multiple users, then you can set permissions and user groups accordingly.

More info :

  1. Understanding File Permissions: What Does “Chmod 777" Mean?
  2. What file permissions should I set on web root?
  3. Why shouldn't /var/www have chmod 777

How to get unique device hardware id in Android?

Please read this official blog entry on Google developer blog: http://android-developers.blogspot.be/2011/03/identifying-app-installations.html

Conclusion For the vast majority of applications, the requirement is to identify a particular installation, not a physical device. Fortunately, doing so is straightforward.

There are many good reasons for avoiding the attempt to identify a particular device. For those who want to try, the best approach is probably the use of ANDROID_ID on anything reasonably modern, with some fallback heuristics for legacy devices

.

What’s the best RESTful method to return total number of items in an object?

I prefer using HTTP Headers for this kind of contextual information.

For the total number of elements, I use the X-total-count header.
For links to next, previous page, etc. I use HTTP Link header:
http://www.w3.org/wiki/LinkHeader

Github does it the same way: https://developer.github.com/v3/#pagination

In my opinion, it's cleaner since it can be used also when you return content that doesn't support hyperlinks (i.e binaries, pictures).

Putting text in top left corner of matplotlib plot

One solution would be to use the plt.legend function, even if you don't want an actual legend. You can specify the placement of the legend box by using the loc keyterm. More information can be found at this website but I've also included an example showing how to place a legend:

ax.scatter(xa,ya, marker='o', s=20, c="lightgreen", alpha=0.9)
ax.scatter(xb,yb, marker='o', s=20, c="dodgerblue", alpha=0.9)
ax.scatter(xc,yc marker='o', s=20, c="firebrick", alpha=1.0)
ax.scatter(xd,xd,xd, marker='o', s=20, c="goldenrod", alpha=0.9)
line1 = Line2D(range(10), range(10), marker='o', color="goldenrod")
line2 = Line2D(range(10), range(10), marker='o',color="firebrick")
line3 = Line2D(range(10), range(10), marker='o',color="lightgreen")
line4 = Line2D(range(10), range(10), marker='o',color="dodgerblue")
plt.legend((line1,line2,line3, line4),('line1','line2', 'line3', 'line4'),numpoints=1, loc=2) 

Note that because loc=2, the legend is in the upper-left corner of the plot. And if the text overlaps with the plot, you can make it smaller by using legend.fontsize, which will then make the legend smaller.

Ignore parent padding

For image purpose you can do something like this

img {
    width: calc(100% + 20px); // twice the value of the parent's padding
    margin-left: -10px; // -1 * parent's padding
}

What is the easiest way to clear a database from the CLI with manage.py in Django?

I think Django docs explicitly mention that if the intent is to start from an empty DB again (which seems to be OP's intent), then just drop and re-create the database and re-run migrate (instead of using flush):

If you would rather start from an empty database and re-run all migrations, you should drop and recreate the database and then run migrate instead.

So for OP's case, we just need to:

  1. Drop the database from MySQL
  2. Recreate the database
  3. Run python manage.py migrate

Removing elements with Array.map in JavaScript

TLDR: Use map (returning undefined when needed) and then filter.


First, I believe that a map + filter function is useful since you don't want to repeat a computation in both. Swift originally called this function flatMap but then renamed it to compactMap.

For example, if we don't have a compactMap function, we might end up with computation defined twice:

  let array = [1, 2, 3, 4, 5, 6, 7, 8];
  let mapped = array
  .filter(x => {
    let computation = x / 2 + 1;
    let isIncluded = computation % 2 === 0;
    return isIncluded;
  })
  .map(x => {
    let computation = x / 2 + 1;
    return `${x} is included because ${computation} is even`
  })

  // Output: [2 is included because 2 is even, 6 is included because 4 is even]

Thus compactMap would be useful to reduce duplicate code.

A really simple way to do something similar to compactMap is to:

  1. Map on real values or undefined.
  2. Filter out all the undefined values.

This of course relies on you never needing to return undefined values as part of your original map function.

Example:

  let array = [1, 2, 3, 4, 5, 6, 7, 8];
  let mapped = array
  .map(x => {
    let computation = x / 2 + 1;
    let isIncluded = computation % 2 === 0;
    if (isIncluded) {
      return `${x} is included because ${computation} is even`
    } else {
      return undefined
    }
  })
  .filter(x => typeof x !== "undefined")

How to get a list of properties with a given attribute?

As far as I know, there isn't any better way in terms of working with Reflection library in a smarter way. However, you could use LINQ to make the code a bit nicer:

var props = from p in t.GetProperties()
            let attrs = p.GetCustomAttributes(typeof(MyAttribute), true)
            where attrs.Length != 0 select p;

// Do something with the properties in 'props'

I believe this helps you to structure the code in a more readable fashion.