Programs & Examples On #Ui helper

Angular2 RC5: Can't bind to 'Property X' since it isn't a known property of 'Child Component'

If you use the Angular CLI to create your components, let's say CarComponent, it attaches app to the selector name (i.e app-car) and this throws the above error when you reference the component in the parent view. Therefore you either have to change the selector name in the parent view to let's say <app-car></app-car> or change the selector in the CarComponent to selector: 'car'

jQuery UI Dialog - missing close icon

I was facing same issue , In my case JQuery-ui.js version was 1.10.3, After referring jquery-ui-1.12.1.min.js close button started to visible.

Opening Chrome From Command Line

Answering this for Ubuntu users for reference.

Run command google-chrome --app-url "http://localhost/"

Replace your desired URL in the parameter.

You can get more options like incognito mode etc. Run google-chrome --help to see the options.

Enumerations on PHP

based on: this gist

a base class for all enum:

abstract class Enum {
    protected $val;

    protected function __construct($arg) {
        $this->val = $arg;
    }

    public function __toString() {
        return $this->val;
    }

    public function __set($arg1, $arg2) {
        throw new Exception("enum does not have property");
    }

    public function __get($arg1) {
        throw new Exception("enum does not have property");
    }

    // not really needed
    public function __call($arg1, $arg2) {
        throw new Exception("enum does not have method");
    }

    // not really needed
    static public function __callStatic($arg1, $arg2) {
        throw new Exception("enum does not have static method");
    }
}

your enum:

final class MyEnum extends Enum {
    static public function val1() {
        return new self("val1");
    }

    static public function val2() {
        return new self("val2");
    }

    static public function val3() {
        return new self("val3");
    }
}

test it:

$a = MyEnum::val1();
echo "1.the enum value is '$a'\n";

function consumeMyEnum(MyEnum $arg) {
    return "2.the return value is '$arg'\n";
}

echo consumeMyEnum($a);
$version = explode(".", PHP_VERSION);
if ($version[0] >= 7) {
    try {
        echo consumeMyEnum("val1");
    } catch (TypeError $e) {
        echo "3.passing argument error happens (PHP 7.0 and above)\n";
    }
}

echo ($a == MyEnum::val1()) ? "4.same\n" : "4.different\n";
echo ($a == MyEnum::val2()) ? "5.same\n" : "5.different\n";

$b = MyEnum::val1();
echo ($a == $b)  ? "6.same\n" : "6.different\n";
echo ($a === $b) ? "7.same\n" : "7.different\n";

$c = MyEnum::val2();
echo ($a == $c)  ? "8.same\n" : "8.different\n";
echo ($a === $c) ? "9.same\n" : "9.different\n";

switch ($c) {
    case MyEnum::val1(): echo "10.case of 1st\n"; break;
    case MyEnum::val2(): echo "11.case of 2nd\n"; break;
    case MyEnum::val3(): echo "12.case of 3rd\n"; break;
}

try {
    $a->prop = 10;
} catch (Exception $e) {
    echo "13.set property error happens\n";
}

try {
    echo $a->prop;
} catch (Exception $e) {
    echo "14.get property error happens\n";
}

try {
    echo $a->meth();
} catch (Exception $e) {
    echo "15.method call error happens\n";
}

try {
    echo MyEnum::meth();
} catch (Exception $e) {
    echo "16.static method call error happens\n";
}

class Ordinary {}
echo $a instanceof MyEnum   ? "17.MyEnum instance\n"   : "17.not MyEnum instance\n";
echo $a instanceof Enum     ? "18.Enum instance\n"     : "18.not Enum instance\n";
echo $a instanceof Ordinary ? "19.Ordinary instance\n" : "19.not Ordinary instance\n";

try it online: sanbox

MySQL: How to allow remote connection to mysql

If your MySQL server process is listening on 127.0.0.1 or ::1 only then you will not be able to connect remotely. If you have a bind-address setting in /etc/my.cnf this might be the source of the problem.

You will also have to add privileges for a non-localhost user as well.

Best approach to real time http streaming to HTML5 video client

Take a look at JSMPEG project. There is a great idea implemented there — to decode MPEG in the browser using JavaScript. Bytes from encoder (FFMPEG, for example) can be transfered to browser using WebSockets or Flash, for example. If community will catch up, I think, it will be the best HTML5 live video streaming solution for now.

prevent property from being serialized in web API

According to the Web API documentation page JSON and XML Serialization in ASP.NET Web API to explicitly prevent serialization on a property you can either use [JsonIgnore] for the Json serializer or [IgnoreDataMember] for the default XML serializer.

However in testing I have noticed that [IgnoreDataMember] prevents serialization for both XML and Json requests, so I would recommend using that rather than decorating a property with multiple attributes.

C# string reference type?

The reference to the string is passed by value. There's a big difference between passing a reference by value and passing an object by reference. It's unfortunate that the word "reference" is used in both cases.

If you do pass the string reference by reference, it will work as you expect:

using System;

class Test
{
    public static void Main()
    {
        string test = "before passing";
        Console.WriteLine(test);
        TestI(ref test);
        Console.WriteLine(test);
    }

    public static void TestI(ref string test)
    {
        test = "after passing";
    }
}

Now you need to distinguish between making changes to the object which a reference refers to, and making a change to a variable (such as a parameter) to let it refer to a different object. We can't make changes to a string because strings are immutable, but we can demonstrate it with a StringBuilder instead:

using System;
using System.Text;

class Test
{
    public static void Main()
    {
        StringBuilder test = new StringBuilder();
        Console.WriteLine(test);
        TestI(test);
        Console.WriteLine(test);
    }

    public static void TestI(StringBuilder test)
    {
        // Note that we're not changing the value
        // of the "test" parameter - we're changing
        // the data in the object it's referring to
        test.Append("changing");
    }
}

See my article on parameter passing for more details.

insert data from one table to another in mysql

  INSERT INTO mt_magazine_subscription ( 
      magazine_subscription_id, 
      subscription_name, 
      magazine_id, 
      status ) 
  VALUES ( 
      (SELECT magazine_subscription_id, 
              subscription_name, 
              magazine_id,'1' as status
       FROM tbl_magazine_subscription 
       ORDER BY magazine_subscription_id ASC))

How do I make case-insensitive queries on Mongodb?

I just solved this problem a few hours ago.

var thename = 'Andrew'
db.collection.find({ $text: { $search: thename } });
  • Case sensitivity and diacritic sensitivity are set to false by default when doing queries this way.

You can even expand upon this by selecting on the fields you need from Andrew's user object by doing it this way:

db.collection.find({ $text: { $search: thename } }).select('age height weight');

Reference: https://docs.mongodb.org/manual/reference/operator/query/text/#text

Android: How to add R.raw to project?

Simply add a folder 'raw' to your res folder.

CMake error at CMakeLists.txt:30 (project): No CMAKE_C_COMPILER could be found

Just in case it helps any one like me in future:

I have had this issue for 24 hours now, on 3 different 64-bit machines(Win7 , Windows 8.1 VM and WIn 8.1 laptop) - whilst trying to build WebKit with VS 2017.

The simple issue here is that the VC++ compiler (i.e cl.exe and it's dependent DLLs) is not visible to CMake. Simple. By making the VC++ folders containing those binaries visible to CMake and your working command prompt(if you're running Cmake from a command prompt), voila! (In addition to key points raised by others , above)

Anyway, after all kinds of fixes - as posted on these many forums- I discovered that it was SIMPLY a matter of ensuring that the PATH variable's contents are not cluttered with multiple Visual Studio BIN paths etc; and instead, points to :

a) the location of your compiler (i.e. cl.exe for your preferred version of Visual Studio ), which in my case(targeting 64-bit platform, and developing on a 64-bit host) is: C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC\Tools\MSVC\14.15.26726\bin\Hostx64\x64

b) and in addition, the folder containing a dependent DLL called (which cl.exe is dependent on): api-ms-win-crt-runtime-l1-1-0.dll - which on my machine is:

C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\Common7\IDE\Remote Debugger\x64

These two directories being added to a simplified and CUSTOM System Path variable(working under a Admin priviledged commmand prompt), eliminated my "No CMAKE_C_COMPILER could be found" and "No CMAKE_CXX_COMPILER could be found." errors.

Hope it helps someone.

ModuleNotFoundError: No module named 'sklearn'

The other name of sklearn in anaconda is scikit-learn. simply open your anaconda navigator, go to the environments, select your environment, for example tensorflow or whatever you want to work with, search for scikit_learn in the list of uninstalled packages, apply it and then you can import sklearn in your jupyter.

Build Eclipse Java Project from Command Line

To complete André's answer, an ant solution could be like the one described in Emacs, JDEE, Ant, and the Eclipse Java Compiler, as in:

      <javac
          srcdir="${src}"
          destdir="${build.dir}/classes"> 
        <compilerarg 
           compiler="org.eclipse.jdt.core.JDTCompilerAdapter" 
           line="-warn:+unused -Xemacs"/>
        <classpath refid="compile.classpath" />
      </javac>

The compilerarg element also allows you to pass in additional command line args to the eclipse compiler.

You can find a full ant script example here which would be invoked in a command line with:

java -cp C:/eclipse-SDK-3.4-win32/eclipse/plugins/org.eclipse.equinox.launcher_1.0.100.v20080509-1800.jar org.eclipse.core.launcher.Main -data "C:\Documents and Settings\Administrator\workspace" -application org.eclipse.ant.core.antRunner -buildfile build.xml -verbose

BUT all that involves ant, which is not what Keith is after.

For a batch compilation, please refer to Compiling Java code, especially the section "Using the batch compiler"

The batch compiler class is located in the JDT Core plug-in. The name of the class is org.eclipse.jdt.compiler.batch.BatchCompiler. It is packaged into plugins/org.eclipse.jdt.core_3.4.0..jar. Since 3.2, it is also available as a separate download. The name of the file is ecj.jar.
Since 3.3, this jar also contains the support for jsr199 (Compiler API) and the support for jsr269 (Annotation processing). In order to use the annotations processing support, a 1.6 VM is required.

Running the batch compiler From the command line would give

java -jar org.eclipse.jdt.core_3.4.0<qualifier>.jar -classpath rt.jar A.java

or:

java -jar ecj.jar -classpath rt.jar A.java

All java compilation options are detailed in that section as well.

The difference with the Visual Studio command line compilation feature is that Eclipse does not seem to directly read its .project and .classpath in a command-line argument. You have to report all information contained in the .project and .classpath in various command-line options in order to achieve the very same compilation result.

So, then short answer is: "yes, Eclipse kind of does." ;)

How to set up fixed width for <td>?

Hard to judge without the context of the page html or the rest of your CSS. There might be a zillion reasons why your CSS rule is not affecting the td element.

Have you tried more specific CSS selectors such as

tr.somethingontrlevel td.something {
  width: 90px;
}

This to avoid your CSS being overridden by a more specific rule from the bootstrap css.

(by the way, in your inline css sample with the style attribute, you misspelled width - that could explain why that try failed!)

Assign variable in if condition statement, good practice or not?

If you were to refer to Martin Fowlers book Refactoring improving the design of existing code ! Then there are several cases where it would be good practice eg. long complex conditionals to use a function or method call to assert your case:

"Motivation

One of the most common areas of complexity in a program lies in complex conditional logic. As you write code to test conditions and to do various things depending on various conditions, you quickly end up with a pretty long method. Length of a method is in itself a factor that makes it harder to read, but conditions increase the difficulty. The problem usually lies in the fact that the code, both in the condition checks and in the actions, tells you what happens but can easily obscure why it happens.

As with any large block of code, you can make your intention clearer by decomposing it and replacing chunks of code with a method call named after the intention of that block of code. > With conditions you can receive further benefit by doing this for the conditional part and each of the alternatives. This way you highlight the condition and make it clearly what you > are branching on. You also highlight the reason for the branching."

And yes his answer is also valid for Java implementations. It does not assign the conditional function to a variable though in the examples.

PHP code to convert a MySQL query to CSV

SELECT * INTO OUTFILE "c:/mydata.csv"
FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"'
LINES TERMINATED BY "\n"
FROM my_table;

(the documentation for this is here: http://dev.mysql.com/doc/refman/5.0/en/select.html)

or:

$select = "SELECT * FROM table_name";

$export = mysql_query ( $select ) or die ( "Sql error : " . mysql_error( ) );

$fields = mysql_num_fields ( $export );

for ( $i = 0; $i < $fields; $i++ )
{
    $header .= mysql_field_name( $export , $i ) . "\t";
}

while( $row = mysql_fetch_row( $export ) )
{
    $line = '';
    foreach( $row as $value )
    {                                            
        if ( ( !isset( $value ) ) || ( $value == "" ) )
        {
            $value = "\t";
        }
        else
        {
            $value = str_replace( '"' , '""' , $value );
            $value = '"' . $value . '"' . "\t";
        }
        $line .= $value;
    }
    $data .= trim( $line ) . "\n";
}
$data = str_replace( "\r" , "" , $data );

if ( $data == "" )
{
    $data = "\n(0) Records Found!\n";                        
}

header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename=your_desired_name.xls");
header("Pragma: no-cache");
header("Expires: 0");
print "$header\n$data";

how to set cursor style to pointer for links without hrefs

Just add this to your global CSS style:

a { cursor: pointer; }

This way you're not dependent on the browser default cursor style anymore.

Create folder in Android

If you are trying to make more than just one folder on the root of the sdcard, ex. Environment.getExternalStorageDirectory() + "/Example/Ex App/"

then instead of folder.mkdir() you would use folder.mkdirs()

I've made this mistake in the past & I took forever to figure it out.

When is assembly faster than C?

I can't give the specific examples because it was too many years ago, but there were plenty of cases where hand-written assembler could out-perform any compiler. Reasons why:

  • You could deviate from calling conventions, passing arguments in registers.

  • You could carefully consider how to use registers, and avoid storing variables in memory.

  • For things like jump tables, you could avoid having to bounds-check the index.

Basically, compilers do a pretty good job of optimizing, and that is nearly always "good enough", but in some situations (like graphics rendering) where you're paying dearly for every single cycle, you can take shortcuts because you know the code, where a compiler could not because it has to be on the safe side.

In fact, I have heard of some graphics rendering code where a routine, like a line-draw or polygon-fill routine, actually generated a small block of machine code on the stack and executed it there, so as to avoid continual decision-making about line style, width, pattern, etc.

That said, what I want a compiler to do is generate good assembly code for me but not be too clever, and they mostly do that. In fact, one of the things I hate about Fortran is its scrambling the code in an attempt to "optimize" it, usually to no significant purpose.

Usually, when apps have performance problems, it is due to wasteful design. These days, I would never recommend assembler for performance unless the overall app had already been tuned within an inch of its life, still was not fast enough, and was spending all its time in tight inner loops.

Added: I've seen plenty of apps written in assembly language, and the main speed advantage over a language like C, Pascal, Fortran, etc. was because the programmer was far more careful when coding in assembler. He or she is going to write roughly 100 lines of code a day, regardless of language, and in a compiler language that's going to equal 3 or 400 instructions.

Docker: Copying files from Docker container to host

I used PowerShell (Admin) with this command.

docker cp {container id}:{container path}/error.html  C:\\error.html

Example

docker cp ff3a6608467d:/var/www/app/error.html  C:\\error.html

Get current directory name (without full path) in a Bash script

Use the basename program. For your case:

% basename "$PWD"
bin

difference between new String[]{} and new String[] in java

{} defines the contents of the array, in this case it is empty. These would both have an array of three Strings

String[] array = {"element1","element2","element3"};
String[] array = new String[] {"element1","element2","element3"};

while [] on the expression side (right side of =) of a statement defines the size of an intended array, e.g. this would have an array of 10 locations to place Strings

String[] array = new String[10];

...But...

String array = new String[10]{};  //The line you mentioned above

Was wrong because you are defining an array of length 10 ([10]), then defining an array of length 0 ({}), and trying to set them to the same array reference (array) in one statement. Both cannot be set.

Additionally

The array should be defined as an array of a given type at the start of the statement like String[] array. String array = /* array value*/ is saying, set an array value to a String, not to an array of Strings.

How to properly add cross-site request forgery (CSRF) token using PHP

CSRF protection

TYPES OF CSRF USAGE

IN FORM

<form>
   @csrf
</form>

or

<input type="hidden" name="token" value="{{ form_token() }}" />

META TAG

<meta name="csrf-token" content="{{ csrf_token() }}">

AJAX

$.ajaxSetup({
    headers: {
        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
    }
});

SESSION

use Illuminate\Http\Request;

Route::get('/token', function (Request $request) {
    $token = $request->session()->token();

    $token = csrf_token();

    // ...
});

MIDDLEWARE

 App\Providers\RouteServiceProvider

<?php

namespace App\Http\Middleware;

use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as Middleware;

class VerifyCsrfToken extends Middleware
{
    /**
     * The URIs that should be excluded from CSRF verification.
     *
     * @var array
     */
    protected $except = [
        'stripe/*',
        'http://example.com/foo/bar',
        'http://example.com/foo/*',
    ];
}

CSS fill remaining width

I would probably do something along the lines of

<div id='search-logo-bar'><input type='text'/></div>

with css

div#search-logo-bar {
    padding-left:10%;
    background:#333 url(logo.png) no-repeat left center;
    background-size:10%;
}
input[type='text'] {
    display:block;
    width:100%;
}

DEMO

http://jsfiddle.net/5MHnt/

Allow anonymous authentication for a single folder in web.config?

<location path="ForAll/Demo.aspx">
 <system.web>
  <authorization>
    <allow users="*" />
  </authorization>
 </system.web>
</location>

In Addition: If you want to write something on that folder through website , you have to give IIS_User permission to the folder

Python: SyntaxError: non-keyword after keyword arg

To really get this clear, here's my for-beginners answer: You inputed the arguments in the wrong order.
A keyword argument has this style:

nullable=True, unique=False

A fixed parameter should be defined: True, False, etc. A non-keyword argument is different:

name="Ricardo", fruit="chontaduro" 

This syntax error asks you to first put name="Ricardo" and all of its kind (non-keyword) before those like nullable=True.

What is the difference between CSS and SCSS?

Variable definitions right:

$      => SCSS, SASS
--     => CSS
@      => LESS

All answers is good but question a little different than answers

"about Sass. How is SCSS different from CSS" : scss is well formed CSS3 syntax. uses sass preprocessor to create that.

and if I use SCSS instead of CSS will it work the same? yes. if your ide supports sass preprocessor. than it will work same.

Sass has two syntaxes. The most commonly used syntax is known as “SCSS” (for “Sassy CSS”), and is a superset of CSS3’s syntax. This means that every valid CSS3 stylesheet is valid SCSS as well. SCSS files use the extension .scss.

The second, older syntax is known as the indented syntax (or just “.sass”). Inspired by Haml’s terseness, it’s intended for people who prefer conciseness over similarity to CSS. Instead of brackets and semicolons, it uses the indentation of lines to specify blocks. Files in the indented syntax use the extension .sass.


  • Furher Information About:

What Is A CSS Preprocessor?

CSS in itself is devoid of complex logic and functionality which is required to write reusable and organized code. As a result, a developer is bound by limitations and would face extreme difficulty in code maintenance and scalability, especially when working on large projects involving extensive code and multiple CSS stylesheets. This is where CSS Preprocessors come to the rescue.

A CSS Preprocessor is a tool used to extend the basic functionality of default vanilla CSS through its own scripting language. It helps us to use complex logical syntax like – variables, functions, mixins, code nesting, and inheritance to name a few, supercharging your vanilla CSS. By using CSS Preprocessors, you can seamlessly automate menial tasks, build reusable code snippets, avoid code repetition and bloating and write nested code blocks that are well organized and easy to read. However, browsers can only understand native vanilla CSS code and will be unable to interpret the CSS Preprocessor syntax. Therefore, the complex and advanced Preprocessor syntax needs to be first compiled into native CSS syntax which can then be interpreted by the browsers to avoid cross browser compatibility issues. While different Preprocessors have their own unique syntaxes, eventually all of them are compiled to the same native CSS code.

Moving forward in the article, we will take a look at the 3 most popular CSS Preprocessors currently being used by developers around the world i.e Sass, LESS, and Stylus. Before you decide the winner between Sass vs LESS vs Stylus, let us get to know them in detail first.

Sass – Syntactically Awesome Style Sheets

Sass is the acronym for “Syntactically Awesome Style Sheets”. Sass is not only the most popular CSS Preprocessor in the world but also one of the oldest, launched in 2006 by Hampton Catlin and later developed by Natalie Weizenbaum. Although Sass is written in Ruby language, a Precompiler LibSass allows Sass to be parsed in other languages and decouple it from Ruby. Sass has a massive active community and extensive learning resources available on the net for beginners. Thanks to its maturity, stability and powerful logical prowess, Sass has established itself to the forefront of CSS Preprocessor ahead of its rival peers.

Sass can be written in 2 syntaxes either using Sass or SCSS. What is the difference between the two? Let’s find out.

Syntax Declaration: Sass vs SCSS

  • SCSS stands for Sassy CSS. Unlike Sass, SCSS is not based on indentation.
  • .sass extension is used as original syntax for Sass, while SCSS offers a newer syntax with .scss extension.
  • Unlike Sass, SCSS has curly braces and semicolons, just like CSS.
  • Contrary to SCSS, Sass is difficult to read as it is quite deviant from CSS. Which is why SCSS it the more recommended Sass syntax as it is easier to read and closely resembles Native CSS while at the same time enjoying with power of Sass.

Consider the example below with Sass vs SCSS syntax along with Compiled CSS code.

Sass SYNTAX
    $font-color: #fff
    $bg-color: #00f

    #box
      color: $font-color
      background: $bg-color

SCSS SYNTAX
    $font-color: #fff;
    $bg-color: #00f;

    #box{
      color: $font-color;
      background: $bg-color;
    }

In both cases, be it Sass or SCSS, the compiled CSS code will be the same –

#box {
      color: #fff;
      background: #00f;

Usage of Sass

Arguably the most Popular front end framework Bootstrap is written in Sass. Up until version 3, Bootstrap was written in LESS but bootstrap 4 adopted Sass and boosted its popularity. A few of the big companies using Sass are – Zapier, Uber, Airbnb and Kickstarter.

LESS – Leaner Style Sheets

LESS is an acronym for “Leaner Stylesheets”. It was released in 2009 by Alexis Sellier, 3 years after the initial launch of Sass in 2006. While Sass is written in Ruby, LESS is written JavaScript. In fact, LESS is a JavaScript library that extends the functionality of native vanilla CSS with mixins, variables, nesting and rule set loop. Sass vs LESS has been a heated debate. It is no surprise that LESS is the strongest competitor to Sass and has the second-largest user base. However, When bootstrap dumped LESS in favor of Sass with the launch of Bootstrap 4, LESS has waned in popularity. One of the few disadvantages of LESS over Sass is that it does not support functions. Unlike Sass, LESS uses @ to declare variables which might cause confusion with @media and @keyframes. However, One key advantage of LESS over Sass and Stylus or any other preprocessors, is the ease of adding it in your project. You can do that either by using NPM or by incorporating Less.js file. Syntax Declaration: LESS Uses .less extension. Syntax of LESS is quite similar to SCSS with the exception that for declaring variables, instead of $ sign, LESS uses @.

@font-color: #fff;
    @bg-color: #00f

    #box{
      color: @font-color;
      background: @bg-color;
    }

COMPILED CSS
    #box {
        color: #fff;
        background: #00f;
      }

Usage Of LESS The popular Bootstrap framework until the launch of version 4 was written in LESS. However, another popular framework called SEMANTIC UI is still written in LESS. Among the big companies using Sass are – Indiegogo, Patreon, and WeChat

Stylus

The stylus was launched in 2010 by former Node JS developer TJ Holowaychuk, nearly 4 years after the release of Sass and 1 year after the release of LESS. The stylus is written Node JS and fits perfectly with JS stack. The stylus was heavily influenced by the logical prowess of the Sass and simplicity of LESS. Even though Stylus is still popular with Node JS developers, it hasn’t managed to carve out a sizeable share for itself. One advantage of Stylus over Sass or LESS, is that it is armed with extremely powerful built-in functions and is capable of handling heavy computing.

Syntax Declaration: Stylus Uses .styl extension. Stylus offers a great deal of flexibility in writing syntax, supports native CSS as well as allows omission of brackets colons and semicolons. Also, note that Stylus does not use @ or $ symbols for defining variables. Instead, Stylus uses the assignment operators to indicate a variable declaration.

STYLUS SYNTAX WRITTEN LIKE NATIVE CSS

font-color = #fff;
bg-color = #00f;

#box {
    color: font-color;
    background: bg-color;
}

OR

STYLUS SYNTAX WITHOUT CURLY BRACES

font-color = #fff;
bg-color = #00f;

#box 
    color: font-color;
    background: bg-color;

OR

STYLUS SYNTAX WITHOUT COLONS AND SEMICOLONS

font-color = #fff
bg-color = #00f

#box 
    color font-color
    background bg-color

How to send email in ASP.NET C#

If you want to generate your email bodies in razor, you can use Mailzory. Also, you can download the nuget package from here.

// template path
var viewPath = Path.Combine("Views/Emails", "hello.cshtml");
// read the content of template and pass it to the Email constructor
var template = File.ReadAllText(viewPath);

var email = new Email(template);

// set ViewBag properties
email.ViewBag.Name = "Johnny";
email.ViewBag.Content = "Mailzory Is Funny";

// send email
var task = email.SendAsync("[email protected]", "subject");
task.Wait()

How can I check if a string represents an int, without using try/except?

You know, I've found (and I've tested this over and over) that try/except does not perform all that well, for whatever reason. I frequently try several ways of doing things, and I don't think I've ever found a method that uses try/except to perform the best of those tested, in fact it seems to me those methods have usually come out close to the worst, if not the worst. Not in every case, but in many cases. I know a lot of people say it's the "Pythonic" way, but that's one area where I part ways with them. To me, it's neither very performant nor very elegant, so, I tend to only use it for error trapping and reporting.

I was going to gripe that PHP, perl, ruby, C, and even the freaking shell have simple functions for testing a string for integer-hood, but due diligence in verifying those assumptions tripped me up! Apparently this lack is a common sickness.

Here's a quick and dirty edit of Bruno's post:

import sys, time, re

g_intRegex = re.compile(r"^([+-]?[1-9]\d*|0)$")

testvals = [
    # integers
    0, 1, -1, 1.0, -1.0,
    '0', '0.','0.0', '1', '-1', '+1', '1.0', '-1.0', '+1.0', '06',
    # non-integers
    'abc 123',
    1.1, -1.1, '1.1', '-1.1', '+1.1',
    '1.1.1', '1.1.0', '1.0.1', '1.0.0',
    '1.0.', '1..0', '1..',
    '0.0.', '0..0', '0..',
    'one', object(), (1,2,3), [1,2,3], {'one':'two'},
    # with spaces
    ' 0 ', ' 0.', ' .0','.01 '
]

def isInt_try(v):
    try:     i = int(v)
    except:  return False
    return True

def isInt_str(v):
    v = str(v).strip()
    return v=='0' or (v if v.find('..') > -1 else v.lstrip('-+').rstrip('0').rstrip('.')).isdigit()

def isInt_re(v):
    import re
    if not hasattr(isInt_re, 'intRegex'):
        isInt_re.intRegex = re.compile(r"^([+-]?[1-9]\d*|0)$")
    return isInt_re.intRegex.match(str(v).strip()) is not None

def isInt_re2(v):
    return g_intRegex.match(str(v).strip()) is not None

def check_int(s):
    s = str(s)
    if s[0] in ('-', '+'):
        return s[1:].isdigit()
    return s.isdigit()    


def timeFunc(func, times):
    t1 = time.time()
    for n in range(times):
        for v in testvals: 
            r = func(v)
    t2 = time.time()
    return t2 - t1

def testFuncs(funcs):
    for func in funcs:
        sys.stdout.write( "\t%s\t|" % func.__name__)
    print()
    for v in testvals:
        if type(v) == type(''):
            sys.stdout.write("'%s'" % v)
        else:
            sys.stdout.write("%s" % str(v))
        for func in funcs:
            sys.stdout.write( "\t\t%s\t|" % func(v))
        sys.stdout.write("\r\n") 

if __name__ == '__main__':
    print()
    print("tests..")
    testFuncs((isInt_try, isInt_str, isInt_re, isInt_re2, check_int))
    print()

    print("timings..")
    print("isInt_try:   %6.4f" % timeFunc(isInt_try, 10000))
    print("isInt_str:   %6.4f" % timeFunc(isInt_str, 10000)) 
    print("isInt_re:    %6.4f" % timeFunc(isInt_re, 10000))
    print("isInt_re2:   %6.4f" % timeFunc(isInt_re2, 10000))
    print("check_int:   %6.4f" % timeFunc(check_int, 10000))

Here are the performance comparison results:

timings..
isInt_try:   0.6426
isInt_str:   0.7382
isInt_re:    1.1156
isInt_re2:   0.5344
check_int:   0.3452

A C method could scan it Once Through, and be done. A C method that scans the string once through would be the Right Thing to do, I think.

EDIT:

I've updated the code above to work in Python 3.5, and to include the check_int function from the currently most voted up answer, and to use the current most popular regex that I can find for testing for integer-hood. This regex rejects strings like 'abc 123'. I've added 'abc 123' as a test value.

It is Very Interesting to me to note, at this point, that NONE of the functions tested, including the try method, the popular check_int function, and the most popular regex for testing for integer-hood, return the correct answers for all of the test values (well, depending on what you think the correct answers are; see the test results below).

The built-in int() function silently truncates the fractional part of a floating point number and returns the integer part before the decimal, unless the floating point number is first converted to a string.

The check_int() function returns false for values like 0.0 and 1.0 (which technically are integers) and returns true for values like '06'.

Here are the current (Python 3.5) test results:

              isInt_try |       isInt_str       |       isInt_re        |       isInt_re2       |   check_int   |
0               True    |               True    |               True    |               True    |       True    |
1               True    |               True    |               True    |               True    |       True    |
-1              True    |               True    |               True    |               True    |       True    |
1.0             True    |               True    |               False   |               False   |       False   |
-1.0            True    |               True    |               False   |               False   |       False   |
'0'             True    |               True    |               True    |               True    |       True    |
'0.'            False   |               True    |               False   |               False   |       False   |
'0.0'           False   |               True    |               False   |               False   |       False   |
'1'             True    |               True    |               True    |               True    |       True    |
'-1'            True    |               True    |               True    |               True    |       True    |
'+1'            True    |               True    |               True    |               True    |       True    |
'1.0'           False   |               True    |               False   |               False   |       False   |
'-1.0'          False   |               True    |               False   |               False   |       False   |
'+1.0'          False   |               True    |               False   |               False   |       False   |
'06'            True    |               True    |               False   |               False   |       True    |
'abc 123'       False   |               False   |               False   |               False   |       False   |
1.1             True    |               False   |               False   |               False   |       False   |
-1.1            True    |               False   |               False   |               False   |       False   |
'1.1'           False   |               False   |               False   |               False   |       False   |
'-1.1'          False   |               False   |               False   |               False   |       False   |
'+1.1'          False   |               False   |               False   |               False   |       False   |
'1.1.1'         False   |               False   |               False   |               False   |       False   |
'1.1.0'         False   |               False   |               False   |               False   |       False   |
'1.0.1'         False   |               False   |               False   |               False   |       False   |
'1.0.0'         False   |               False   |               False   |               False   |       False   |
'1.0.'          False   |               False   |               False   |               False   |       False   |
'1..0'          False   |               False   |               False   |               False   |       False   |
'1..'           False   |               False   |               False   |               False   |       False   |
'0.0.'          False   |               False   |               False   |               False   |       False   |
'0..0'          False   |               False   |               False   |               False   |       False   |
'0..'           False   |               False   |               False   |               False   |       False   |
'one'           False   |               False   |               False   |               False   |       False   |
<obj..>         False   |               False   |               False   |               False   |       False   |
(1, 2, 3)       False   |               False   |               False   |               False   |       False   |
[1, 2, 3]       False   |               False   |               False   |               False   |       False   |
{'one': 'two'}  False   |               False   |               False   |               False   |       False   |
' 0 '           True    |               True    |               True    |               True    |       False   |
' 0.'           False   |               True    |               False   |               False   |       False   |
' .0'           False   |               False   |               False   |               False   |       False   |
'.01 '          False   |               False   |               False   |               False   |       False   |

Just now I tried adding this function:

def isInt_float(s):
    try:
        return float(str(s)).is_integer()
    except:
        return False

It performs almost as well as check_int (0.3486) and it returns true for values like 1.0 and 0.0 and +1.0 and 0. and .0 and so on. But it also returns true for '06', so. Pick your poison, I guess.

Validate phone number using angular js

Check this answer

Basically you can create a regex to fulfil your needs and then assign that pattern to your input field.

Or for a more direct approach:

<input type="number" require ng-pattern="<your regex here>">

More info @ angular docs here and here (built-in validators)

trying to align html button at the center of the my page

I've really taken recently to display: table to give things a fixed size such as to enable margin: 0 auto to work. Has made my life a lot easier. You just need to get past the fact that 'table' display doesn't mean table html.

It's especially useful for responsive design where things just get hairy and crazy 50% left this and -50% that just become unmanageable.

style
{
   display: table;
   margin: 0 auto
}

JsFiddle

In addition if you've got two buttons and you want them the same width you don't even need to know the size of each to get them to be the same width - because the table will magically collapse them for you.

enter image description here

JsFiddle

(this also works if they're inline and you want to center two buttons side to side - try doing that with percentages!).

Can I have multiple :before pseudo-elements for the same element?

If your main element has some child elements or text, you could make use of it.

Position your main element relative (or absolute/fixed) and use both :before and :after positioned absolute (in my situation it had to be absolute, don't know about your's).

Now if you want one more pseudo-element, attach an absolute :before to one of the main element's children (if you have only text, put it in a span, now you have an element), which is not relative/absolute/fixed.

This element will start acting like his owner is your main element.

HTML

<div class="circle">
    <span>Some text</span>
</div>

CSS

.circle {
    position: relative; /* or absolute/fixed */
}

.circle:before {
    position: absolute;
    content: "";
    /* more styles: width, height, etc */
}

.circle:after {
    position: absolute;
    content: "";
    /* more styles: width, height, etc */
}

.circle span {
    /* not relative/absolute/fixed */
}

.circle span:before {
    position: absolute;
    content: "";
    /* more styles: width, height, etc */
}

printing a value of a variable in postgresql

You can raise a notice in Postgres as follows:

raise notice 'Value: %', deletedContactId;

Read here

Why doesn't JavaScript have a last method?

Array.prototype.last = Array.prototype.last || function() {
    var l = this.length;
    return this[l-1];
}

x = [1,2];
alert( x.last() )

How to change facet labels?

Simple solution (from here):

p <- ggplot(mtcars, aes(disp, drat)) + geom_point()
# Example (old labels)
p + facet_wrap(~am)


to_string <- as_labeller(c(`0` = "Zero", `1` = "One"))
# Example (New labels)
p + facet_wrap(~am, labeller = to_string)

Search for one value in any column of any table inside a database

All third=party tools mentioned below are 100% free.

I’ve used ApexSQL Search with good success for searching both objects and data in tables. It comes with several other features such as relationship diagrams and such…

I was a bit slow on large (40GB TFS Database) databases though…

enter image description here

Apart from this there is also SSMS Tools pack that offers a lot of other features that are quite useful even though these are not directly related to searching text.

Request UAC elevation from within a Python script?

If your script always requires an Administrator's privileges then:

runas /user:Administrator "python your_script.py"

Writing numerical values on the plot with Matplotlib

You can use the annotate command to place text annotations at any x and y values you want. To place them exactly at the data points you could do this

import numpy
from matplotlib import pyplot

x = numpy.arange(10)
y = numpy.array([5,3,4,2,7,5,4,6,3,2])

fig = pyplot.figure()
ax = fig.add_subplot(111)
ax.set_ylim(0,10)
pyplot.plot(x,y)
for i,j in zip(x,y):
    ax.annotate(str(j),xy=(i,j))

pyplot.show()

If you want the annotations offset a little, you could change the annotate line to something like

ax.annotate(str(j),xy=(i,j+0.5))

How to kill all processes with a given partial name?

Use pkill -f, which matches the pattern for any part of the command line

pkill -f my_pattern

Converting an int into a 4 byte char array (C)

Do you want to address the individual bytes of a 32-bit int? One possible method is a union:

union
{
    unsigned int integer;
    unsigned char byte[4];
} foo;

int main()
{
    foo.integer = 123456789;
    printf("%u %u %u %u\n", foo.byte[3], foo.byte[2], foo.byte[1], foo.byte[0]);
}

Note: corrected the printf to reflect unsigned values.

Check if a parameter is null or empty in a stored procedure

Another option:

IF ISNULL(@PreviousStartDate, '') = '' ...

see a function based on this expression at http://weblogs.sqlteam.com/mladenp/archive/2007/06/13/60231.aspx

Variable is accessed within inner class. Needs to be declared final

    public class ConfigureActivity extends Activity {

        EditText etOne;
        EditText etTwo;
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_configure);

            Button btnConfigure = findViewById(R.id.btnConfigure1);   
            btnConfigure.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            configure();
                        }
                    });
    }

    public  void configure(){
            String one = etOne.getText().toString();
            String two = etTwo.getText().toString();
    }
}

Check whether a value is a number in JavaScript or jQuery

function isNumber(n) {
  return !isNaN(parseFloat(n)) && isFinite(n);
}

Correct path for img on React.js

Some older answers din't work, others are good but won't explain the theme, in summary:

If image is in 'public' directory

Example: \public\charts\a.png

In html:

<img id="imglogo" src="/charts/logo.svg" />

In JavaScript:

Create image to new img, dynamically:

var img1 = document.createElement("img");  
img1.src = 'charts/a.png';  

Set image to existing img with id as 'img1', dynamically:

document.getElementById('img1').src = 'charts/a.png';

If image is in 'src' directory:

Example: \src\logo.svg

In JavaScript:

import logo from './logo.svg';  
img1.src = logo;  

In jsx:

<img src={logo} /> 

Python 3 string.join() equivalent?

Visit https://www.tutorialspoint.com/python/string_join.htm

s=" "
seq=["ab", "cd", "ef"]
print(s.join(seq))

ab cd ef

s="."
print(s.join(seq))

ab.cd.ef

Change DIV content using ajax, php and jQuery

<script>

function getSummary(id)
{
   $.ajax({

     type: "GET",//post
     url: 'Your URL',
     data: "id="+id, // appears as $_GET['id'] @ ur backend side
     success: function(data) {
           // data is ur summary
          $('#summary').html(data);
     }

   });

}
</script>

How to properly use jsPDF library

This is finally what did it for me (and triggers a disposition):

_x000D_
_x000D_
function onClick() {_x000D_
  var pdf = new jsPDF('p', 'pt', 'letter');_x000D_
  pdf.canvas.height = 72 * 11;_x000D_
  pdf.canvas.width = 72 * 8.5;_x000D_
_x000D_
  pdf.fromHTML(document.body);_x000D_
_x000D_
  pdf.save('test.pdf');_x000D_
};_x000D_
_x000D_
var element = document.getElementById("clickbind");_x000D_
element.addEventListener("click", onClick);
_x000D_
<h1>Dsdas</h1>_x000D_
_x000D_
<a id="clickbind" href="#">Click</a>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.3.3/jspdf.min.js"></script>
_x000D_
_x000D_
_x000D_

And for those of the KnockoutJS inclination, a little binding:

ko.bindingHandlers.generatePDF = {
    init: function(element) {

        function onClick() {
            var pdf = new jsPDF('p', 'pt', 'letter');
            pdf.canvas.height = 72 * 11;
            pdf.canvas.width = 72 * 8.5;

            pdf.fromHTML(document.body);

            pdf.save('test.pdf');                    
        };

        element.addEventListener("click", onClick);
    }
};

How to restore the permissions of files and directories within git if they have been modified?

I use git from cygwin on Windows, the git apply solution doesn't work for me. Here is my solution, run chmod on every file to reset its permissions.

#!/bin/bash
IFS=$'\n'
for c in `git diff -p |sed -n '/diff --git/{N;s/diff --git//g;s/\n/ /g;s# a/.* b/##g;s/old mode //g;s/\(.*\) 100\(.*\)/chmod \2 \1/g;p}'`
do
        eval $c
done
unset IFS

What do curly braces mean in Verilog?

As Matt said, the curly braces are for concatenation. The extra curly braces around 16{a[15]} are the replication operator. They are described in the IEEE Standard for Verilog document (Std 1364-2005), section "5.1.14 Concatenations".

{16{a[15]}}

is the same as

{ 
   a[15], a[15], a[15], a[15], a[15], a[15], a[15], a[15],
   a[15], a[15], a[15], a[15], a[15], a[15], a[15], a[15]
}

In bit-blasted form,

assign result = {{16{a[15]}}, {a[15:0]}};

is the same as:

assign result[ 0] = a[ 0];
assign result[ 1] = a[ 1];
assign result[ 2] = a[ 2];
assign result[ 3] = a[ 3];
assign result[ 4] = a[ 4];
assign result[ 5] = a[ 5];
assign result[ 6] = a[ 6];
assign result[ 7] = a[ 7];
assign result[ 8] = a[ 8];
assign result[ 9] = a[ 9];
assign result[10] = a[10];
assign result[11] = a[11];
assign result[12] = a[12];
assign result[13] = a[13];
assign result[14] = a[14];
assign result[15] = a[15];
assign result[16] = a[15];
assign result[17] = a[15];
assign result[18] = a[15];
assign result[19] = a[15];
assign result[20] = a[15];
assign result[21] = a[15];
assign result[22] = a[15];
assign result[23] = a[15];
assign result[24] = a[15];
assign result[25] = a[15];
assign result[26] = a[15];
assign result[27] = a[15];
assign result[28] = a[15];
assign result[29] = a[15];
assign result[30] = a[15];
assign result[31] = a[15];

NameError: name 'datetime' is not defined

It can also be used as below:

from datetime import datetime
start_date = datetime(2016,3,1)
end_date = datetime(2016,3,10)

Insert php variable in a href

in php

echo '<a href="' . $folder_path . '">Link text</a>';

or

<a href="<?=$folder_path?>">Link text</a>;

or

<a href="<?php echo $folder_path ?>">Link text</a>;

How to check if DST (Daylight Saving Time) is in effect, and if so, the offset?

I've found that using the Moment.js library with some of the concepts described here (comparing Jan to June) works very well.

This simple function will return whether the timezone that the user is in observes Daylight Saving Time:

function HasDST() {
    return moment([2017, 1, 1]).isDST() != moment([2017, 6, 1]).isDST();
}

A simple way to check that this works (on Windows) is to change your timezone to a non DST zone, for example Arizona will return false, whereas EST or PST will return true.

enter image description here

Invert match with regexp

Based on Daniel's answer, I think I've got something that works:

^(.(?!test))*$

The key is that you need to make the negative assertion on every character in the string

How do I read image data from a URL in Python?

Manually wrapping in BytesIO is no longer needed since PIL >= 2.8.0. Just use Image.open(response.raw)

Adding on top of Vinícius's comment:

You should pass stream=True as noted https://requests.readthedocs.io/en/master/user/quickstart/#raw-response-content

So

img = Image.open(requests.get(url, stream=True).raw)

When to use StringBuilder in Java

Ralph's answer is fabulous. I would rather use StringBuilder class to build/decorate the String because the usage of it is more look like Builder pattern.

public String decorateTheString(String orgStr){
            StringBuilder builder = new StringBuilder();
            builder.append(orgStr);
            builder.deleteCharAt(orgStr.length()-1);
            builder.insert(0,builder.hashCode());
            return builder.toString();
}

It can be use as a helper/builder to build the String, not the String itself.

How to Disable landscape mode in Android?

You can do this for your entire application without having to make all your activities extend a common base class.

The trick is first to make sure you include an Application subclass in your project. In its onCreate(), called when your app first starts up, you register an ActivityLifecycleCallbacks object (API level 14+) to receive notifications of activity lifecycle events.

This gives you the opportunity to execute your own code whenever any activity in your app is started (or stopped, or resumed, or whatever). At this point you can call setRequestedOrientation() on the newly created activity.

And do not forget to add app:name=".MyApp" in your manifest file.

class MyApp extends Application {

    @Override
    public void onCreate() {
        super.onCreate();  

        // register to be informed of activities starting up
        registerActivityLifecycleCallbacks(new ActivityLifecycleCallbacks() {

            @Override
            public void onActivityCreated(Activity activity, 
                                          Bundle savedInstanceState) {

                // new activity created; force its orientation to portrait
                activity.setRequestedOrientation(
                    ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
            }
            ....
        });
    }
}

Short form for Java if statement

You can use ternary operator in java.

Syntax:

Condition ? Block 1 : Block 2

So in your code you can do like this,

name = ((city.getName() == null) ? "N/A" : city.getName());

For more info you can refer this resource.

Need to navigate to a folder in command prompt

I prefer to use

pushd d:\windows\movie

because it requires no switches yet the working directory will change to the correct drive and path in one step.

Added plus:

  • also works with UNC paths if an unused drive letter is available for automatic drive mapping,
  • easy to go back to the previous working directory: just enter popd.

How to get a tab character?

Tab is [HT], or character number 9, in the unicode library.

C# version of java's synchronized keyword?

You can use the lock statement instead. I think this can only replace the second version. Also, remember that both synchronized and lock need to operate on an object.

Quickly create large file on a Windows system

I was looking for a way to create a large dummy file with space allocation recently. All of the solutions look awkward. Finally I just started the DISKPART utility in Windows (embedded since Windows Vista):

DISKPART
CREATE VDISK FILE="C:\test.vhd" MAXIMUM=20000 TYPE=FIXED

Where MAXIMUM is the resulting file size, 20 GB here.

MongoDB via Mongoose JS - What is findByID?

If the schema of id is not of type ObjectId you cannot operate with function : findbyId()

Best database field type for a URL

This really depends on your use case (see below), but storing as TEXT has performance issues, and a huge VARCHAR sounds like overkill for most cases.

My approach: use a generous, but not unreasonably large VARCHAR length, such as VARCHAR(500) or so, and encourage the users who need a larger URL to use a URL shortener such as safe.mn.

The Twitter approach: For a really nice UX, provide an automatic URL shortener for overly-long URL's and store the "display version" of the link as a snippet of the URL with ellipses at the end. (Example: http://stackoverflow.com/q/219569/1235702 would be displayed as stackoverflow.com/q/21956... and would link to a shortened URL http://ex.ampl/e1234)

Notes and Caveats

  • Obviously, the Twitter approach is nicer, but for my app's needs, recommending a URL shortener was sufficient.
  • URL shorteners have their drawbacks, such as security concerns. In my case, it's not a huge risk because the URL's are not public and not heavily used; however, this obviously won't work for everyone. safe.mn appears to block a lot of spam and phishing URL's, but I would still recommend caution.
  • Be sure to note that you shouldn't force your users to use a URL shortener. For most cases (at least for my app's needs), 500 characters is overly sufficient for what most users will be using it for. Only use/recommend a URL shortener for overly-long links.

Regex: Check if string contains at least one digit

The regular expression you are looking for is simply this:

[0-9]

You do not mention what language you are using. If your regular expression evaluator forces REs to be anchored, you need this:

.*[0-9].*

Some RE engines (modern ones!) also allow you to write the first as \d (mnemonically: digit) and the second would then become .*\d.*.

Will Google Android ever support .NET?

Update: Since I wrote this answer two years ago, we productized Mono to run on Android. The work included a few steps: porting Mono to Android, integrating it with Visual Studio, building plugins for MonoDevelop on Mac and Windows and exposing the Java Android APIs to .NET languages. This is now available at http://monodroid.net

Mono on Android is based on the Mono 2.10 runtime, and defaults to 4.0 profile with the C# 4.0 compiler and uses Mono's new SGen garbage collection engine, as well as our new distributed garbage collection system that performs GC across Java and Mono.


The links below reflect Mono on Android as of January of 2009, I have kept them for historical context

Mono now works on Android thanks to the work of Koushik Dutta and Marc Crichton.

You can see a video of it running here: http://www.koushikdutta.com/2009/01/mono-on-android-with-gratuitous-shaky.html

And you can get the instructions to build Mono yourself here: http://www.koushikdutta.com/2009/01/building-mono-for-android.html

You can get a benchmark comparing Mono's JIT vs Dalvik's interpreter here: http://www.koushikdutta.com/2009/01/dalvik-vs-mono.html

And of course, you can get a pre-configured image with Mono here (go to the bottom of the post for details on using that): http://www.koushikdutta.com/2009/01/building-mono-for-android.html

Calculate row means on subset of columns

Calculate row means on a subset of columns:

Create a new data.frame which specifies the first column from DF as an column called ID and calculates the mean of all the other fields on that row, and puts that into column entitled 'Means':

data.frame(ID=DF[,1], Means=rowMeans(DF[,-1]))
  ID    Means
1  A 3.666667
2  B 4.333333
3  C 3.333333
4  D 4.666667
5  E 4.333333

Redirect form to different URL based on select option element

This can be archived by adding code on the onchange event of the select control.

For Example:

<select onchange="this.options[this.selectedIndex].value && (window.location = this.options[this.selectedIndex].value);">
    <option value="http://gmail.com">Gmail</option>
    <option value="http://youtube.com">Youtube</option>
</select>

Markdown: continue numbered list

I solved this problem on Github separating the indented sub-block with a newline, for instance, you write the item 1, then hit enter twice (like if it was a new paragraph), indent the block and write what you want (a block of code, text, etc). More information on Markdown lists and Markdown line breaks.

Example:

  1. item one
  2. item two

    this block acts as a new paragraph, above there is a blank line

  3. item three

    some other code

  4. item four

How to get public directory?

I know this is a little late, but if someone else comes across this looking, you can now use public_path(); in Laravel 4, it has been added to the helper.php file in the support folder see here.

Scrolling to an Anchor using Transition/CSS3

If anybody is just like me willing to use jQuery, but still found himself looking to this question then this may help you guys:

https://html-online.com/articles/animated-scroll-anchorid-function-jquery/

_x000D_
_x000D_
$(document).ready(function () {_x000D_
            $("a.scrollLink").click(function (event) {_x000D_
                event.preventDefault();_x000D_
                $("html, body").animate({ scrollTop: $($(this).attr("href")).offset().top }, 500);_x000D_
            });_x000D_
        });
_x000D_
<a href="#anchor1" class="scrollLink">Scroll to anchor 1</a>_x000D_
<a href="#anchor2" class="scrollLink">Scroll to anchor 2</a>_x000D_
<p id="anchor1"><strong>Anchor 1</strong> - Lorem ipsum dolor sit amet, nonumes voluptatum mel ea.</p>_x000D_
<p id="anchor2"><strong>Anchor 2</strong> - Ex ignota epicurei quo, his ex doctus delenit fabellas.</p>
_x000D_
_x000D_
_x000D_

Possible to view PHP code of a website?

A bug or security vulnerability in the server (either Apache or the PHP engine), or your own PHP code, might allow an attacker to obtain access to your code.

For instance if you have a PHP script to allow people to download files, and an attacker can trick this script into download some of your PHP files, then your code can be leaked.

Since it's impossible to eliminate all bugs from the software you're using, if someone really wants to steal your code, and they have enough resources, there's a reasonable chance they'll be able to.

However, as long as you keep your server up-to-date, someone with casual interest is not able to see the PHP source unless there are some obvious security vulnerabilities in your code.

Read the Security section of the PHP manual as a starting point to keeping your code safe.

Can I clear cell contents without changing styling?

You should use the ClearContents method if you want to clear the content but preserve the formatting.

Worksheets("Sheet1").Range("A1:G37").ClearContents

How to set minDate to current date in jQuery UI Datepicker?

You can specify minDate as today by adding minDate: 0 to the options.

$("input.DateFrom").datepicker({
    minDate: 0,
    ...
});

Demo: http://jsfiddle.net/2CZtV/

Docs: http://jqueryui.com/datepicker/#min-max

How to call a parent class function from derived class function?

Given a parent class named Parent and a child class named Child, you can do something like this:

class Parent {
public:
    virtual void print(int x);
};

class Child : public Parent {
    void print(int x) override;
};

void Parent::print(int x) {
    // some default behavior
}

void Child::print(int x) {
    // use Parent's print method; implicitly passes 'this' to Parent::print
    Parent::print(x);
}

Note that Parent is the class's actual name and not a keyword.

How does BitLocker affect performance?

I used to use the PGP disk encryption product on a laptop (and ran NTFS compressed on top of that!). It didn't seem to have much effect if the amount of disk to be read was small; and most software sources aren't huge by disk standards.

You have lots of RAM and pretty fast processors. I spent most of my time thinking, typing or debugging.

I wouldn't worry very much about it.

Vertical dividers on horizontal UL menu

Quite and simple without any "having to specify the first element". CSS is more powerful than most think (e.g. the first-child:before is great!). But this is by far the cleanest and most proper way to do this, at least in my opinion it is.

#navigation ul
{
    margin: 0;
    padding: 0;
}

#navigation ul li
{
    list-style-type: none;
    display: inline;
}

#navigation li:not(:first-child):before {
    content: " | ";
}

Now just use a simple unordered list in HTML and it'll populate it for you. HTML should look like this:

<div id="navigation">
    <ul>
        <li><a href="#">Home</a></li>
        <li><a href="#">About Us</a></li>
        <li><a href="#">Support</a></li>
    </ul>
</div><!-- navigation -->

The result will be just like this:

HOME | ABOUT US | SUPPORT

Now you can indefinitely expand and never have to worry about order, changing links, or your first entry. It's all automated and works great!

Is it possible to pass parameters programmatically in a Microsoft Access update query?

You can also use TempVars - note '!' syntax is essential You can also use TempVars - note '!' syntax is essential

How to get the separate digits of an int number?

Since I don't see a method on this question which uses Java 8, I'll throw this in. Assuming that you're starting with a String and want to get a List<Integer>, then you can stream the elements like so.

List<Integer> digits = digitsInString.chars()
        .map(Character::getNumericValue)
        .boxed()
        .collect(Collectors.toList());

This gets the characters in the String as a IntStream, maps those integer representations of characters to a numeric value, boxes them, and then collects them into a list.

Add the loading screen in starting of the android application

Write the code:

  @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.splash);

        Thread welcomeThread = new Thread() {

            @Override
            public void run() {
                try {
                    super.run();
                    sleep(10000)  //Delay of 10 seconds
                } catch (Exception e) {

                } finally {

                    Intent i = new Intent(SplashActivity.this,
                            MainActivity.class);
                    startActivity(i);
                    finish();
                }
            }
        };
        welcomeThread.start();
    }

Using Custom Domains With IIS Express

I tried all of above, nothing worked. What resolved the issue was adding IPv6 bindings in the hosts file. In step 5 of @David Murdochs answer, add two lines instead of one, i.e.:

127.0.0.1 dev.example.com
::1 dev.example.com

I figured it out by checking $ ping localhost from command line, which used to return:

Reply from 127.0.0.1: bytes=32 time<1ms TTL=128

Instead, it now returns:

Reply from ::1: time<1ms

I don't know why, but for some reason IIS Express started using IPv6 instead of IPv4.

Python Array with String Indices

Even better, try an OrderedDict (assuming you want something like a list). Closer to a list than a regular dict since the keys have an order just like list elements have an order. With a regular dict, the keys have an arbitrary order.

Note that this is available in Python 3 and 2.7. If you want to use with an earlier version of Python you can find installable modules to do that.

Running conda with proxy

The best way I settled with is to set proxy environment variables right before using conda or pip install/update commands. Simply run:

set HTTP_PROXY=http://username:password@proxy_url:port

For example, your actual command could be like

set HTTP_PROXY=http://yourname:[email protected]_company.com:8080

If your company uses https proxy, then also

set HTTPS_PROXY=https://username:password@proxy_url:port

Once you exit Anaconda prompt then this setting is gone, so your username/password won't be saved after the session.

I didn't choose other methods mentioned in Anaconda documentation or some other sources, because they all require hardcoding of username/password into

  • Windows environment variables (also this requires restart of Anaconda prompt for the first time)
  • Conda .condarc or .netrc configuration files (also this won't work for PIP)
  • A batch/script file loaded while starting Anaconda prompt (also this might require configuring the path)

All of these are unsafe and will require constant update later. And if you forget where to update? More troubleshooting will come your way...

C#: Dynamic runtime cast

This should work:

public static dynamic Cast(dynamic obj, Type castTo)
{
    return Convert.ChangeType(obj, castTo);
}

Edit

I've written the following test code:

var x = "123";
var y = Cast(x, typeof(int));
var z = y + 7;
var w = Cast(z, typeof(string)); // w == "130"

It does resemble the kind of "typecasting" one finds in languages like PHP, JavaScript or Python (because it also converts the value to the desired type). I don't know if that's a good thing, but it certainly works... :-)

VBA Public Array : how to?

Option Explicit
     Public myarray (1 To 10)
     Public Count As Integer
     myarray(1) = "A"
     myarray(2) = "B"
     myarray(3) = "C"
     myarray(4) = "D"
     myarray(5) = "E"
     myarray(6) = "F"
     myarray(7) = "G"
     myarray(8) = "H"
     myarray(9) = "I"
     myarray(10) = "J"
Private Function unwrapArray()
     For Count = 1 to UBound(myarray)
       MsgBox "Letters of the Alphabet : " & myarray(Count)
     Next 
End Function

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

This is a warning related to the fact that most JavaScript frameworks (jQuery, Angular, YUI, Bootstrap...) offer backward support for old-nasty-most-hated Internet Explorer starting from IE8 down to IE6 :/

One day that backward compatibility support will be dropped (for IE8/7/6 since IE9 deals with it), and you will no more see this warning (and other IEish bugs)..

It's a question of time (now IE8 has 10% worldwide share, once it reaches 1% it is DEAD), meanwhile, just ignore the warning and stay zen :)

Is there any way to install Composer globally on Windows?

A bit more generic if you put the batch in the same folder as composer.phar:

@ECHO OFF
SET SUBDIR=%~dp0
php %SUBDIR%/composer.phar %*

I'd write it as a comment, but code isn't avail there

How to name an object within a PowerPoint slide?

Select the Object -> Format -> Selection Pane -> Double click to change the name

enter image description here

var self = this?

This question is not specific to jQuery, but specific to JavaScript in general. The core problem is how to "channel" a variable in embedded functions. This is the example:

var abc = 1; // we want to use this variable in embedded functions

function xyz(){
  console.log(abc); // it is available here!
  function qwe(){
    console.log(abc); // it is available here too!
  }
  ...
};

This technique relies on using a closure. But it doesn't work with this because this is a pseudo variable that may change from scope to scope dynamically:

// we want to use "this" variable in embedded functions

function xyz(){
  // "this" is different here!
  console.log(this); // not what we wanted!
  function qwe(){
    // "this" is different here too!
    console.log(this); // not what we wanted!
  }
  ...
};

What can we do? Assign it to some variable and use it through the alias:

var abc = this; // we want to use this variable in embedded functions

function xyz(){
  // "this" is different here! --- but we don't care!
  console.log(abc); // now it is the right object!
  function qwe(){
    // "this" is different here too! --- but we don't care!
    console.log(abc); // it is the right object here too!
  }
  ...
};

this is not unique in this respect: arguments is the other pseudo variable that should be treated the same way — by aliasing.

The current .NET SDK does not support targeting .NET Standard 2.0 error in Visual Studio 2017 update 15.3

I had the same problem as the current .NET SDK does not support targeting .NET Core 3.1. Either target .NET Core 1.1 or lower, or use a version of the .NET SDK that supports .NET Core 3.1

1) Make sure .Net core SDK installed on your machine. Download .NET!

2) set PATH environment variables as below Path

Go test string contains substring

Use the function Contains from the strings package.

import (
    "strings"
)
strings.Contains("something", "some") // true

What's the difference between django OneToOneField and ForeignKey?

The easiest way to draw a relationship between items is by understanding them in plain languages. Example

A user can have many cars but then a car can have just one owner. After establishing this, the foreign key should be used on the item with the many relationship. In this case the car. Meaning you'll include user as a foreign key in cars

And a one on one relationship is quite simple. Say a man and a heart. A man has only one heart and a heart can belong to just one man

All possible array initialization syntaxes

The array creation syntaxes in C# that are expressions are:

new int[3]
new int[3] { 10, 20, 30 }
new int[] { 10, 20, 30 }
new[] { 10, 20, 30 }

In the first one, the size may be any non-negative integral value and the array elements are initialized to the default values.

In the second one, the size must be a constant and the number of elements given must match. There must be an implicit conversion from the given elements to the given array element type.

In the third one, the elements must be implicitly convertible to the element type, and the size is determined from the number of elements given.

In the fourth one the type of the array element is inferred by computing the best type, if there is one, of all the given elements that have types. All the elements must be implicitly convertible to that type. The size is determined from the number of elements given. This syntax was introduced in C# 3.0.

There is also a syntax which may only be used in a declaration:

int[] x = { 10, 20, 30 };

The elements must be implicitly convertible to the element type. The size is determined from the number of elements given.

there isn't an all-in-one guide

I refer you to C# 4.0 specification, section 7.6.10.4 "Array Creation Expressions".

C++ Calling a function from another class

What you should do, is put CallFunction into *.cpp file, where you include B.h.

After edit, files will look like:

B.h:

#pragma once //or other specific to compiler...
using namespace std;

class A 
{
public:
    void CallFunction ();
};

class B: public A
{
public:
    virtual void bFunction()
        {
            //stuff done here
        }
};

B.cpp

#include "B.h"
void A::CallFunction(){
//use B object here...
}

Referencing to your explanation, that you have tried to change B b; into pointer- it would be okay, if you wouldn't use it in that same place. You can use pointer of undefined class(but declared), because ALL pointers have fixed byte size(4), so compiler doesn't have problems with that. But it knows nothing about the object they are pointing to(simply: knows the size/boundary, not the content).

So as long as you are using the knowledge, that all pointers are same size, you can use them anywhere. But if you want to use the object, they are pointing to, the class of this object must be already defined and known by compiler.

And last clarification: objects may differ in size, unlike pointers. Pointer is a number/index, which indicates the place in RAM, where something is stored(for example index: 0xf6a7b1).

React Native version mismatch

I had this problem for the longest time and none of the above solutions helped. I was in the middle of upgrading react native in a create-react-native-app project until I found out that not all versions of Expo support the latest React Native.

Found this page linked in the documentation that shows which version combinations of React Native, React, and Expo are officially supported:

Source: https://github.com/react-community/create-react-native-app/blob/master/VERSIONS.md

Editing the app.json and package.json files to match the corresponding versions and running npm install got everything working again.

git clone from another directory

In case you have space in your path, wrap it in double quotes:

$ git clone "//serverName/New Folder/Target" f1/

IIS7: Setup Integrated Windows Authentication like in IIS6

To enable the Windows Authentication on IIS7 on Windows 7 machine:

  • Go to Control Panel

  • Click Programs >> Programs and Features

  • Select "Turn Windows Features on or off" from left side.

  • Expand Internet Information Services >> World Wide Web Services >> Security

  • Select Windows Authentication and click OK.

  • Reset the IIS and Check in IIS now for windows authentication.

Enjoy

jQuery or JavaScript auto click

First i tried with this sample code:

$(document).ready(function(){ 
     $('#upload-file').click(); 
});

It didn't work for me. Then after, tried with this

$(document).ready(function(){ 
     $('#upload-file')[0].click(); 
});

No change. At last, tried with this

$(document).ready(function(){ 
     $('#upload-file')[0].click(function(){
     }); 
});

Solved my problem. Helpful for anyone.

How to show/hide an element on checkbox checked/unchecked states using jQuery?

Try this

<script>
    $().ready(function(){
        $('.coupon_question').live('click',function() 
        {
            if ($('.coupon_question').is(':checked')) {
                $(".answer").show();
            } else {
                $(".answer").hide();
            } 
        });
    });
</script>

Grid of responsive squares

Now we can easily do this using the aspect-ratio ref property

_x000D_
_x000D_
.container {
  display: grid;
  grid-template-columns: repeat(3, minmax(0, 1fr)); /* 3 columns */
  grid-gap: 10px;
}

.container>* {
  aspect-ratio: 1 / 1; /* a square ratio */
  border: 1px solid;
  
  /* center content */
  display: flex;
  align-items: center;
  justify-content: center;
  text-align: center;
}

img {
  max-width: 100%;
  display: block;
}
_x000D_
<div class="container">
  <div> some content here </div>
  <div><img src="https://picsum.photos/id/25/400/400"></div>
  <div>
    <h1>a title</h1>
  </div>
  <div>more and more content <br>here</div>
  <div>
    <h2>another title</h2>
  </div>
  <div><img src="https://picsum.photos/id/104/400/400"></div>
</div>
_x000D_
_x000D_
_x000D_

Also like below where we can have a variable number of columns

_x000D_
_x000D_
.container {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
  grid-gap: 10px;
}

.container>* {
  aspect-ratio: 1 / 1; /* a square ratio */
  border: 1px solid;
  
  /* center content */
  display: flex;
  align-items: center;
  justify-content: center;
  text-align: center;
}

img {
  max-width: 100%;
  display: block;
}
_x000D_
<div class="container">
  <div> some content here </div>
  <div><img src="https://picsum.photos/id/25/400/400"></div>
  <div>
    <h1>a title</h1>
  </div>
  <div>more and more content <br>here</div>
  <div>
    <h2>another title</h2>
  </div>
  <div><img src="https://picsum.photos/id/104/400/400"></div>
  <div>more and more content <br>here</div>
  <div>
    <h2>another title</h2>
  </div>
  <div><img src="https://picsum.photos/id/104/400/400"></div>
</div>
_x000D_
_x000D_
_x000D_

Using HTTPS with REST in Java

Here's the painful route:

    SSLContext ctx = null;
    try {
        KeyStore trustStore;
        trustStore = KeyStore.getInstance("JKS");
        trustStore.load(new FileInputStream("C:\\truststore_client"),
                "asdfgh".toCharArray());
        TrustManagerFactory tmf = TrustManagerFactory
                .getInstance("SunX509");
        tmf.init(trustStore);
        ctx = SSLContext.getInstance("SSL");
        ctx.init(null, tmf.getTrustManagers(), null);
    } catch (NoSuchAlgorithmException e1) {
        e1.printStackTrace();
    } catch (KeyStoreException e) {
        e.printStackTrace();
    } catch (CertificateException e) {
        e.printStackTrace();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (KeyManagementException e) {
        e.printStackTrace();
    }
    ClientConfig config = new DefaultClientConfig();
    config.getProperties().put(HTTPSProperties.PROPERTY_HTTPS_PROPERTIES,
            new HTTPSProperties(null, ctx));

    WebResource service = Client.create(config).resource(
            "https://localhost:9999/");
    service.addFilter(new HTTPBasicAuthFilter(username, password));

    // Attempt to view the user's page.
    try {
        service.path("user/" + username).get(String.class);
    } catch (Exception e) {
        e.printStackTrace();
    }

Gotta love those six different caught exceptions :). There are certainly some refactoring to simplify the code a bit. But, I like delfuego's -D options on the VM. I wish there was a javax.net.ssl.trustStore static property that I could just set. Just two lines of code and done. Anyone know where that would be?

This may be too much to ask, but, ideally the keytool would not be used. Instead, the trustedStore would be created dynamically by the code and the cert is added at runtime.

There must be a better answer.

CSS: how to get scrollbars for div inside container of fixed height

Code from the above answer by Dutchie432

.FixedHeightContainer {
    float:right;
    height: 250px;
    width:250px; 
    padding:3px; 
    background:#f00;
}

.Content {
    height:224px;
    overflow:auto;
    background:#fff;
}

basic authorization command for curl

Use the -H header again before the Authorization:Basic things. So it will be

curl -i \
    -H 'Accept:application/json' \
    -H 'Authorization:Basic BASE64_string' \
    http://example.com

Here, BASE64_string = Base64 of username:password

Lost connection to MySQL server during query?

I think you can use mysql_ping() function.

This function checks for connection to the server alive or not. if it fails then you can reconnect and proceed with your query.

Git Commit Messages: 50/72 Formatting

Regarding the “summary” line (the 50 in your formula), the Linux kernel documentation has this to say:

For these reasons, the "summary" must be no more than 70-75
characters, and it must describe both what the patch changes, as well
as why the patch might be necessary.  It is challenging to be both
succinct and descriptive, but that is what a well-written summary
should do.

That said, it seems like kernel maintainers do indeed try to keep things around 50. Here’s a histogram of the lengths of the summary lines in the git log for the kernel:

Lengths of Git summary lines (view full-sized)

There is a smattering of commits that have summary lines that are longer (some much longer) than this plot can hold without making the interesting part look like one single line. (There’s probably some fancy statistical technique for incorporating that data here but oh well… :-)

If you want to see the raw lengths:

cd /path/to/repo
git shortlog  | grep -e '^      ' | sed 's/[[:space:]]\+\(.*\)$/\1/' | awk '{print length($0)}'

or a text-based histogram:

cd /path/to/repo
git shortlog  | grep -e '^      ' | sed 's/[[:space:]]\+\(.*\)$/\1/' | awk '{lens[length($0)]++;} END {for (len in lens) print len, lens[len] }' | sort -n

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

You might give this a try:

@echo off

for /f %%a in (sample.txt) do (
  echo %%a
  exit /b
)

edit Or, say you have four columns of data and want from the 5th row down to the bottom, try this:

@echo off

for /f "skip=4 tokens=1-4" %%a in (junkl.txt) do (
  echo %%a %%b %%c %%d
)

Apply a theme to an activity in Android?

You can apply a theme to any activity by including android:theme inside <activity> inside manifest file.

For example:

  1. <activity android:theme="@android:style/Theme.Dialog">
  2. <activity android:theme="@style/CustomTheme">

And if you want to set theme programatically then use setTheme() before calling setContentView() and super.onCreate() method inside onCreate() method.

How get value from URL

There are two ways to get variable from URL in PHP:

When your URL is: http://www.example.com/index.php?id=7 you can get this id via $_GET['id'] or $_REQUEST['id'] command and store in $id variable.

Lest's take a look:

// url is www.example.com?id=7

//get id from url via $_GET['id'] command:
$id = $_GET['id']

same will be:

//get id from url via $_REQUEST['id'] command:
$id = $_REQUEST['id']

the difference is that variables can be passed to file via URL or via POST method.

if variable is passed through url, then you can get it with $_GET['variable_name'] or $_REQUEST['variable_name'] but if variable is posted, then you need to you $_POST['variable_name'] or $_REQUEST['variable_name']

So as you see $_REQUEST['variable_name'] can be used in both ways.

P.S: Also remember - never do like this: $results = mysql_query("SELECT * FROM next WHERE id=$id"); it may cause MySQL Injection and your database can be hacked.

Try to use:

$results = mysql_query("SELECT * FROM next WHERE id='".mysql_real_escape_string($id)."'");

how to reference a YAML "setting" from elsewhere in the same YAML file?

In some languages, you can use an alternative library, For example, tampax is an implementation of YAML handling variables:

const tampax = require('tampax');

const yamlString = `
dude:
  name: Arthur
weapon:
  favorite: Excalibur
  useless: knife
sentence: "{{dude.name}} use {{weapon.favorite}}. The goal is {{goal}}."`;

const r = tampax.yamlParseString(yamlString, { goal: 'to kill Mordred' });
console.log(r.sentence);

// output : "Arthur use Excalibur. The goal is to kill Mordred."

Editor's Note: poster is also the author of this package.

How to check if spark dataframe is empty?

For Spark 2.1.0, my suggestion would be to use head(n: Int) or take(n: Int) with isEmpty, whichever one has the clearest intent to you.

df.head(1).isEmpty
df.take(1).isEmpty

with Python equivalent:

len(df.head(1)) == 0  # or bool(df.head(1))
len(df.take(1)) == 0  # or bool(df.take(1))

Using df.first() and df.head() will both return the java.util.NoSuchElementException if the DataFrame is empty. first() calls head() directly, which calls head(1).head.

def first(): T = head()
def head(): T = head(1).head

head(1) returns an Array, so taking head on that Array causes the java.util.NoSuchElementException when the DataFrame is empty.

def head(n: Int): Array[T] = withAction("head", limit(n).queryExecution)(collectFromPlan)

So instead of calling head(), use head(1) directly to get the array and then you can use isEmpty.

take(n) is also equivalent to head(n)...

def take(n: Int): Array[T] = head(n)

And limit(1).collect() is equivalent to head(1) (notice limit(n).queryExecution in the head(n: Int) method), so the following are all equivalent, at least from what I can tell, and you won't have to catch a java.util.NoSuchElementException exception when the DataFrame is empty.

df.head(1).isEmpty
df.take(1).isEmpty
df.limit(1).collect().isEmpty

I know this is an older question so hopefully it will help someone using a newer version of Spark.

Use PHP to convert PNG to JPG with compression?

Do this to convert safely a PNG to JPG with the transparency in white.

$image = imagecreatefrompng($filePath);
$bg = imagecreatetruecolor(imagesx($image), imagesy($image));
imagefill($bg, 0, 0, imagecolorallocate($bg, 255, 255, 255));
imagealphablending($bg, TRUE);
imagecopy($bg, $image, 0, 0, 0, 0, imagesx($image), imagesy($image));
imagedestroy($image);
$quality = 50; // 0 = worst / smaller file, 100 = better / bigger file 
imagejpeg($bg, $filePath . ".jpg", $quality);
imagedestroy($bg);

PHP simple foreach loop with HTML

This will work although when embedding PHP in HTML it is better practice to use the following form:

<table>
    <?php foreach($array as $key=>$value): ?>
    <tr>
        <td><?= $key; ?></td>
    </tr>
    <?php endforeach; ?>
</table>

You can find the doc for the alternative syntax on PHP.net

Eclipse - Installing a new JRE (Java SE 8 1.8.0)

You can have many java versions in your system.

I think you should add the java 8 in yours JREs installed or edit.

Take a look my screen:

enter image description here

If you click in edit (check your java 8 path):

enter image description here

PHP decoding and encoding json with unicode characters

Judging from everything you've said, it seems like the original Odómetro string you're dealing with is encoded with ISO 8859-1, not UTF-8.

Here's why I think so:

  • json_encode produced parseable output after you ran the input string through utf8_encode, which converts from ISO 8859-1 to UTF-8.
  • You did say that you got "mangled" output when using print_r after doing utf8_encode, but the mangled output you got is actually exactly what would happen by trying to parse UTF-8 text as ISO 8859-1 (ó is \x63\xb3 in UTF-8, but that sequence is ó in ISO 8859-1.
  • Your htmlentities hackaround solution worked. htmlentities needs to know what the encoding of the input string to work correctly. If you don't specify one, it assumes ISO 8859-1. (html_entity_decode, confusingly, defaults to UTF-8, so your method had the effect of converting from ISO 8859-1 to UTF-8.)
  • You said you had the same problem in Python, which would seem to exclude PHP from being the issue.

PHP will use the \uXXXX escaping, but as you noted, this is valid JSON.

So, it seems like you need to configure your connection to Postgres so that it will give you UTF-8 strings. The PHP manual indicates you'd do this by appending options='--client_encoding=UTF8' to the connection string. There's also the possibility that the data currently stored in the database is in the wrong encoding. (You could simply use utf8_encode, but this will only support characters that are part of ISO 8859-1).

Finally, as another answer noted, you do need to make sure that you're declaring the proper charset, with an HTTP header or otherwise (of course, this particular issue might have just been an artifact of the environment where you did your print_r testing).

Responsive background image in div full width

Here is one way of getting the design that you want.

Start with the following HTML:

<div class="container">
    <div class="row-fluid">
        <div class="span12">
            <div class="nav">nav area</div>
            <div class="bg-image">
                <img src="http://unplugged.ee/wp-content/uploads/2013/03/frank2.jpg">
                 <h1>This is centered text.</h1>
            </div>
            <div class="main">main area</div>
        </div>
    </div>
</div>

Note that the background image is now part of the regular flow of the document.

Apply the following CSS:

.bg-image {
    position: relative;
}
.bg-image img {
    display: block;
    width: 100%;
    max-width: 1200px; /* corresponds to max height of 450px */
    margin: 0 auto;
}
.bg-image h1 {
    position: absolute;
    text-align: center;
    bottom: 0;
    left: 0;
    right: 0;
    color: white;
}
.nav, .main {
    background-color: #f6f6f6;
    text-align: center;
}

How This Works

The image is set an regular flow content with a width of 100%, so it will adjust itself responsively to the width of the parent container. However, you want the height to be no more than 450px, which corresponds to the image width of 1200px, so set the maximum width of the image to 1200px. You can keep the image centered by using display: block and margin: 0 auto.

The text is painted over the image by using absolute positioning. In the simplest case, I stretch the h1 element to be the full width of the parent and use text-align: center to center the text. Use the top or bottom offsets to place the text where it is needed.

If your banner images are going to vary in aspect ratio, you will need to adjust the maximum width value for .bg-image img dynamically using jQuery/Javascript, but otherwise, this approach has a lot to offer.

See demo at: http://jsfiddle.net/audetwebdesign/EGgaN/

Mongoose query where value is not null

Hello guys I am stucked with this. I've a Document Profile who has a reference to User,and I've tried to list the profiles where user ref is not null (because I already filtered by rol during the population), but after googleing a few hours I cannot figure out how to get this. I have this query:

const profiles = await Profile.find({ user: {$exists: true,  $ne: null }})
                            .select("-gallery")
                            .sort( {_id: -1} )
                            .skip( skip )
                            .limit(10)
                            .select(exclude)
                            .populate({
                                path: 'user',
                                match: { role: {$eq: customer}},
                                select: '-password -verified -_id -__v'
                              })

                            .exec();

And I get this result, how can I remove from the results the user:null colletions? . I meant, I dont want to get the profile when user is null (the role does not match).
{
    "code": 200,
    "profiles": [
        {
            "description": null,
            "province": "West Midlands",
            "country": "UK",
            "postal_code": "83000",
            "user": null
        },
        {
            "description": null,

            "province": "Madrid",
            "country": "Spain",
            "postal_code": "43000",
            "user": {
                "role": "customer",
                "name": "pedrita",
                "email": "[email protected]",
                "created_at": "2020-06-05T11:05:36.450Z"
            }
        }
    ],
    "page": 1
}

Thanks in advance.

How to add comments into a Xaml file in WPF?

You cannot put comments inside UWP XAML tags. Your syntax is right.

TO DO:

<xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:System="clr-namespace:System;assembly=mscorlib"/>
<!-- Cool comment -->

NOT TO DO:

<xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    <!-- Cool comment -->
xmlns:System="clr-namespace:System;assembly=mscorlib"/>

Python sum() function with list parameter

Have you used the variable sum anywhere else? That would explain it.

>>> sum = 1
>>> numbers = [1, 2, 3]
>>> numsum = (sum(numbers))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'int' object is not callable

The name sum doesn't point to the function anymore now, it points to an integer.

Solution: Don't call your variable sum, call it total or something similar.

How to turn on line numbers in IDLE?

If you are trying to track down which line caused an error, if you right-click in the Python shell where the line error is displayed it will come up with a "Go to file/line" which takes you directly to the line in question.

Android Webview gives net::ERR_CACHE_MISS message

I solved the problem by changing my AndroidManifest.xml.

old  : <uses-permission android:name="android.permission.internet"/>
new: <uses-permission android:name="android.permission.INTERNET"/>

No content to map due to end-of-input jackson parser

I got this error when sending a GET request with postman. The request required no parameters. My mistake was I had a blank line in the request body.

Tomcat in Intellij Idea Community Edition

If you are using maven, you can use this command mvn tomcat:run, but first you add in your pom.xml this structure into build tag, just like this:

<build>
    <finalName>mvn-webapp-test</finalName>
      <plugins>
          <plugin>
              <groupId>org.apache.maven.plugins</groupId>
              <artifactId>maven-compiler-plugin</artifactId>
              <version>${maven.compiler.plugin.version}</version>
              <configuration>
                  <source>1.6</source>
                  <target>1.6</target>
              </configuration>
          </plugin>
      </plugins>
  </build>

Python read JSON file and modify

There is really quite a number of ways to do this and all of the above are in one way or another valid approaches... Let me add a straightforward proposition. So assuming your current existing json file looks is this....

{
     "name":"myname"
}

And you want to bring in this new json content (adding key "id")

{
     "id": "134",
     "name": "myname"
 }

My approach has always been to keep the code extremely readable with easily traceable logic. So first, we read the entire existing json file into memory, assuming you are very well aware of your json's existing key(s).

import json 

# first, get the absolute path to json file
PATH_TO_JSON = 'data.json' #  assuming same directory (but you can work your magic here with os.)

# read existing json to memory. you do this to preserve whatever existing data. 
with open(PATH_TO_JSON,'r') as jsonfile:
    json_content = json.load(jsonfile) # this is now in memory! you can use it outside 'open'

Next, we use the 'with open()' syntax again, with the 'w' option. 'w' is a write mode which lets us edit and write new information to the file. Here s the catch that works for us ::: any existing json with the same target write name will be erased automatically.

So what we can do now, is simply write to the same filename with the new data

# add the id key-value pair (rmbr that it already has the "name" key value)
json_content["id"] = "134"

with open(PATH_TO_JSON,'w') as jsonfile:
    json.dump(json_content, jsonfile, indent=4) # you decide the indentation level

And there you go! data.json should be good to go for an good old POST request

Removing duplicates from a SQL query (not just "use distinct")

Your question is kind of confusing; do you want to show only one row per user, or do you want to show a row per picture but suppress repeating values in the U.NAME field? I think you want the second; if not there are plenty of answers for the first.

Whether to display repeating values is display logic, which SQL wasn't really designed for. You can use a cursor in a loop to process the results row-by-row, but you will lose a lot of performance. If you have a "smart" frontend language like a .NET language or Java, whatever construction you put this data into can be cheaply manipulated to suppress repeating values before finally displaying it in the UI.

If you're using Microsoft SQL Server, and the transformation HAS to be done at the data layer, you may consider using a CTE (Computed Table Expression) to hold the initial query, then select values from each row of the CTE based on whether the columns in the previous row hold the same data. It'll be more performant than the cursor, but it'll be kinda messy either way. Observe:

USING CTE (Row, Name, PicID)
AS
(
    SELECT ROW_NUMBER() OVER (ORDER BY U.NAME, P.PIC_ID),
       U.NAME, P.PIC_ID
    FROM USERS U
        INNER JOIN POSTINGS P1
            ON U.EMAIL_ID = P1.EMAIL_ID
        INNER JOIN PICTURES P
            ON P1.PIC_ID = P.PIC_ID
    WHERE P.CAPTION LIKE '%car%'
    ORDER BY U.NAME, P.PIC_ID 
)
SELECT
    CASE WHEN current.Name == previous.Name THEN '' ELSE current.Name END,
    current.PicID
FROM CTE current
LEFT OUTER JOIN CTE previous
   ON current.Row = previous.Row + 1
ORDER BY current.Row

The above sample is TSQL-specific; it is not guaranteed to work in any other DBPL like PL/SQL, but I think most of the enterprise-level SQL engines have something similar.

Very simple log4j2 XML configuration file using Console and File appender

log4j2 has a very flexible configuration system (which IMHO is more a distraction than a help), you can even use JSON. See https://logging.apache.org/log4j/2.x/manual/configuration.html for a reference.

Personally, I just recently started using log4j2, but I'm tending toward the "strict XML" configuration (that is, using attributes instead of element names), which can be schema-validated.

Here is my simple example using autoconfiguration and strict mode, using a "Property" for setting the filename:

<?xml version="1.0" encoding="UTF-8"?>
<Configuration monitorinterval="30" status="info" strict="true">
    <Properties>
        <Property name="filename">log/CelsiusConverter.log</Property>
    </Properties>
    <Appenders>
        <Appender type="Console" name="Console">
            <Layout type="PatternLayout" pattern="%d %p [%t] %m%n" />
        </Appender>
        <Appender type="Console" name="FLOW">
            <Layout type="PatternLayout" pattern="%C{1}.%M %m %ex%n" />
        </Appender>
        <Appender type="File" name="File" fileName="${filename}">
            <Layout type="PatternLayout" pattern="%d %p %C{1.} [%t] %m%n" />
        </Appender>
    </Appenders>
    <Loggers>
        <Root level="debug">
            <AppenderRef ref="File" />
            <AppenderRef ref="Console" />
            <!-- Use FLOW to trace down exact method sending the msg -->
            <!-- <AppenderRef ref="FLOW" /> -->
        </Root>
    </Loggers>
</Configuration>

How can I format a nullable DateTime with ToString()?

IFormattable also includes a format provider that can be used, it allows both format of IFormatProvider to be null in dotnet 4.0 this would be

/// <summary>
/// Extentionclass for a nullable structs
/// </summary>
public static class NullableStructExtensions {

    /// <summary>
    /// Formats a nullable struct
    /// </summary>
    /// <param name="source"></param>
    /// <param name="format">The format string 
    /// If <c>null</c> use the default format defined for the type of the IFormattable implementation.</param>
    /// <param name="provider">The format provider 
    /// If <c>null</c> the default provider is used</param>
    /// <param name="defaultValue">The string to show when the source is <c>null</c>. 
    /// If <c>null</c> an empty string is returned</param>
    /// <returns>The formatted string or the default value if the source is <c>null</c></returns>
    public static string ToString<T>(this T? source, string format = null, 
                                     IFormatProvider provider = null, 
                                     string defaultValue = null) 
                                     where T : struct, IFormattable {
        return source.HasValue
                   ? source.Value.ToString(format, provider)
                   : (String.IsNullOrEmpty(defaultValue) ? String.Empty : defaultValue);
    }
}

using together with named parameters you can do:

dt2.ToString(defaultValue: "n/a");

In older versions of dotnet you get a lot of overloads

/// <summary>
/// Extentionclass for a nullable structs
/// </summary>
public static class NullableStructExtensions {

    /// <summary>
    /// Formats a nullable struct
    /// </summary>
    /// <param name="source"></param>
    /// <param name="format">The format string 
    /// If <c>null</c> use the default format defined for the type of the IFormattable implementation.</param>
    /// <param name="provider">The format provider 
    /// If <c>null</c> the default provider is used</param>
    /// <param name="defaultValue">The string to show when the source is <c>null</c>. 
    /// If <c>null</c> an empty string is returned</param>
    /// <returns>The formatted string or the default value if the source is <c>null</c></returns>
    public static string ToString<T>(this T? source, string format, 
                                     IFormatProvider provider, string defaultValue) 
                                     where T : struct, IFormattable {
        return source.HasValue
                   ? source.Value.ToString(format, provider)
                   : (String.IsNullOrEmpty(defaultValue) ? String.Empty : defaultValue);
    }

    /// <summary>
    /// Formats a nullable struct
    /// </summary>
    /// <param name="source"></param>
    /// <param name="format">The format string 
    /// If <c>null</c> use the default format defined for the type of the IFormattable implementation.</param>
    /// <param name="defaultValue">The string to show when the source is null. If <c>null</c> an empty string is returned</param>
    /// <returns>The formatted string or the default value if the source is <c>null</c></returns>
    public static string ToString<T>(this T? source, string format, string defaultValue) 
                                     where T : struct, IFormattable {
        return ToString(source, format, null, defaultValue);
    }

    /// <summary>
    /// Formats a nullable struct
    /// </summary>
    /// <param name="source"></param>
    /// <param name="format">The format string 
    /// If <c>null</c> use the default format defined for the type of the IFormattable implementation.</param>
    /// <param name="provider">The format provider (if <c>null</c> the default provider is used)</param>
    /// <returns>The formatted string or an empty string if the source is <c>null</c></returns>
    public static string ToString<T>(this T? source, string format, IFormatProvider provider)
                                     where T : struct, IFormattable {
        return ToString(source, format, provider, null);
    }

    /// <summary>
    /// Formats a nullable struct or returns an empty string
    /// </summary>
    /// <param name="source"></param>
    /// <param name="format">The format string 
    /// If <c>null</c> use the default format defined for the type of the IFormattable implementation.</param>
    /// <returns>The formatted string or an empty string if the source is null</returns>
    public static string ToString<T>(this T? source, string format)
                                     where T : struct, IFormattable {
        return ToString(source, format, null, null);
    }

    /// <summary>
    /// Formats a nullable struct
    /// </summary>
    /// <param name="source"></param>
    /// <param name="provider">The format provider (if <c>null</c> the default provider is used)</param>
    /// <param name="defaultValue">The string to show when the source is <c>null</c>. If <c>null</c> an empty string is returned</param>
    /// <returns>The formatted string or the default value if the source is <c>null</c></returns>
    public static string ToString<T>(this T? source, IFormatProvider provider, string defaultValue)
                                     where T : struct, IFormattable {
        return ToString(source, null, provider, defaultValue);
    }

    /// <summary>
    /// Formats a nullable struct or returns an empty string
    /// </summary>
    /// <param name="source"></param>
    /// <param name="provider">The format provider (if <c>null</c> the default provider is used)</param>
    /// <returns>The formatted string or an empty string if the source is <c>null</c></returns>
    public static string ToString<T>(this T? source, IFormatProvider provider)
                                     where T : struct, IFormattable {
        return ToString(source, null, provider, null);
    }

    /// <summary>
    /// Formats a nullable struct or returns an empty string
    /// </summary>
    /// <param name="source"></param>
    /// <returns>The formatted string or an empty string if the source is <c>null</c></returns>
    public static string ToString<T>(this T? source) 
                                     where T : struct, IFormattable {
        return ToString(source, null, null, null);
    }
}

What does -z mean in Bash?

-z

string is null, that is, has zero length

String=''   # Zero-length ("null") string variable.

if [ -z "$String" ]
then
  echo "\$String is null."
else
  echo "\$String is NOT null."
fi     # $String is null.

How to upgrade safely php version in wamp server

To add to the above answer (do steps 1-5).

  1. Click on WAMP -> Select PHP -> Versions: Select the new version installed
  2. Check that your PATH folder is updated to new path to PHP so your OS has same PHP version of WAMP.

How to set up file permissions for Laravel?

I found an even better solution to this. Its caused because php is running as another user by default.

so to fix this do

sudo nano /etc/php/7.0/fpm/pool.d/www.conf

then edit the user = "put user that owns the directories" group = "put user that owns the directories"

then:

sudo systemctl reload php7.0-fpm

Using union and count(*) together in SQL query

Is your goal...

  1. To count all the instances of "Bob Jones" in both tables (for example)
  2. To count all the instances of "Bob Jones" in Results in one row and all the instances of "Bob Jones" in Archive_Results in a separate row?

Assuming it's #1 you'd want something like...

SELECT name, COUNT(*) FROM
(SELECT name FROM Results UNION ALL SELECT name FROM Archive_Results)
GROUP BY name
ORDER BY name

How do you log content of a JSON object in Node.js?

This will for most of the objects for outputting in nodejs console

_x000D_
_x000D_
var util = require('util')_x000D_
function print (data){_x000D_
  console.log(util.inspect(data,true,12,true))_x000D_
  _x000D_
}_x000D_
_x000D_
print({name : "Your name" ,age : "Your age"})
_x000D_
_x000D_
_x000D_

How to label each equation in align environment?

\tag also works in align*. Example:

\begin{align*}
  a(x)^{2} &= bx\tag{1}\\ 
  a(x)^{2} &= b\tag{2}\\ 
  ax &= b\tag{3}\\ 
  a(x)^{2}+bx &= c\tag{4}\\ 
  a(x)^{2}+c &= bx\tag{5}\\ 
  a(x)^{2} &= bx+c\tag{6}\\ \\ 
  Where\quad a, b, c \, \in N
\end{align*}

Output:

PDF output for \tag example

HTTPS setup in Amazon EC2

One of the best resources I found was using let's encrypt, you do not need ELB nor cloudfront for your EC2 instance to have HTTPS, just follow the following simple instructions: let's encrypt Login to your server and follow the steps in the link.

It is also important as mentioned by others that you have port 443 opened by editing your security groups

You can view your certificate or any other website's by changing the site name in this link

Please do not forget that it is only valid for 90 days

executing shell command in background from script

This works because the it's a static variable. You could do something much cooler like this:

filename="filename"
extension="txt"
for i in {1..20}; do
    eval "filename${i}=${filename}${i}.${extension}"
    touch filename${i}
    echo "this rox" > filename${i}
done

This code will create 20 files and dynamically set 20 variables. Of course you could use an array, but I'm just showing you the feature :). Note that you can use the variables $filename1, $filename2, $filename3... because they were created with evaluate command. In this case I'm just creating files, but you could use to create dynamically arguments to the commands, and then execute in background.

Using "Object.create" instead of "new"

Object.create is not yet standard on several browsers, for example IE8, Opera v11.5, Konq 4.3 do not have it. You can use Douglas Crockford's version of Object.create for those browsers but this doesn't include the second 'initialisation object' parameter used in CMS's answer.

For cross browser code one way to get object initialisation in the meantime is to customise Crockford's Object.create. Here is one method:-

Object.build = function(o) {
   var initArgs = Array.prototype.slice.call(arguments,1)
   function F() {
      if((typeof o.init === 'function') && initArgs.length) {
         o.init.apply(this,initArgs)
      }
   }
   F.prototype = o
   return new F()
}

This maintains Crockford prototypal inheritance, and also checks for any init method in the object, then runs it with your parameter(s), like say new man('John','Smith'). Your code then becomes:-

MY_GLOBAL = {i: 1, nextId: function(){return this.i++}}  // For example

var userB = {
    init: function(nameParam) {
        this.id = MY_GLOBAL.nextId();
        this.name = nameParam;
    },
    sayHello: function() {
        console.log('Hello '+ this.name);
    }
};
var bob = Object.build(userB, 'Bob');  // Different from your code
bob.sayHello();

So bob inherits the sayHello method and now has own properties id=1 and name='Bob'. These properties are both writable and enumerable of course. This is also a much simpler way to initialise than for ECMA Object.create especially if you aren't concerned about the writable, enumerable and configurable attributes.

For initialisation without an init method the following Crockford mod could be used:-

Object.gen = function(o) {
   var makeArgs = arguments 
   function F() {
      var prop, i=1, arg, val
      for(prop in o) {
         if(!o.hasOwnProperty(prop)) continue
         val = o[prop]
         arg = makeArgs[i++]
         if(typeof arg === 'undefined') break
         this[prop] = arg
      }
   }
   F.prototype = o
   return new F()
}

This fills the userB own properties, in the order they are defined, using the Object.gen parameters from left to right after the userB parameter. It uses the for(prop in o) loop so, by ECMA standards, the order of property enumeration cannot be guaranteed the same as the order of property definition. However, several code examples tested on (4) major browsers show they are the same, provided the hasOwnProperty filter is used, and sometimes even if not.

MY_GLOBAL = {i: 1, nextId: function(){return this.i++}};  // For example

var userB = {
   name: null,
   id: null,
   sayHello: function() {
      console.log('Hello '+ this.name);
   }
}

var bob = Object.gen(userB, 'Bob', MY_GLOBAL.nextId());

Somewhat simpler I would say than Object.build since userB does not need an init method. Also userB is not specifically a constructor but looks like a normal singleton object. So with this method you can construct and initialise from normal plain objects.

C# Parsing JSON array of objects

Use NewtonSoft JSON.Net library.

dynamic obj = Newtonsoft.Json.JsonConvert.DeserializeObject(jsonString);

Hope this helps.

Making macOS Installer Packages which are Developer ID ready

A +1 to accepted answer:

Destination Selection in Installer

If domain (a.k.a destination) selection is desired between user domain and system domain then rather than trying <domains enable_anywhere="true"> use following:

<domains enable_currentUserHome="true" enable_localSystem="true"/>

enable_currentUserHome installs application app under ~/Applications/ and enable_localSystem allows the application to be installed under /Application

I've tried this in El Capitan 10.11.6 (15G1217) and it seems to be working perfectly fine in 1 dev machine and 2 different VMs I tried.

Why an interface can not implement another interface?

Hope this will help you a little what I have learned in oops (core java) during my college.

Implements denotes defining an implementation for the methods of an interface. However interfaces have no implementation so that's not possible. An interface can however extend another interface, which means it can add more methods and inherit its type.

Here is an example below, this is my understanding and what I have learnt in oops.

interface ParentInterface{  
        void myMethod();  
}  

interface SubInterface extends ParentInterface{  
        void anotherMethod();  
}  

and keep one thing in a mind one interface can only extend another interface and if you want to define it's function on some class then only a interface in implemented eg below

public interface Dog
{
    public boolean Barks();

    public boolean isGoldenRetriever();
}

Now, if a class were to implement this interface, this is what it would look like:

public class SomeClass implements Dog
{
    public boolean Barks{
    // method definition here

    }

    public boolean isGoldenRetriever{
    // method definition here
    }
}

and if a abstract class has some abstract function define and declare and you want to define those function or you can say implement those function then you suppose to extends that class because abstract class can only be extended. here is example below.

public abstract class MyAbstractClass {

    public abstract void abstractMethod();
}

Here is an example subclass of MyAbstractClass:

public class MySubClass extends MyAbstractClass {

    public void abstractMethod() {
        System.out.println("My method implementation");
    }
}

Excel 2013 VBA Clear All Filters macro

This thread is ancient, but I wasn't happy with any of the given answers, and ended up writing my own. I'm sharing it now:

We start with:

  Sub ResetWSFilters(ws as worksheet)
             If ws.FilterMode Then   
     ws.ShowAllData   
     Else   
     End If  
    'This gets rid of "normal" filters - but tables will remain filtered
    For Each listObj In ws.ListObjects 
               If listObj.ShowHeaders Then   
                    listObj.AutoFilter.ShowAllData
                    listObj.Sort.SortFields.Clear    
               End If     
       Next listObj
        'And this gets rid of table filters
        End Sub

We can feed a specific worksheet to this macro which will unfilter just that one worksheet. Useful if you need to make sure just one worksheet is clear. However, I usually want to do the entire workbook

Sub ResetAllWBFilters(wb as workbook)
  Dim ws As Worksheet  
  Dim wb As Workbook  
  Dim listObj As ListObject    

       For Each ws In wb.Worksheets  
          If ws.FilterMode Then 
          ws.ShowAllData  
          Else   
          End If   
 'This removes "normal" filters in the workbook - however, it doesn't remove table filters           
   For Each listObj In ws.ListObjects 
        If listObj.ShowHeaders Then   
             listObj.AutoFilter.ShowAllData 
             listObj.Sort.SortFields.Clear    
        End If     
   Next listObj

        Next   
'And this removes table filters. You need both aspects to make it work.  
    End Sub

You can use this, by, for example, opening a workbook you need to deal with and resetting their filters before doing anything with it:

Sub ExampleOpen()
Set TestingWorkBook = Workbooks.Open("C:\Intel\......") 'The .open is assuming you need to open the workbook in question - different procedure if it's already open
Call ResetAllWBFilters(TestingWorkBook)
End Sub

The one I use the most: Resetting all filters in the workbook that the module is stored in:

Sub ResetFilters()
      Dim ws As Worksheet  
      Dim wb As Workbook  
      Dim listObj As ListObject  
       Set wb = ThisWorkbook  
       'Set wb = ActiveWorkbook
       'This is if you place the macro in your personal wb to be able to reset the filters on any wb you're currently working on. Remove the set wb = thisworkbook if that's what you need
           For Each ws In wb.Worksheets  
              If ws.FilterMode Then 
              ws.ShowAllData  
              Else   
              End If   
     'This removes "normal" filters in the workbook - however, it doesn't remove table filters           
       For Each listObj In ws.ListObjects 
            If listObj.ShowHeaders Then   
                 listObj.AutoFilter.ShowAllData 
                 listObj.Sort.SortFields.Clear    
            End If     
       Next listObj

            Next   
'And this removes table filters. You need both aspects to make it work.  
    End Sub

Switch statement equivalent in Windows batch file

Try by this way. To perform some list of operations like

  1. Switch case has been used.
  2. Checking the conditional statements.
  3. Invoking the function with more than two arguments.

 @echo off
 :Start2 
    cls
    goto Start
    :Start
    echo --------------------------------------
    echo     Welcome to the Shortcut tool     
    echo --------------------------------------            
    echo Choose from the list given below:
    echo [1] 2017
    echo [2] 2018
    echo [3] Task

    set /a one=1
    set /a two=2
    set /a three=3
    set /a four=4
    set input=
    set /p input= Enter your choice:
    if %input% equ %one% goto Z if NOT goto Start2
    if %input% equ %two% goto X if NOT goto Start2
    if %input% equ %three% goto C if NOT goto Start2
    if %input% geq %four% goto N

    :Z
    cls
    echo You have selected year : 2017
    set year=2017
    echo %year%
    call:branches year

    pause
    exit

    :X
    cls
    echo You have selected year : 2018
    set year=2018
    echo %year%
    call:branches year
    pause
    exit

    :C  
    cls
    echo You have selected Task
    call:Task
    pause
    exit

    :N
    cls
    echo Invalid Selection! Try again
    pause
    goto :start2




    :branches
    cls
    echo Choose from the list of Branches given below:
    echo [1] January
    echo [2] Feburary
    echo [3] March
    SETLOCAL
    set /a "Number1=%~1"
    set input=
    set /p input= Enter your choice:
    set /a b=0
    set /a bd=3
    set /a bdd=4
    if %input% equ %b% goto N
    if %input% leq %bd% call:Z1 Number1,input if NOT goto Start2
    if %input% geq %bdd% goto N



    :Z1
    cls
    SETLOCAL
    set /a "Number1=%~1"
    echo year = %Number1%
    set /a "Number2=%~2"
    echo branch = %Number2%
    call:operation Number1,Number2
    pause
    GOTO :EOF


    :operation
    cls
    echo Choose from the list of Operation given below:
    echo [1] UB
    echo [3] B
    echo [4] C
    echo [5] l
    echo [6] R
    echo [7] JT
    echo [8] CT
    echo [9] JT
    SETLOCAL
    set /a "year=%~1"
    echo Your have selected year = %year%
    set /a "month=%~2"
    echo You have selected Branch = %month%
    set operation=
    set /p operation= Enter your choice:
    set /a b=0
    set /a bd=9
    set /a bdd=10
    if %input% equ %b% goto N
    if %operation% leq %bd% goto :switch-case-N-%operation% if NOT goto Start2
    if %input% geq %bdd% goto N




    :switch-case-N-1
    echo Januray
    echo %year%,%month%,%operation%
    goto :switch-case-end

    :switch-case-N-2
    echo Feburary
    echo %year%,%month%,%operation%
    goto :switch-case-end

    :switch-case-N-3
    echo march
    echo %year%,%month%,%operation%
    goto :switch-case-end

    :switch-case-end
       echo Task Completed
       pause
       exit
       goto :start2






    :Task
    cls
    echo Choose from the list of Operation given below:
    echo [1] UB
    echo [3] B
    echo [4] C
    echo [5] l
    echo [6] R
    echo [7] JT
    echo [8] CT
    echo [9] JT
    SETLOCAL
    set operation=
    set /p operation= Enter your choice:
    set /a b=0
    set /a bd=9
    set /a bdd=10
    if %input% equ %b% goto N
    if %operation% leq %bd% goto :switch-case-N-%operation% if NOT goto Start2
    if %input% geq %bdd% goto N




    :switch-case-N-1
    echo Januray
    echo %operation%
    goto :switch-case-end

    :switch-case-N-2
    echo Feburary
    echo %year%,%month%,%operation%
    goto :switch-case-end

    :switch-case-N-3
    echo march
    echo %year%,%month%,%operation%
    goto :switch-case-end

    :switch-case-end
       echo Task Completed
       pause
       exit
       goto :start2

How to schedule a function to run every hour on Flask?

You could try using APScheduler's BackgroundScheduler to integrate interval job into your Flask app. Below is the example that uses blueprint and app factory (init.py) :

from datetime import datetime

# import BackgroundScheduler
from apscheduler.schedulers.background import BackgroundScheduler
from flask import Flask

from webapp.models.main import db 
from webapp.controllers.main import main_blueprint    

# define the job
def hello_job():
    print('Hello Job! The time is: %s' % datetime.now())

def create_app(object_name):
    app = Flask(__name__)
    app.config.from_object(object_name)
    db.init_app(app)
    app.register_blueprint(main_blueprint)
    # init BackgroundScheduler job
    scheduler = BackgroundScheduler()
    # in your case you could change seconds to hours
    scheduler.add_job(hello_job, trigger='interval', seconds=3)
    scheduler.start()

    try:
        # To keep the main thread alive
        return app
    except:
        # shutdown if app occurs except 
        scheduler.shutdown()

Hope it helps :)

Ref :

  1. https://github.com/agronholm/apscheduler/blob/master/examples/schedulers/background.py

Can a CSV file have a comment?

A Comma Separated File is really just a text file where the lines consist of values separated by commas.

There is no standard which defines the contents of a CSV file, so there is no defined way of indicating a comment. It depends on the program which will be importing the CSV file.

Of course, this is usually Excel. You should ask yourself how does Excel define a comment? In other words, what would make Excel ignore a line (or part of a line) in the CSV file? I'm not aware of anything which would do this.

How do you keep parents of floated elements from collapsing?

The main problem you may find with changing overflow to auto or hidden is that everything can become scrollable with the middle mouse buttom and a user can mess up the entire site layout.

nginx 502 bad gateway

When I did sudo /etc/init.d/php-fpm start I got the following error:

Starting php-fpm: [28-Mar-2013 16:18:16] ERROR: [pool www] cannot get uid for user 'apache'

I guess /etc/php-fpm.d/www.conf needs to know the user that the webserver is running as and assumes it's apache when, for nginx, it's actually nginx, and needs to be changed.

Best way to remove duplicate entries from a data table

    /* To eliminate Duplicate rows */
    private void RemoveDuplicates(DataTable dt)
    {

        if (dt.Rows.Count > 0)
        {
            for (int i = dt.Rows.Count - 1; i >= 0; i--)
            {
                if (i == 0)
                {
                    break;
                }
                for (int j = i - 1; j >= 0; j--)
                {
                    if (Convert.ToInt32(dt.Rows[i]["ID"]) == Convert.ToInt32(dt.Rows[j]["ID"]) && dt.Rows[i]["Name"].ToString() == dt.Rows[j]["Name"].ToString())
                    {
                        dt.Rows[i].Delete();
                        break;
                    }
                }
            }
            dt.AcceptChanges();
        }
    }

How to revert a merge commit that's already pushed to remote branch?

If you want to revert a merge commit, here is what you have to do.

  1. First, check the git log to find your merge commit's id. You'll also find multiple parent ids associated with the merge (see image below).

enter image description here

Note down the merge commit id shown in yellow. The parent IDs are the ones written in the next line as Merge: parent1 parent2. Now...

Short Story:

  1. Switch to branch on which the merge was made. Then Just do the git revert <merge commit id> -m 1 which will open a vi console for entering commit message. Write, save, exit, done!

Long story:

  1. Switch to branch on which the merge was made. In my case, it is the test branch and I'm trying to remove the feature/analytics-v3 branch from it.

  2. git revert is the command which reverts any commit. But there is a nasty trick when reverting a merge commit. You need to enter the -m flag otherwise it will fail. From here on, you need to decide whether you want to revert your branch and make it look like exactly it was on parent1 or parent2 via:

git revert <merge commit id> -m 1 (reverts to parent2)

git revert <merge commit id> -m 2 (reverts to parent1)

You can git log these parents to figure out which way you want to go and that's the root of all the confusion.

Should I always use a parallel stream when possible?

Other answers have already covered profiling to avoid premature optimization and overhead cost in parallel processing. This answer explains the ideal choice of data structures for parallel streaming.

As a rule, performance gains from parallelism are best on streams over ArrayList , HashMap , HashSet , and ConcurrentHashMap instances; arrays; int ranges; and long ranges. What these data structures have in common is that they can all be accurately and cheaply split into subranges of any desired sizes, which makes it easy to divide work among parallel threads. The abstraction used by the streams library to perform this task is the spliterator , which is returned by the spliterator method on Stream and Iterable.

Another important factor that all of these data structures have in common is that they provide good-to-excellent locality of reference when processed sequentially: sequential element references are stored together in memory. The objects referred to by those references may not be close to one another in memory, which reduces locality-of-reference. Locality-of-reference turns out to be critically important for parallelizing bulk operations: without it, threads spend much of their time idle, waiting for data to be transferred from memory into the processor’s cache. The data structures with the best locality of reference are primitive arrays because the data itself is stored contiguously in memory.

Source: Item #48 Use Caution When Making Streams Parallel, Effective Java 3e by Joshua Bloch

Use Robocopy to copy only changed files?

Looks like /e option is what you need, it'll skip same files/directories.

robocopy c:\data c:\backup /e

If you run the command twice, you'll see the second round is much faster since it skips a lot of things.

how to create a logfile in php?

Please check with this documentation.

http://php.net/manual/en/function.error-log.php

Example:

<?php
// Send notification through the server log if we can not
// connect to the database.
if (!Ora_Logon($username, $password)) {
    error_log("Oracle database not available!", 0);
}

// Notify administrator by email if we run out of FOO
if (!($foo = allocate_new_foo())) {
    error_log("Big trouble, we're all out of FOOs!", 1,
               "[email protected]");
}

// another way to call error_log():
error_log("You messed up!", 3, "/var/tmp/my-errors.log");
?>

What is LD_LIBRARY_PATH and how to use it?

Typically you must set java.library.path on the JVM's command line:

java -Djava.library.path=/path/to/my/dll -cp /my/classpath/goes/here MainClass

Convert Xml to DataTable

How To Read XML Data into a DataSet by Using Visual C# .NET contains some details. Basically, you can use the overloaded DataSet method ReadXml to get the data into a DataSet. Your XML data will be in the first DataTable there.

There is also a DataTable.ReadXml method.

When should I use a List vs a LinkedList

In most cases, List<T> is more useful. LinkedList<T> will have less cost when adding/removing items in the middle of the list, whereas List<T> can only cheaply add/remove at the end of the list.

LinkedList<T> is only at it's most efficient if you are accessing sequential data (either forwards or backwards) - random access is relatively expensive since it must walk the chain each time (hence why it doesn't have an indexer). However, because a List<T> is essentially just an array (with a wrapper) random access is fine.

List<T> also offers a lot of support methods - Find, ToArray, etc; however, these are also available for LinkedList<T> with .NET 3.5/C# 3.0 via extension methods - so that is less of a factor.

How can I make a weak protocol reference in 'pure' Swift (without @objc)

You need to declare the type of the protocol as AnyObject.

protocol ProtocolNameDelegate: AnyObject {
    // Protocol stuff goes here
}

class SomeClass {
    weak var delegate: ProtocolNameDelegate?
}

Using AnyObject you say that only classes can conform to this protocol, whereas structs or enums can't.

Highlight Bash/shell code in Markdown files

Per the documentation from GitHub regarding GFM syntax highlighted code blocks

We use Linguist to perform language detection and syntax highlighting. You can find out which keywords are valid in the languages YAML file.

Rendered on GitHub, console makes the lines after the console blue. bash, sh, or shell don't seem to "highlight" much ...and you can use posh for PowerShell or CMD.

Typescript interface default values

Default values to an interface are not possible because interfaces only exists at compile time.

Alternative solution:

You could use a factory method for this which returns an object which implements the XI interface.

Example:

class AnotherType {}

interface IX {
    a: string,
    b: any,
    c: AnotherType | null
}

function makeIX (): IX {
    return {
    a: 'abc',
    b: null,
    c: null
    }
}

const x = makeIX();

x.a = 'xyz';
x.b = 123;
x.c = new AnotherType();

The only thing I changed with regard to your example is made the property c both AnotherType | null. Which will be necessary to not have any compiler errors (This error was also present in your example were you initialized null to property c).

How can I add a box-shadow on one side of an element?

This could be a simple way

border-right : 1px solid #ddd;
height:85px;    
box-shadow : 10px 0px 5px 1px #eaeaea;

Assign this to any div

Component is not part of any NgModule or the module has not been imported into your module

My case is same as @7guyo mentioned. I'm using lazyloading and was unconsiously doing this:

import { component1Route } from './path/component1.route';

export const entityState: Routes = [
{
   path: 'home',
   children: component1Route
}]

Instead of:

@NgModule({
imports: [
   RouterModule.forChild([
   {
     path: '',
     loadChildren: () => import('./component1/component1.module').then(m => m.ComponentOneModule)
  },
  {
    path: '',
    loadChildren: () => import('./component2/component2.module').then(m => m.ComponentTwoModule)
  }])
  ]})

  export class MainModule {}

Visual Studio debugger error: Unable to start program Specified file cannot be found

I had the same problem :) Verify the "Source code" folder on the "Solution Explorer", if it doesn't contain any "source code" file then :

Right click on "Source code" > Add > Existing Item > Choose the file You want to build and run.

Good luck ;)

How do you change the server header returned by nginx?

Like Apache, this is a quick edit to the source and recompile. From Calomel.org:

The Server: string is the header which is sent back to the client to tell them what type of http server you are running and possibly what version. This string is used by places like Alexia and Netcraft to collect statistics about how many and of what type of web server are live on the Internet. To support the author and statistics for Nginx we recommend keeping this string as is. But, for security you may not want people to know what you are running and you can change this in the source code. Edit the source file src/http/ngx_http_header_filter_module.c at look at lines 48 and 49. You can change the String to anything you want.

## vi src/http/ngx_http_header_filter_module.c (lines 48 and 49)
static char ngx_http_server_string[] = "Server: MyDomain.com" CRLF;
static char ngx_http_server_full_string[] = "Server: MyDomain.com" CRLF;

March 2011 edit: Props to Flavius below for pointing out a new option, replacing Nginx's standard HttpHeadersModule with the forked HttpHeadersMoreModule. Recompiling the standard module is still the quick fix, and makes sense if you want to use the standard module and won't be changing the server string often. But if you want more than that, the HttpHeadersMoreModule is a strong project and lets you do all sorts of runtime black magic with your HTTP headers.

How do I detect unsigned integer multiply overflow?

To perform an unsigned multiplication without overflowing in a portable way the following can be used:

... /* begin multiplication */
unsigned multiplicand, multiplier, product, productHalf;
int zeroesMultiplicand, zeroesMultiplier;
zeroesMultiplicand = number_of_leading_zeroes( multiplicand );
zeroesMultiplier   = number_of_leading_zeroes( multiplier );
if( zeroesMultiplicand + zeroesMultiplier <= 30 ) goto overflow;
productHalf = multiplicand * ( c >> 1 );
if( (int)productHalf < 0 ) goto overflow;
product = productHalf * 2;
if( multiplier & 1 ){
   product += multiplicand;
   if( product < multiplicand ) goto overflow;
}
..../* continue code here where "product" is the correct product */
....
overflow: /* put overflow handling code here */

int number_of_leading_zeroes( unsigned value ){
   int ctZeroes;
   if( value == 0 ) return 32;
   ctZeroes = 1;
   if( ( value >> 16 ) == 0 ){ ctZeroes += 16; value = value << 16; }
   if( ( value >> 24 ) == 0 ){ ctZeroes +=  8; value = value <<  8; }
   if( ( value >> 28 ) == 0 ){ ctZeroes +=  4; value = value <<  4; }
   if( ( value >> 30 ) == 0 ){ ctZeroes +=  2; value = value <<  2; }
   ctZeroes -= x >> 31;
   return ctZeroes;
}

How to write some data to excel file(.xlsx)

just follow below steps:

//Start Excel and get Application object.

oXL = new Microsoft.Office.Interop.Excel.Application();

oXL.Visible = false;

Jenkins pipeline if else not working

        if ( params.build_deploy == '1' ) {
            println "build_deploy ? ${params.build_deploy}"
              jobB = build job: 'k8s-core-user_deploy', propagate: false, wait: true, parameters: [
                         string(name:'environment', value: "${params.environment}"),
                         string(name:'branch_name', value: "${params.branch_name}"),
                         string(name:'service_name', value: "${params.service_name}"),                      
                     ]
            println jobB.getResult()
        }

Better way to find index of item in ArrayList?

Java API specifies two methods you could use: indexOf(Object obj) and lastIndexOf(Object obj). The first one returns the index of the element if found, -1 otherwise. The second one returns the last index, that would be like searching the list backwards.

Two decimal places using printf( )

Try using a format like %d.%02d

int iAmount = 10050;
printf("The number with fake decimal point is %d.%02d", iAmount/100, iAmount%100);

Another approach is to type cast it to double before printing it using %f like this:

printf("The number with fake decimal point is %0.2f", (double)(iAmount)/100);

My 2 cents :)

Extract source code from .jar file

suppose your JAR file is in C:\Documents and Settings\mmeher\Desktop\jar and the JAR file name is xx.jar, then write the below two commands in command prompt:

1> cd C:\Documents and Settings\mmeher\Desktop\jar

2> jar xf xx.jar

How to create a link to a directory

Symbolic or soft link (files or directories, more flexible and self documenting)

#     Source                             Link
ln -s /home/jake/doc/test/2000/something /home/jake/xxx

Hard link (files only, less flexible and not self documenting)

#   Source                             Link
ln /home/jake/doc/test/2000/something /home/jake/xxx

More information: man ln


/home/jake/xxx is like a new directory. To avoid "is not a directory: No such file or directory" error, as @trlkly comment, use relative path in the target, that is, using the example:

  1. cd /home/jake/
  2. ln -s /home/jake/doc/test/2000/something xxx

How to get the size of a JavaScript object?

The Google Chrome Heap Profiler allows you to inspect object memory use.

You need to be able to locate the object in the trace which can be tricky. If you pin the object to the Window global, it is pretty easy to find from the "Containment" listing mode.

In the attached screenshot, I created an object called "testObj" on the window. I then located in the profiler (after making a recording) and it shows the full size of the object and everything in it under "retained size".

More details on the memory breakdowns.

Chrome profiler

In the above screenshot, the object shows a retained size of 60. I believe the unit is bytes here.

Virtual Serial Port for Linux

There is also tty0tty http://sourceforge.net/projects/tty0tty/ which is a real null modem emulator for linux.

It is a simple kernel module - a small source file. I don't know why it only got thumbs down on sourceforge, but it works well for me. The best thing about it is that is also emulates the hardware pins (RTC/CTS DSR/DTR). It even implements TIOCMGET/TIOCMSET and TIOCMIWAIT iotcl commands!

On a recent kernel you may get compilation errors. This is easy to fix. Just insert a few lines at the top of the module/tty0tty.c source (after the includes):

#ifndef init_MUTEX
#define init_MUTEX(x) sema_init((x),1)
#endif

When the module is loaded, it creates 4 pairs of serial ports. The devices are /dev/tnt0 to /dev/tnt7 where tnt0 is connected to tnt1, tnt2 is connected to tnt3, etc. You may need to fix the file permissions to be able to use the devices.

edit:

I guess I was a little quick with my enthusiasm. While the driver looks promising, it seems unstable. I don't know for sure but I think it crashed a machine in the office I was working on from home. I can't check until I'm back in the office on monday.

The second thing is that TIOCMIWAIT does not work. The code seems to be copied from some "tiny tty" example code. The handling of TIOCMIWAIT seems in place, but it never wakes up because the corresponding call to wake_up_interruptible() is missing.

edit:

The crash in the office really was the driver's fault. There was an initialization missing, and the completely untested TIOCMIWAIT code caused a crash of the machine.

I spent yesterday and today rewriting the driver. There were a lot of issues, but now it works well for me. There's still code missing for hardware flow control managed by the driver, but I don't need it because I'll be managing the pins myself using TIOCMGET/TIOCMSET/TIOCMIWAIT from user mode code.

If anyone is interested in my version of the code, send me a message and I'll send it to you.

How to pass variable number of arguments to printf/sprintf

You are looking for variadic functions. printf() and sprintf() are variadic functions - they can accept a variable number of arguments.

This entails basically these steps:

  1. The first parameter must give some indication of the number of parameters that follow. So in printf(), the "format" parameter gives this indication - if you have 5 format specifiers, then it will look for 5 more arguments (for a total of 6 arguments.) The first argument could be an integer (eg "myfunction(3, a, b, c)" where "3" signifies "3 arguments)

  2. Then loop through and retrieve each successive argument, using the va_start() etc. functions.

There are plenty of tutorials on how to do this - good luck!

Python Database connection Close

You might try turning off pooling, which is enabled by default. See this discussion for more information.

import pyodbc
pyodbc.pooling = False
conn = pyodbc.connect('DRIVER=MySQL ODBC 5.1 driver;SERVER=localhost;DATABASE=spt;UID=who;PWD=testest') 

csr = conn.cursor()  
csr.close()
del csr

How to validate a credit card number

You define the variable name re16digit but later refer to it as re10digit, which will throw an error. To simplify your code, you should use RegExp.prototype.test() rather than String.prototype.search():

function validate_creditcardnumber() {
    var re16digit = /^\d{16}$/;
    if (!re16digit.test(document.myform.CreditCardNumber.value)) {
        alert("Please enter your 16 digit credit card numbers");
        return false;
    }
}

Working demo: http://jsfiddle.net/Dxjkh/

As others have mentioned, you may be better off using a JavaScript implementation of the Luhn Algorithm. It's also worth mentioning that a check for 16 digits will fail for American Express (15 digits) and Diners (14 digits) cards.

what does "error : a nonstatic member reference must be relative to a specific object" mean?

Only static functions are called with class name.

classname::Staicfunction();

Non static functions have to be called using objects.

classname obj;
obj.Somefunction();

This is exactly what your error means. Since your function is non static you have to use a object reference to invoke it.

How to copy text from a div to clipboard

I tried the solution proposed above. But it was not cross-browser enough. I really needed ie11 to work. After trying I got to:

    <html>
        <body>
            <div id="a" onclick="copyDivToClipboard()"> Click to copy </div>
            <script>
                function copyDivToClipboard() {
                    var range = document.createRange();
                    range.selectNode(document.getElementById("a"));
                    window.getSelection().removeAllRanges(); // clear current selection
                    window.getSelection().addRange(range); // to select text
                    document.execCommand("copy");
                    window.getSelection().removeAllRanges();// to deselect
                }
            </script>
        </body>
    </html>

Tested with firefox 64, Chrome 71, Opera 57, ie11(11.472.17134.0), edge( EdgeHTML 17.17134)

Update March 27th, 2019.

For some reason document.createRange() didn't work before with ie11. But now properly returns a Range object. So is better to use that, rather than document.getSelection().getRangeAt(0).

C# Lambda expressions: Why should I use them?

I found them useful in a situation when I wanted to declare a handler for some control's event, using another control. To do it normally you would have to store controls' references in fields of the class so that you could use them in a different method than they were created.

private ComboBox combo;
private Label label;

public CreateControls()
{
    combo = new ComboBox();
    label = new Label();
    //some initializing code
    combo.SelectedIndexChanged += new EventHandler(combo_SelectedIndexChanged);
}

void combo_SelectedIndexChanged(object sender, EventArgs e)
{
    label.Text = combo.SelectedValue;
}

thanks to lambda expressions you can use it like this:

public CreateControls()
{
    ComboBox combo = new ComboBox();
    Label label = new Label();
    //some initializing code
    combo.SelectedIndexChanged += (s, e) => {label.Text = combo.SelectedValue;};
}

Much easier.

How to check if an element is visible with WebDriver

I have the following 2 suggested ways:

  1. You can use isDisplayed() as below:

    driver.findElement(By.id("idOfElement")).isDisplayed();
    
  2. You can define a method as shown below and call it:

    public boolean isElementPresent(By by) {
      try {
        driver.findElement(by);
        return true;
      }
    catch (org.openqa.selenium.NoSuchElementException e) {
        return false;
      }
    }
    

Now, you can do assertion as below to check either the element is present or not:

assertTrue(isElementPresent(By.id("idOfElement")));

"Are you missing an assembly reference?" compile error - Visual Studio

Delete 'Web.Debug.config' and 'Web.Release.config' file for your solution directory,it should remove all errors

Check if an object exists

I think the easiest from a logical and efficiency point of view is using the queryset's exists() function, documented here:

https://docs.djangoproject.com/en/stable/ref/models/querysets/#django.db.models.query.QuerySet.exists

So in your example above I would simply write:

if User.objects.filter(email = cleaned_info['username']).exists():
    # at least one object satisfying query exists
else:
    # no object satisfying query exists

Position a div container on the right side

Is this what you wanted? - http://jsfiddle.net/jomanlk/x5vyC/3/

Floats on both sides now

#wrapper{
    background:red;
    overflow:auto;
}

#c1{
   float:left;
   background:blue;
}

#c2{
    background:green;
    float:right;
}?

<div id="wrapper">
    <div id="c1">con1</div>
    <div id="c2">con2</div>
</div>?

What is the correct way to start a mongod service on linux / OS X?

After installing mongodb through brew, run this to get it up and running:

mongod --dbpath /usr/local/var/mongodb

Task continuation on UI thread

With async you just do:

await Task.Run(() => do some stuff);
// continue doing stuff on the same context as before.
// while it is the default it is nice to be explicit about it with:
await Task.Run(() => do some stuff).ConfigureAwait(true);

However:

await Task.Run(() => do some stuff).ConfigureAwait(false);
// continue doing stuff on the same thread as the task finished on.

HTTP test server accepting GET/POST requests

Have a look at PutsReq, it's similar to the others, but it also allows you to write the responses you want using JavaScript.

Reading a text file and splitting it into single words in python

with open(filename) as file:
    words = file.read().split()

Its a List of all words in your file.

import re
with open(filename) as file:
    words = re.findall(r"([a-zA-Z\-]+)", file.read())

How to select a schema in postgres when using psql?

if playing with psql inside docker exec it like this:

docker exec -e "PGOPTIONS=--search_path=<your_schema>" -it docker_pg psql -U user db_name

ASP.NET Temporary files cleanup

Just an update on more current OS's (Vista, Win7, etc.) - the temp file path has changed may be different based on several variables. The items below are not definitive, however, they are a few I have encountered:

"temp" environment variable setting - then it would be:

%temp%\Temporary ASP.NET Files

Permissions and what application/process (VS, IIS, IIS Express) is running the .Net compiler. Accessing the C:\WINDOWS\Microsoft.NET\Framework folders requires elevated permissions and if you are not developing under an account with sufficient permissions then this folder might be used:

c:\Users\[youruserid]\AppData\Local\Temp\Temporary ASP.NET Files

There are also cases where the temp folder can be set via config for a machine or site specific using this:

<compilation tempDirectory="d:\MyTempPlace" />

I even have a funky setup at work where we don't run Admin by default, plus the IT guys have login scripts that set %temp% and I get temp files in 3 different locations depending on what is compiling things! And I'm still not certain about how these paths get picked....sigh.

Still, dthrasher is correct, you can just delete these and VS and IIS will just recompile them as needed.

nodemon command is not recognized in terminal for node js server

To use nodemon you must install it globally.

For Windows

npm i -g nodemon

For Mac

sudo npm i -g nodemon

If you don't want to install it globally you can install it locally in your project folder by running command npm i nodemon . It will give error something like this if run locally:

nodemon : The term 'nodemon' is not recognized as the name of a
cmdlet, function, script file, or operable program. Check the spelling
of the name, or if a path was included, verify that the path is
correct and try again.

To remove this error open package.json file and add

"scripts": {
     "server": "nodemon server.js"
 },

and after that just run command

npm run server

and your nodemon will start working properly.

Get file name from URI string in C#

I think this will do what you need:

var uri = new Uri(hreflink);
var filename = uri.Segments.Last();

How to open mail app from Swift

While other answers are all correct, you can never know if the iPhone/iPad that is running your application has the Apple's Mail app installed or not as it can be deleted by the user.

It is better to support multiple email clients. Following code handles the email sending in a more graceful way. The flow of the code is:

  • If Mail app is installed, open Mail's composer pre-filled with provided data
  • Otherwise, try opening the Gmail app, then Outlook, then Yahoo mail, then Spark, in this order
  • If none of those clients are installed, fallback to default mailto:.. that prompts the user to install Apple's Mail app.

Code is written in Swift 5:

    import MessageUI
    import UIKit

    class SendEmailViewController: UIViewController, MFMailComposeViewControllerDelegate {
        
        @IBAction func sendEmail(_ sender: UIButton) {
            // Modify following variables with your text / recipient
            let recipientEmail = "[email protected]"
            let subject = "Multi client email support"
            let body = "This code supports sending email via multiple different email apps on iOS! :)"
            
            // Show default mail composer
            if MFMailComposeViewController.canSendMail() {
                let mail = MFMailComposeViewController()
                mail.mailComposeDelegate = self
                mail.setToRecipients([recipientEmail])
                mail.setSubject(subject)
                mail.setMessageBody(body, isHTML: false)
                
                present(mail, animated: true)
            
            // Show third party email composer if default Mail app is not present
            } else if let emailUrl = createEmailUrl(to: recipientEmail, subject: subject, body: body) {
                UIApplication.shared.open(emailUrl)
            }
        }
        
        private func createEmailUrl(to: String, subject: String, body: String) -> URL? {
            let subjectEncoded = subject.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!
            let bodyEncoded = body.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!
            
            let gmailUrl = URL(string: "googlegmail://co?to=\(to)&subject=\(subjectEncoded)&body=\(bodyEncoded)")
            let outlookUrl = URL(string: "ms-outlook://compose?to=\(to)&subject=\(subjectEncoded)")
            let yahooMail = URL(string: "ymail://mail/compose?to=\(to)&subject=\(subjectEncoded)&body=\(bodyEncoded)")
            let sparkUrl = URL(string: "readdle-spark://compose?recipient=\(to)&subject=\(subjectEncoded)&body=\(bodyEncoded)")
            let defaultUrl = URL(string: "mailto:\(to)?subject=\(subjectEncoded)&body=\(bodyEncoded)")
            
            if let gmailUrl = gmailUrl, UIApplication.shared.canOpenURL(gmailUrl) {
                return gmailUrl
            } else if let outlookUrl = outlookUrl, UIApplication.shared.canOpenURL(outlookUrl) {
                return outlookUrl
            } else if let yahooMail = yahooMail, UIApplication.shared.canOpenURL(yahooMail) {
                return yahooMail
            } else if let sparkUrl = sparkUrl, UIApplication.shared.canOpenURL(sparkUrl) {
                return sparkUrl
            }
            
            return defaultUrl
        }
        
        func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) {
            controller.dismiss(animated: true)
        }
    }

Please note that I intentionally missed out the body for the Outlook app, as it is not able to parse it.

You also have to add following code to Info.plist file that whitelists the URl query schemes that are used.

<key>LSApplicationQueriesSchemes</key>
<array>
    <string>googlegmail</string>
    <string>ms-outlook</string>
    <string>readdle-spark</string>
    <string>ymail</string>
</array>

Show/hide 'div' using JavaScript

Just Simple Set the style attribute of ID:

To Show the hidden div

<div id="xyz" style="display:none">
     ...............
</div>
//In JavaScript

document.getElementById('xyz').style.display ='block';  // to hide

To hide the shown div

<div id="xyz">
     ...............
</div>
//In JavaScript

document.getElementById('xyz').style.display ='none';  // to display

Way to go from recursion to iteration

My examples are in Clojure, but should be fairly easy to translate to any language.

Given this function that StackOverflows for large values of n:

(defn factorial [n]
  (if (< n 2)
    1
    (*' n (factorial (dec n)))))

we can define a version that uses its own stack in the following manner:

(defn factorial [n]
  (loop [n n
         stack []]
    (if (< n 2)
      (return 1 stack)
      ;; else loop with new values
      (recur (dec n)
             ;; push function onto stack
             (cons (fn [n-1!]
                     (*' n n-1!))
                   stack)))))

where return is defined as:

(defn return
  [v stack]
  (reduce (fn [acc f]
            (f acc))
          v
          stack))

This works for more complex functions too, for example the ackermann function:

(defn ackermann [m n]
  (cond
    (zero? m)
    (inc n)

    (zero? n)
    (recur (dec m) 1)

    :else
    (recur (dec m)
           (ackermann m (dec n)))))

can be transformed into:

(defn ackermann [m n]
  (loop [m m
         n n
         stack []]
    (cond
      (zero? m)
      (return (inc n) stack)

      (zero? n)
      (recur (dec m) 1 stack)

      :else
      (recur m
             (dec n)
             (cons #(ackermann (dec m) %)
                   stack)))))

How to pretty print XML from the command line?

libxml2-utils

This utility comes with libxml2-utils:

echo '<root><foo a="b">lorem</foo><bar value="ipsum" /></root>' |
    xmllint --format -

Perl's XML::Twig

This command comes with XML::Twig module, sometimes xml-twig-tools package:

echo '<root><foo a="b">lorem</foo><bar value="ipsum" /></root>' |
    xml_pp

xmlstarlet

This command comes with xmlstarlet:

echo '<root><foo a="b">lorem</foo><bar value="ipsum" /></root>' |
    xmlstarlet format --indent-tab

tidy

Check the tidy package:

echo '<root><foo a="b">lorem</foo><bar value="ipsum" /></root>' |
    tidy -xml -i -

Python

Python's xml.dom.minidom can format XML (both python2 and python3):

echo '<root><foo a="b">lorem</foo><bar value="ipsum" /></root>' |
    python -c 'import sys;import xml.dom.minidom;s=sys.stdin.read();print(xml.dom.minidom.parseString(s).toprettyxml())'

saxon-lint

You need saxon-lint:

echo '<root><foo a="b">lorem</foo><bar value="ipsum" /></root>' |
    saxon-lint --indent --xpath '/' -

saxon-HE

You need saxon-HE:

 echo '<root><foo a="b">lorem</foo><bar value="ipsum" /></root>' |
    java -cp /usr/share/java/saxon/saxon9he.jar net.sf.saxon.Query \
    -s:- -qs:/ '!indent=yes'

How to select between brackets (or quotes or ...) in Vim?

To select between the single quotes I usually do a vi' ("select inner single quotes").

Inside a parenthesis block, I use vib ("select inner block")

Inside a curly braces block you can use viB ("capital B")

To make the selections "inclusive" (select also the quotes, parenthesis or braces) you can use a instead of i.

You can read more about the Text object selections on the manual, or :help text-objects within vim.

Salt and hash a password in Python

Firstly import:-

import hashlib, uuid

Then change your code according to this in your method:

uname = request.form["uname"]
pwd=request.form["pwd"]
salt = hashlib.md5(pwd.encode())

Then pass this salt and uname in your database sql query, below login is a table name:

sql = "insert into login values ('"+uname+"','"+email+"','"+salt.hexdigest()+"')"

no overload for matches delegate 'system.eventhandler'

Change the klik method as follows:

public void klik(object pea, EventArgs e)
{
    Bitmap c = this.DrawMandel();
    Button btn = pea as Button;
    Graphics gr = btn.CreateGraphics();
    gr.DrawImage(b, 150, 200);
}

How to embed a video into GitHub README.md?

This is an old post but I was looking for an answer and I found this: https://gifs.com. Just upload the video, then it creates a gif we can add easily in a github markdown. I tried it, the quality of the gif is a good one.

Disable Drag and Drop on HTML elements?

I will just leave it here. Helped me after I tried everything.

   $(document.body).bind("dragover", function(e) {
        e.preventDefault();
        return false;
   });

   $(document.body).bind("drop", function(e){
        e.preventDefault();
        return false;
   });

ASP.NET Bundles how to disable minification

If you have debug="true" in web.config and are using Scripts/Styles.Render to reference the bundles in your pages, that should turn off both bundling and minification. BundleTable.EnableOptimizations = false will always turn off both bundling and minification as well (irrespective of the debug true/false flag).

Are you perhaps not using the Scripts/Styles.Render helpers? If you are directly rendering references to the bundle via BundleTable.Bundles.ResolveBundleUrl() you will always get the minified/bundled content.

Alter a MySQL column to be AUTO_INCREMENT

You can apply the atuto_increment constraint to the data column by the following query:

ALTER TABLE customers MODIFY COLUMN customer_id BIGINT NOT NULL AUTO_INCREMENT;

But, if the columns are part of a foreign key constraint you, will most probably receive an error. Therefore, it is advised to turn off foreign_key_checks by using the following query:

SET foreign_key_checks = 0;

Therefore, use the following query instead:

SET foreign_key_checks = 0;
ALTER TABLE customers MODIFY COLUMN customer_id BIGINT NOT NULL AUTO_INCREMENT;
SET foreign_key_checks = 1;

CSS background-image - What is the correct usage?

just check the directory structure where exactly image is suppose you have a css folder and images folder outside css folder then you will have to use"../images/image.jpg" and it will work as it did for me just make sure the directory stucture.

Check if value exists in Postgres array

Watch out for the trap I got into: When checking if certain value is not present in an array, you shouldn't do:

SELECT value_variable != ANY('{1,2,3}'::int[])

but use

SELECT value_variable != ALL('{1,2,3}'::int[])

instead.