Programs & Examples On #Typekit

Typekit is an Adobe service which allows embedding fonts into online and offline documents.

Adding script tag to React/JSX

You can also use react helmet

import React from "react";
import {Helmet} from "react-helmet";

class Application extends React.Component {
  render () {
    return (
        <div className="application">
            <Helmet>
                <meta charSet="utf-8" />
                <title>My Title</title>
                <link rel="canonical" href="http://example.com/example" />
                <script src="/path/to/resource.js" type="text/javascript" />
            </Helmet>
            ...
        </div>
    );
  }
};

Helmet takes plain HTML tags and outputs plain HTML tags. It's dead simple, and React beginner friendly.

Is there any "font smoothing" in Google Chrome?

Ok you can use this simply

-webkit-text-stroke-width: .7px;
-webkit-text-stroke-color: #34343b;
-webkit-font-smoothing:antialiased;

Make sure your text color and upper text-stroke-width must me same and that's it.

How to loop in excel without VBA or macros?

You could create a table somewhere on a calculation spreadsheet which performs this operation for each pair of cells, and use auto-fill to fill it up.

Aggregate the results from that table into a results cell.

The 200 so cells which reference the results could then reference the cell that holds the aggregation results. In the newest versions of excel you can name the result cell and reference it that way, for ease of reading.

Reading specific columns from a text file in python

f=open(file,"r")
lines=f.readlines()
result=[]
for x in lines:
    result.append(x.split(' ')[1])
f.close()

You can do the same using a list comprehension

print([x.split(' ')[1] for x in open(file).readlines()])

Docs on split()

string.split(s[, sep[, maxsplit]])

Return a list of the words of the string s. If the optional second argument sep is absent or None, the words are separated by arbitrary strings of whitespace characters (space, tab, newline, return, formfeed). If the second argument sep is present and not None, it specifies a string to be used as the word separator. The returned list will then have one more item than the number of non-overlapping occurrences of the separator in the string.

So, you can omit the space I used and do just x.split() but this will also remove tabs and newlines, be aware of that.

Add two textbox values and display the sum in a third textbox automatically

try this

  function sum() {
       var txtFirstNumberValue = document.getElementById('txt1').value;
       var txtSecondNumberValue = document.getElementById('txt2').value;
       if (txtFirstNumberValue == "")
           txtFirstNumberValue = 0;
       if (txtSecondNumberValue == "")
           txtSecondNumberValue = 0;

       var result = parseInt(txtFirstNumberValue) + parseInt(txtSecondNumberValue);
       if (!isNaN(result)) {
           document.getElementById('txt3').value = result;
       }
   }

How to determine the Boost version on a system?

Might be already answered, but you can try this simple program to determine if and what installation of boost you have :

#include<boost/version.hpp>
#include<iostream>
using namespace std;
int main()
{
cout<<BOOST_VERSION<<endl;
return 0;
}

Android how to use Environment.getExternalStorageDirectory()

As described in Documentation Environment.getExternalStorageDirectory() :

Environment.getExternalStorageDirectory() Return the primary shared/external storage directory.

This is an example of how to use it reading an image :

String fileName = "stored_image.jpg";
 String baseDir = Environment.getExternalStorageDirectory().getAbsolutePath();
 String pathDir = baseDir + "/Android/data/com.mypackage.myapplication/";

 File f = new File(pathDir + File.separator + fileName);

        if(f.exists()){
          Log.d("Application", "The file " + file.getName() + " exists!";
         }else{
          Log.d("Application", "The file no longer exists!";
         }

How to enumerate an enum

There are two ways to iterate an Enum:

1. var values =  Enum.GetValues(typeof(myenum))
2. var values =  Enum.GetNames(typeof(myenum))

The first will give you values in form on an array of **object**s, and the second will give you values in form of an array of **String**s.

Use it in a foreach loop as below:

foreach(var value in values)
{
    // Do operations here
}

How to replace a string in an existing file in Perl?

None of the existing answers here has provided a complete example of how to do this from within a script (not a one-liner). Here is what I did:

rename($file, $file.'.bak');
open(IN, '<'.$file.'.bak') or die $!;
open(OUT, '>'.$file) or die $!;
while(<IN>)
{
    $_ =~ s/blue/red/g;
    print OUT $_;
}
close(IN);
close(OUT);

NullInjectorError: No provider for AngularFirestore

I take that to my app.module. After the imports it should be works

providers: [
    { provide: LocationStrategy, useClass: HashLocationStrategy },
    { provide: FirestoreSettingsToken, useValue: {} }
  ],

My Version:

Angular CLI: 7.2.4
Node: 10.15.0
Angular: 7.2.5
... common, compiler, compiler-cli, core, forms
... language-service, platform-browser, platform-browser-dynamic
... router

Package                           Version
-----------------------------------------------------------
@angular-devkit/architect         0.12.4
@angular-devkit/build-angular     0.12.4
@angular-devkit/build-optimizer   0.12.4
@angular-devkit/build-webpack     0.12.4
@angular-devkit/core              7.2.4
@angular-devkit/schematics        7.2.4
@angular/animations               8.0.0-beta.4+7.sha-3c7ce82
@angular/cdk                      7.3.2-3ae6eb2
@angular/cli                      7.2.4
@angular/fire                     5.1.1
@angular/flex-layout              7.0.0-beta.23
@angular/material                 7.3.2-3ae6eb2
@ngtools/webpack                  7.2.4
@schematics/angular               7.2.4
@schematics/update                0.12.4
rxjs                              6.3.3
typescript                        3.2.4
webpack                           4.28.4

.substring error: "is not a function"

you can also quote string

''+document.location+''.substring(2,3);

_DEBUG vs NDEBUG

Unfortunately DEBUG is overloaded heavily. For instance, it's recommended to always generate and save a pdb file for RELEASE builds. Which means one of the -Zx flags, and -DEBUG linker option. While _DEBUG relates to special debug versions of runtime library such as calls to malloc and free. Then NDEBUG will disable assertions.

How to allow only a number (digits and decimal point) to be typed in an input?

I wanted a directive that could be limited in range by min and max attributes like so:

<input type="text" integer min="1" max="10" />

so I wrote the following:

.directive('integer', function() {
    return {
        restrict: 'A',
        require: '?ngModel',
        link: function(scope, elem, attr, ngModel) {
            if (!ngModel)
                return;

            function isValid(val) {
                if (val === "")
                    return true;

                var asInt = parseInt(val, 10);
                if (asInt === NaN || asInt.toString() !== val) {
                    return false;
                }

                var min = parseInt(attr.min);
                if (min !== NaN && asInt < min) {
                    return false;
                }

                var max = parseInt(attr.max);
                if (max !== NaN && max < asInt) {
                    return false;
                }

                return true;
            }

            var prev = scope.$eval(attr.ngModel);
            ngModel.$parsers.push(function (val) {
                // short-circuit infinite loop
                if (val === prev)
                    return val;

                if (!isValid(val)) {
                    ngModel.$setViewValue(prev);
                    ngModel.$render();
                    return prev;
                }

                prev = val;
                return val;
            });
        }
    };
});

Is returning out of a switch statement considered a better practice than using break?

Neither, because both are quite verbose for a very simple task. You can just do:

let result = ({
  1: 'One',
  2: 'Two',
  3: 'Three'
})[opt] ?? 'Default'    // opt can be 1, 2, 3 or anything (default)

This, of course, also works with strings, a mix of both or without a default case:

let result = ({
  'first': 'One',
  'second': 'Two',
  3: 'Three'
})[opt]                // opt can be 'first', 'second' or 3

Explanation:

It works by creating an object where the options/cases are the keys and the results are the values. By putting the option into the brackets you access the value of the key that matches the expression via the bracket notation.

This returns undefined if the expression inside the brackets is not a valid key. We can detect this undefined-case by using the nullish coalescing operator ?? and return a default value.

Example:

_x000D_
_x000D_
console.log('Using a valid case:', ({
  1: 'One',
  2: 'Two',
  3: 'Three'
})[1] ?? 'Default')

console.log('Using an invalid case/defaulting:', ({
  1: 'One',
  2: 'Two',
  3: 'Three'
})[7] ?? 'Default')
_x000D_
.as-console-wrapper {max-height: 100% !important;top: 0;}
_x000D_
_x000D_
_x000D_

How to simplify a null-safe compareTo() implementation?

I know that it may be not directly answer to your question, because you said that null values have to be supported.

But I just want to note that supporting nulls in compareTo is not in line with compareTo contract described in official javadocs for Comparable:

Note that null is not an instance of any class, and e.compareTo(null) should throw a NullPointerException even though e.equals(null) returns false.

So I would either throw NullPointerException explicitly or just let it be thrown first time when null argument is being dereferenced.

C# cannot convert method to non delegate type

You need to add parentheses after a method call, else the compiler will think you're talking about the method itself (a delegate type), whereas you're actually talking about the return value of that method.

string t = obj.getTitle();

Extra Non-Essential Information

Also, have a look at properties. That way you could use title as if it were a variable, while, internally, it works like a function. That way you don't have to write the functions getTitle() and setTitle(string value), but you could do it like this:

public string Title // Note: public fields, methods and properties use PascalCasing
{
    get // This replaces your getTitle method
    {
        return _title; // Where _title is a field somewhere
    }
    set // And this replaces your setTitle method
    {
        _title = value; // value behaves like a method parameter
    }
}

Or you could use auto-implemented properties, which would use this by default:

public string Title { get; set; }

And you wouldn't have to create your own backing field (_title), the compiler would create it itself.

Also, you can change access levels for property accessors (getters and setters):

public string Title { get; private set; }

You use properties as if they were fields, i.e.:

this.Title = "Example";
string local = this.Title;

WebForms UnobtrusiveValidationMode requires a ScriptResourceMapping for jquery

I think this is the best solution for this type error. So please add below line. Also it work my code when I am using MSVS 2015.

<configuration>
<appSettings>
<add key="ValidationSettings:UnobtrusiveValidationMode" value="None" />
</appSettings>
</configuration>

Saving an Excel sheet in a current directory with VBA

VBA has a CurDir keyword that will return the "current directory" as stored in Excel. I'm not sure all the things that affect the current directory, but definitely opening or saving a workbook will change it.

MyWorkbook.SaveAs CurDir & Application.PathSeparator & "MySavedWorkbook.xls"

This assumes that the sheet you want to save has never been saved and you want to define the file name in code.

How can I rename a single column in a table at select?

Also you may omit the AS keyword.
SELECT row1 Price, row2 'Other Price' FROM exampleDB.table1;
in this option readability is a bit degraded but you have desired result.

Change WPF window background image in C# code

i just place one image in " d drive-->Data-->IMG". The image name is x.jpg:

And on c# code type

ImageBrush myBrush = new ImageBrush();

myBrush.ImageSource = new BitmapImage(new Uri(BaseUriHelper.GetBaseUri(this), "D:\\Data\\IMG\\x.jpg"));

(please put double slash in between path)

this.Background = myBrush;

finally i got the background.. enter image description here

How do I bottom-align grid elements in bootstrap fluid layout

.align-bottom {
    position: absolute;
    bottom: 10px;
    right: 10px;
}

Command not found after npm install in zsh

If you installed Node.js using Homebrew, npm binaries can be found in /usr/local/share/npm/bin. You should make sure this directory is in your PATH environment variable. So, in your ~/.zshrc file add export PATH=/usr/local/share/npm/bin:$PATH.

SQL error "ORA-01722: invalid number"

Suppose telephone number is defined as NUMBER then the blanks cannot be converted into a number:

create table telephone_number (tel_number number);
insert into telephone_number values ('0419 853 694');

The above gives you a

ORA-01722: invalid number

API vs. Webservice

API is code based integration while web service is message based integration with interoperable standards having a contract such as WSDL.

How to create a checkbox with a clickable label?

<label for="my_checkbox">Check me</label>
<input type="checkbox" name="my_checkbox" value="Car" />

TCP vs UDP on video stream

Drawbacks of using TCP for live video:

  1. Typically live video-streaming appliances are not designed with TCP streaming in mind. If you use TCP, the OS must buffer the unacknowledged segments for every client. This is undesirable, particularly in the case of live events; presumably your list of simultaneous clients is long due to the singularity of the event. Pre-recorded video-casts typically don't have as much of a problem with this because viewers stagger their replay activity; therefore TCP is more appropriate for replaying a video-on-demand.
  2. IP multicast significantly reduces video bandwidth requirements for large audiences; TCP prevents the use of IP multicast, but UDP is well-suited for IP multicast.
  3. Live video is normally a constant-bandwidth stream recorded off a camera; pre-recorded video streams come off a disk. The loss-backoff dynamics of TCP make it harder to serve live video when the source streams are at a constant bandwidth (as would happen for a live-event). If you buffer to disk off a camera, be sure you have enough buffer for unpredictable network events and variable TCP send/backoff rates. UDP gives you much more control for this application since UDP doesn't care about network transport layer drops.

FYI, please don't use the word "packages" when describing networks. Networks send "packets".

Passing html values into javascript functions

Give the textbox an id of "txtValue" and change the input button declaration to the following:

<input type="button" value="submit" onclick="verifyorder(document.getElementById('txtValue').value)" />

TypeError: document.getElementbyId is not a function

Case sensitive: document.getElementById (notice the capital B).

How to read/write from/to file using Go?

With newer Go versions, reading/writing to/from file is easy. To read from a file:

package main

import (
    "fmt"
    "io/ioutil"
)

func main() {
    data, err := ioutil.ReadFile("text.txt")
    if err != nil {
        return
    }
    fmt.Println(string(data))
}

To write to a file:

package main

import "os"

func main() {
    file, err := os.Create("text.txt")
    if err != nil {
        return
    }
    defer file.Close()

    file.WriteString("test\nhello")
}

This will overwrite the content of a file (create a new file if it was not there).

How to pass parameter to click event in Jquery

As DOC says, you can pass data to the handler as next:

// say your selector and click handler looks something like this...
$("some selector").on('click',{param1: "Hello", param2: "World"}, cool_function);

// in your function, just grab the event object and go crazy...
function cool_function(event){
    alert(event.data.param1);
    alert(event.data.param2);

    // access element's id where click occur
    alert( event.target.id ); 
}

What is the difference between char, nchar, varchar, and nvarchar in SQL Server?

  • nchar is fixed-length and can hold unicode characters. it uses two bytes storage per character.

  • varchar is of variable length and cannot hold unicode characters. it uses one byte storage per character.

Displaying Total in Footer of GridView and also Add Sum of columns(row vise) in last Column

int total = 0;
protected void gvEmp_RowDataBound(object sender, GridViewRowEventArgs e)
{
if(e.Row.RowType==DataControlRowType.DataRow)
{
total += Convert.ToInt32(DataBinder.Eval(e.Row.DataItem, "Amount"));
}
if(e.Row.RowType==DataControlRowType.Footer)
{
Label lblamount = (Label)e.Row.FindControl("lblTotal");
lblamount.Text = total.ToString();
}
}

Is multiplication and division using shift operators in C actually faster?

Is it actually faster to use say (i<<3)+(i<<1) to multiply with 10 than using i*10 directly?

It might or might not be on your machine - if you care, measure in your real-world usage.

A case study - from 486 to core i7

Benchmarking is very difficult to do meaningfully, but we can look at a few facts. From http://www.penguin.cz/~literakl/intel/s.html#SAL and http://www.penguin.cz/~literakl/intel/i.html#IMUL we get an idea of x86 clock cycles needed for arithmetic shift and multiplication. Say we stick to "486" (the newest one listed), 32 bit registers and immediates, IMUL takes 13-42 cycles and IDIV 44. Each SAL takes 2, and adding 1, so even with a few of those together shifting superficially looks like a winner.

These days, with the core i7:

(from http://software.intel.com/en-us/forums/showthread.php?t=61481)

The latency is 1 cycle for an integer addition and 3 cycles for an integer multiplication. You can find the latencies and thoughput in Appendix C of the "IntelĀ® 64 and IA-32 Architectures Optimization Reference Manual", which is located on http://www.intel.com/products/processor/manuals/.

(from some Intel blurb)

Using SSE, the Core i7 can issue simultaneous add and multiply instructions, resulting in a peak rate of 8 floating-point operations (FLOP) per clock cycle

That gives you an idea of how far things have come. The optimisation trivia - like bit shifting versus * - that was been taken seriously even into the 90s is just obsolete now. Bit-shifting is still faster, but for non-power-of-two mul/div by the time you do all your shifts and add the results it's slower again. Then, more instructions means more cache faults, more potential issues in pipelining, more use of temporary registers may mean more saving and restoring of register content from the stack... it quickly gets too complicated to quantify all the impacts definitively but they're predominantly negative.

functionality in source code vs implementation

More generally, your question is tagged C and C++. As 3rd generation languages, they're specifically designed to hide the details of the underlying CPU instruction set. To satisfy their language Standards, they must support multiplication and shifting operations (and many others) even if the underlying hardware doesn't. In such cases, they must synthesize the required result using many other instructions. Similarly, they must provide software support for floating point operations if the CPU lacks it and there's no FPU. Modern CPUs all support * and <<, so this might seem absurdly theoretical and historical, but the significance thing is that the freedom to choose implementation goes both ways: even if the CPU has an instruction that implements the operation requested in the source code in the general case, the compiler's free to choose something else that it prefers because it's better for the specific case the compiler's faced with.

Examples (with a hypothetical assembly language)

source           literal approach         optimised approach
#define N 0
int x;           .word x                xor registerA, registerA
x *= N;          move x -> registerA
                 move x -> registerB
                 A = B * immediate(0)
                 store registerA -> x
  ...............do something more with x...............

Instructions like exclusive or (xor) have no relationship to the source code, but xor-ing anything with itself clears all the bits, so it can be used to set something to 0. Source code that implies memory addresses may not entail any being used.

These kind of hacks have been used for as long as computers have been around. In the early days of 3GLs, to secure developer uptake the compiler output had to satisfy the existing hardcore hand-optimising assembly-language dev. community that the produced code wasn't slower, more verbose or otherwise worse. Compilers quickly adopted lots of great optimisations - they became a better centralised store of it than any individual assembly language programmer could possibly be, though there's always the chance that they miss a specific optimisation that happens to be crucial in a specific case - humans can sometimes nut it out and grope for something better while compilers just do as they've been told until someone feeds that experience back into them.

So, even if shifting and adding is still faster on some particular hardware, then the compiler writer's likely to have worked out exactly when it's both safe and beneficial.

Maintainability

If your hardware changes you can recompile and it'll look at the target CPU and make another best choice, whereas you're unlikely to ever want to revisit your "optimisations" or list which compilation environments should use multiplication and which should shift. Think of all the non-power-of-two bit-shifted "optimisations" written 10+ years ago that are now slowing down the code they're in as it runs on modern processors...!

Thankfully, good compilers like GCC can typically replace a series of bitshifts and arithmetic with a direct multiplication when any optimisation is enabled (i.e. ...main(...) { return (argc << 4) + (argc << 2) + argc; } -> imull $21, 8(%ebp), %eax) so a recompilation may help even without fixing the code, but that's not guaranteed.

Strange bitshifting code implementing multiplication or division is far less expressive of what you were conceptually trying to achieve, so other developers will be confused by that, and a confused programmer's more likely to introduce bugs or remove something essential in an effort to restore seeming sanity. If you only do non-obvious things when they're really tangibly beneficial, and then document them well (but don't document other stuff that's intuitive anyway), everyone will be happier.

General solutions versus partial solutions

If you have some extra knowledge, such as that your int will really only be storing values x, y and z, then you may be able to work out some instructions that work for those values and get you your result more quickly than when the compiler's doesn't have that insight and needs an implementation that works for all int values. For example, consider your question:

Multiplication and division can be achieved using bit operators...

You illustrate multiplication, but how about division?

int x;
x >> 1;   // divide by 2?

According to the C++ Standard 5.8:

-3- The value of E1 >> E2 is E1 right-shifted E2 bit positions. If E1 has an unsigned type or if E1 has a signed type and a nonnegative value, the value of the result is the integral part of the quotient of E1 divided by the quantity 2 raised to the power E2. If E1 has a signed type and a negative value, the resulting value is implementation-defined.

So, your bit shift has an implementation defined result when x is negative: it may not work the same way on different machines. But, / works far more predictably. (It may not be perfectly consistent either, as different machines may have different representations of negative numbers, and hence different ranges even when there are the same number of bits making up the representation.)

You may say "I don't care... that int is storing the age of the employee, it can never be negative". If you have that kind of special insight, then yes - your >> safe optimisation might be passed over by the compiler unless you explicitly do it in your code. But, it's risky and rarely useful as much of the time you won't have this kind of insight, and other programmers working on the same code won't know that you've bet the house on some unusual expectations of the data you'll be handling... what seems a totally safe change to them might backfire because of your "optimisation".

Is there any sort of input that can't be multiplied or divided in this way?

Yes... as mentioned above, negative numbers have implementation defined behaviour when "divided" by bit-shifting.

Unable to install Android Studio in Ubuntu

This issue arises when your 64 bit os tries to install the Android SDK which in turns tries to install some 32 bit binaries and thus is the issue of compatibility.

Open an additional terminal and type

sudo apt-get install lib32z1 lib32ncurses5 lib32bz2-1.0 lib32stdc++6 

would help to install all the required binaries. After this, start the afresh the Android SDK installation process.

Check whether a path is valid

Get the invalid chars from System.IO.Path.GetInvalidPathChars(); and check if your string (Directory path) contains those or not.

Location for session files in Apache/PHP

The only surefire option to find the current session.save_path value is always to check with phpinfo() in exactly the environment where you want to find out the session storage directory.

Reason: there can be all sorts of things that change session.save_path, either by overriding the php.ini value or by setting it at runtime with ini_set('session.save_path','/path/to/folder');. For example, web server management panels like ISPConfig, Plesk etc. often adapt this to give each website its own directory with session files.

.c vs .cc vs. .cpp vs .hpp vs .h vs .cxx

Talking about .hpp extension, I find it useful when people are supposed to know that this header file contains C++ an not C, like using namespaces or template etc, by the moment they see the files, so they won't try to feed it to a C compiler! And I also like to name header files which contain not only declarations but implementations as well, as .hpp files. like header files including template classes. Although that's just my opinion and of course it's not supposed to be right! :)

How to get first character of a string in SQL?

I prefer:

SUBSTRING (my_column, 1, 1)

because it is Standard SQL-92 syntax and therefore more portable.


Strictly speaking, the standard version would be

SUBSTRING (my_column FROM 1 FOR 1)

The point is, transforming from one to the other, hence to any similar vendor variation, is trivial.

p.s. It was only recently pointed out to me that functions in standard SQL are deliberately contrary, by having parameters lists that are not the conventional commalists, in order to make them easily identifiable as being from the standard!

How to parse JSON with VBA without external libraries?

There are two issues here. The first is to access fields in the array returned by your JSON parse, the second is to rename collections/fields (like sentences) away from VBA reserved names.

Let's address the second concern first. You were on the right track. First, replace all instances of sentences with jsentences If text within your JSON also contains the word sentences, then figure out a way to make the replacement unique, such as using "sentences":[ as the search string. You can use the VBA Replace method to do this.

Once that's done, so VBA will stop renaming sentences to Sentences, it's just a matter of accessing the array like so:

'first, declare the variables you need:
Dim jsent as Variant

'Get arr all setup, then
For Each jsent in arr.jsentences
  MsgBox(jsent.orig)
Next

JavaScript: changing the value of onclick with or without jQuery

You shouldn't be using onClick any more if you are using jQuery. jQuery provides its own methods of attaching and binding events. See .click()

$(document).ready(function(){
    var js = "alert('B:' + this.id); return false;";
    // create a function from the "js" string
    var newclick = new Function(js);

    // clears onclick then sets click using jQuery
    $("#anchor").attr('onclick', '').click(newclick);
});

That should cancel the onClick function - and keep your "javascript from a string" as well.

The best thing to do would be to remove the onclick="" from the <a> element in the HTML code and switch to using the Unobtrusive method of binding an event to click.

You also said:

Using onclick = function() { return eval(js); } doesn't work because you are not allowed to use return in code passed to eval().

No - it won't, but onclick = eval("(function(){"+js+"})"); will wrap the 'js' variable in a function enclosure. onclick = new Function(js); works as well and is a little cleaner to read. (note the capital F) -- see documentation on Function() constructors

Why is "npm install" really slow?

One of the simple solution to speed up your npm install is to spin up a high powered machine on AWS and use that to compile your project and ship the code back to you.

I was experimenting with it and I found that there was a very high decrease in the time to run npm install. I found a tool to execute the above command easily https://stormyapp.com

PostgreSQL how to see which queries have run

Turn on the server log:

log_statement = all

This will log every call to the database server.

I would not use log_statement = all on a production server. Produces huge log files.
The manual about logging-parameters:

log_statement (enum)

Controls which SQL statements are logged. Valid values are none (off), ddl, mod, and all (all statements). [...]

Resetting the log_statement parameter requires a server reload (SIGHUP). A restart is not necessary. Read the manual on how to set parameters.

Don't confuse the server log with pgAdmin's log. Two different things!

You can also look at the server log files in pgAdmin, if you have access to the files (may not be the case with a remote server) and set it up correctly. In pgadmin III, have a look at: Tools -> Server status. That option was removed in pgadmin4.

I prefer to read the server log files with vim (or any editor / reader of your choice).

How to use JQuery with ReactJS

Yes, we can use jQuery in ReactJs. Here I will tell how we can use it using npm.

step 1: Go to your project folder where the package.json file is present via using terminal using cd command.

step 2: Write the following command to install jquery using npm : npm install jquery --save

step 3: Now, import $ from jquery into your jsx file where you need to use.

Example:

write the below in index.jsx

import React from 'react';
import ReactDOM from 'react-dom';
import $ from 'jquery';


//   react code here


$("button").click(function(){
    $.get("demo_test.asp", function(data, status){
        alert("Data: " + data + "\nStatus: " + status);
    });
});

// react code here

write the below in index.html

<!DOCTYPE html>
<html>
<head>
    <script src="index.jsx"></script>
    <!-- other scripting files -->
</head>
<body>
    <!-- other useful tags -->
    <div id="div1">
        <h2>Let jQuery AJAX Change This Text</h2>
    </div>
    <button>Get External Content</button>
</body>
</html>

SVN 405 Method Not Allowed

This means that the folder/file that you are trying to put on svn already exists there. My advice is that before doing anything just right click on the folder/file and click on repo-browser. By doing this you will be able to see all the files/sub-folders etc that are already present on svn. If the required file/folder is not present on the svn then you just delete(after taking backup) the file that you you want to add and then run an update.

Stuck at ".android/repositories.cfg could not be loaded."

Creating a dummy blank repositories.cfg works on Windows 7 as well. After waiting for a couple of minutes the installation finishes and you get the message on your cmd window -- done

How to assign name for a screen?

To create a new screen with the name foo, use

screen -S foo

Then to reattach it, run

screen -r foo  # or use -x, as in
screen -x foo  # for "Multi display mode" (see the man page)

Calling a Variable from another Class

That would just be:

 Console.WriteLine(Variables.name);

and it needs to be public also:

public class Variables
{
   public static string name = "";
}

How to find server name of SQL Server Management Studio

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

How can I mark a foreign key constraint using Hibernate annotations?

@JoinColumn(name="reference_column_name") annotation can be used above that property or field of class that is being referenced from some other entity.

Proper indentation for Python multiline strings

If you want a quick&easy solution and save yourself from typing newlines, you could opt for a list instead, e.g.:

def func(*args, **kwargs):
    string = '\n'.join([
        'first line of very long string and',
        'second line of the same long thing and',
        'third line of ...',
        'and so on...',
        ])
    print(string)
    return

JQUERY: Uncaught Error: Syntax error, unrecognized expression

This can also happen in safari if you try a selector with a missing ], for example

$('select[name="something"')

but interestingly, this same jquery selector with a missing bracket will work in chrome.

ValueError: unsupported pickle protocol: 3, python2 pickle can not load the file dumped by python 3 pickle?

You should write the pickled data with a lower protocol number in Python 3. Python 3 introduced a new protocol with the number 3 (and uses it as default), so switch back to a value of 2 which can be read by Python 2.

Check the protocolparameter in pickle.dump. Your resulting code will look like this.

pickle.dump(your_object, your_file, protocol=2)

There is no protocolparameter in pickle.load because pickle can determine the protocol from the file.

ALTER TABLE on dependent column

you can drop the Constraint which is restricting you. If the column has access to other table. suppose a view is accessing the column which you are altering then it wont let you alter the column unless you drop the view. and after making changes you can recreate the view.

enter image description here

Regular expression "^[a-zA-Z]" or "[^a-zA-Z]"

^[a-zA-Z] means any a-z or A-Z at the start of a line

[^a-zA-Z] means any character that IS NOT a-z OR A-Z

Logcat not displaying my log calls

I figured out I was automatically importing com.sileria.Log (from some library project) instead of android.util.Log, where the latter was the correct one. Check your imports as well.

How do I toggle an element's class in pure JavaScript?

2014 answer: classList.toggle() is the standard and supported by most browsers.

Older browsers can use use classlist.js for classList.toggle():

var menu = document.querySelector('.menu') // Using a class instead, see note below.
menu.classList.toggle('hidden-phone');

As an aside, you shouldn't be using IDs (they leak globals into the JS window object).

Checking Date format from a string in C#

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

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

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

Getting all selected checkboxes in an array

var chk_arr =  document.getElementsByName("chkRights[]");
var chklength = chk_arr.length;             

for(k=0;k< chklength;k++)
{
    chk_arr[k].checked = false;
} 

What does jQuery.fn mean?

fn literally refers to the jquery prototype.

This line of code is in the source code:

jQuery.fn = jQuery.prototype = {
 //list of functions available to the jQuery api
}

But the real tool behind fn is its availability to hook your own functionality into jQuery. Remember that jquery will be the parent scope to your function, so this will refer to the jquery object.

$.fn.myExtension = function(){
 var currentjQueryObject = this;
 //work with currentObject
 return this;//you can include this if you would like to support chaining
};

So here is a simple example of that. Lets say I want to make two extensions, one which puts a blue border, and which colors the text blue, and I want them chained.

jsFiddle Demo

$.fn.blueBorder = function(){
 this.each(function(){
  $(this).css("border","solid blue 2px");
 });
 return this;
};
$.fn.blueText = function(){
 this.each(function(){
  $(this).css("color","blue");
 });
 return this;
};

Now you can use those against a class like this:

$('.blue').blueBorder().blueText();

(I know this is best done with css such as applying different class names, but please keep in mind this is just a demo to show the concept)

This answer has a good example of a full fledged extension.

Difference between number and integer datatype in oracle dictionary views

This is what I got from oracle documentation, but it is for oracle 10g release 2:

When you define a NUMBER variable, you can specify its precision (p) and scale (s) so that it is sufficiently, but not unnecessarily, large. Precision is the number of significant digits. Scale can be positive or negative. Positive scale identifies the number of digits to the right of the decimal point; negative scale identifies the number of digits to the left of the decimal point that can be rounded up or down.

The NUMBER data type is supported by Oracle Database standard libraries and operates the same way as it does in SQL. It is used for dimensions and surrogates when a text or INTEGER data type is not appropriate. It is typically assigned to variables that are not used for calculations (like forecasts and aggregations), and it is used for variables that must match the rounding behavior of the database or require a high degree of precision. When deciding whether to assign the NUMBER data type to a variable, keep the following facts in mind in order to maximize performance:

  • Analytic workspace calculations on NUMBER variables is slower than other numerical data types because NUMBER values are calculated in software (for accuracy) rather than in hardware (for speed).
  • When data is fetched from an analytic workspace to a relational column that has the NUMBER data type, performance is best when the data already has the NUMBER data type in the analytic workspace because a conversion step is not required.

ASP.NET MVC - Attaching an entity of type 'MODELNAME' failed because another entity of the same type already has the same primary key value

Similar to what Luke Puplett is saying, the problem can be caused by not properly disposing or creating your context.

In my case, I had a class which accepted a context called ContextService:

public class ContextService : IDisposable
{
    private Context _context;

    public void Dispose()
    {
        _context.Dispose();
    }
    public ContextService(Context context)
    {
        _context = context;
    }
//... do stuff with the context

My context service had a function which updates an entity using an instantiated entity object:

        public void UpdateEntity(MyEntity myEntity, ICollection<int> ids)
        {
            var item = _context.Entry(myEntity);
            item.State = EntityState.Modified;
            item.Collection(x => x.RelatedEntities).Load();
            myEntity.RelatedEntities.Clear();
            foreach (var id in ids)
            {
                myEntity.RelatedEntities.Add(_context.RelatedEntities.Find(id));
            }
            _context.SaveChanges();
        }

All of this was fine, my controller where I initialized the service was the problem. My controller originally looked like this:

    private static NotificationService _service = 
        new NotificationService(new NotificationContext());
    public void Dispose()
    {
    }

I changed it to this and the error went away:

    private static NotificationService _service;
    public TemplateController()
    {
        _service = new NotificationService(new NotificationContext());
    }
    public void Dispose()
    {
        _service.Dispose();
    }

What does "O(1) access time" mean?

O(1) does not necessarily mean "quickly". It means that the time it takes is constant, and not based on the size of the input to the function. Constant could be fast or slow. O(n) means that the time the function takes will change in direct proportion to the size of the input to the function, denoted by n. Again, it could be fast or slow, but it will get slower as the size of n increases.

React Router Pass Param to Component

If you want to pass props to a component inside a route, the simplest way is by utilizing the render, like this:

<Route exact path="/details/:id" render={(props) => <DetailsPage globalStore={globalStore} {...props} /> } />

You can access the props inside the DetailPage using:

this.props.match
this.props.globalStore

The {...props} is needed to pass the original Route's props, otherwise you will only get this.props.globalStore inside the DetailPage.

Google Maps Android API v2 - Interactive InfoWindow (like in original android google maps)

For those who couldn't get choose007's answer up and running

If clickListener is not working properly at all times in chose007's solution, try to implement View.onTouchListener instead of clickListener. Handle touch event using any of the action ACTION_UP or ACTION_DOWN. For some reason, maps infoWindow causes some weird behaviour when dispatching to clickListeners.

infoWindow.findViewById(R.id.my_view).setOnTouchListener(new View.OnTouchListener() {
    @Override
    public boolean onTouch(View v, MotionEvent event) {
          int action = MotionEventCompat.getActionMasked(event);
          switch (action){
                case MotionEvent.ACTION_UP:
                    Log.d(TAG,"a view in info window clicked" );
                    break;
                }
                return true;
          }

Edit : This is how I did it step by step

First inflate your own infowindow (global variable) somewhere in your activity/fragment. Mine is within fragment. Also insure that root view in your infowindow layout is linearlayout (for some reason relativelayout was taking full width of screen in infowindow)

infoWindow = (ViewGroup) getActivity().getLayoutInflater().inflate(R.layout.info_window, null);
/* Other global variables used in below code*/
private HashMap<Marker,YourData> mMarkerYourDataHashMap = new HashMap<>();
private GoogleMap mMap;
private MapWrapperLayout mapWrapperLayout;

Then in onMapReady callback of google maps android api (follow this if you donot know what onMapReady is Maps > Documentation - Getting Started )

   @Override
    public void onMapReady(GoogleMap googleMap) {
       /*mMap is global GoogleMap variable in activity/fragment*/
        mMap = googleMap;
       /*Some function to set map UI settings*/ 
        setYourMapSettings();

MapWrapperLayout initialization http://stackoverflow.com/questions/14123243/google-maps-android-api-v2- interactive-infowindow-like-in-original-android-go/15040761#15040761 39 - default marker height 20 - offset between the default InfoWindow bottom edge and it's content bottom edge */

        mapWrapperLayout.init(mMap, Utils.getPixelsFromDp(mContext, 39 + 20));

        /*handle marker clicks separately - not necessary*/
       mMap.setOnMarkerClickListener(this);

       mMap.setInfoWindowAdapter(new GoogleMap.InfoWindowAdapter() {
                @Override
                public View getInfoWindow(Marker marker) {
                    return null;
                }

            @Override
            public View getInfoContents(Marker marker) {
                YourData data = mMarkerYourDataHashMap.get(marker);
                setInfoWindow(marker,data);
                mapWrapperLayout.setMarkerWithInfoWindow(marker, infoWindow);
                return infoWindow;
            }
        });
    }

SetInfoWindow method

private void setInfoWindow (final Marker marker, YourData data)
            throws NullPointerException{
        if (data.getVehicleNumber()!=null) {
            ((TextView) infoWindow.findViewById(R.id.VehicelNo))
                    .setText(data.getDeviceId().toString());
        }
        if (data.getSpeed()!=null) {
            ((TextView) infoWindow.findViewById(R.id.txtSpeed))
                    .setText(data.getSpeed());
        }

        //handle dispatched touch event for view click
        infoWindow.findViewById(R.id.any_view).setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                int action = MotionEventCompat.getActionMasked(event);
                switch (action) {
                    case MotionEvent.ACTION_UP:
                        Log.d(TAG,"any_view clicked" );
                        break;
                }
                return true;
            }
        });

Handle marker click separately

    @Override
    public boolean onMarkerClick(Marker marker) {
        Log.d(TAG,"on Marker Click called");
        marker.showInfoWindow();
        CameraPosition cameraPosition = new CameraPosition.Builder()
                .target(marker.getPosition())      // Sets the center of the map to Mountain View
                .zoom(10)
                .build();
        mMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition),1000,null);
        return true;
    }

How to convert a timezone aware string to datetime in Python without dateutil?

As of Python 3.7, datetime.datetime.fromisoformat() can handle your format:

>>> import datetime
>>> datetime.datetime.fromisoformat('2012-11-01T04:16:13-04:00')
datetime.datetime(2012, 11, 1, 4, 16, 13, tzinfo=datetime.timezone(datetime.timedelta(days=-1, seconds=72000)))

In older Python versions you can't, not without a whole lot of painstaking manual timezone defining.

Python does not include a timezone database, because it would be outdated too quickly. Instead, Python relies on external libraries, which can have a far faster release cycle, to provide properly configured timezones for you.

As a side-effect, this means that timezone parsing also needs to be an external library. If dateutil is too heavy-weight for you, use iso8601 instead, it'll parse your specific format just fine:

>>> import iso8601
>>> iso8601.parse_date('2012-11-01T04:16:13-04:00')
datetime.datetime(2012, 11, 1, 4, 16, 13, tzinfo=<FixedOffset '-04:00'>)

iso8601 is a whopping 4KB small. Compare that tot python-dateutil's 148KB.

As of Python 3.2 Python can handle simple offset-based timezones, and %z will parse -hhmm and +hhmm timezone offsets in a timestamp. That means that for a ISO 8601 timestamp you'd have to remove the : in the timezone:

>>> from datetime import datetime
>>> iso_ts = '2012-11-01T04:16:13-04:00'
>>> datetime.strptime(''.join(iso_ts.rsplit(':', 1)), '%Y-%m-%dT%H:%M:%S%z')
datetime.datetime(2012, 11, 1, 4, 16, 13, tzinfo=datetime.timezone(datetime.timedelta(-1, 72000)))

The lack of proper ISO 8601 parsing is being tracked in Python issue 15873.

How to use Bootstrap 4 in ASP.NET Core

Libman seems to be the tool preferred by Microsoft now. It is integrated in Visual Studio 2017(15.8).

This article describes how to use it and even how to set up a restore performed by the build process.

Bootstrap's documentation tells you what files you need in your project.

The following example should work as a configuration for libman.json.

{
  "version": "1.0",
  "defaultProvider": "cdnjs",
  "libraries": [
  {
    "library": "[email protected]",
    "destination": "wwwroot/lib/bootstrap",
    "files": [
    "js/bootstrap.bundle.js",
    "css/bootstrap.min.css"
    ]
  },
  {
    "library": "[email protected]",
    "destination": "wwwroot/lib/jquery",
    "files": [
      "jquery.min.js"
    ]
  }
]
}

Ping with timestamp on Windows CLI

You can do this in Bash (e.g. Linux or WSL):

ping 10.0.0.1 | while read line; do echo `date` - $line; done

Although it doesn't give the statistics you usually get when you hit ^C at the end.

Bootstrap - Uncaught TypeError: Cannot read property 'fn' of undefined

My way is importing the jquery library.

<script
  src="https://code.jquery.com/jquery-3.3.1.js"
  integrity="sha256-2Kok7MbOyxpgUVvAk/HJ2jigOSYS2auK4Pfzbm7uH60="
  crossorigin="anonymous"></script>

Print to the same line and not a new line?

for Console you'll probably need

sys.stdout.flush()

to force update. I think using , in print will block stdout from flushing and somehow it won't update

Is it possible to put a ConstraintLayout inside a ScrollView?

Don't forget that If you constraint some view's bottom to constraint layout's bottom.Scrollview could not scroll.

What is boilerplate code?

You can refer to it as "snippets" or more accurately "collection of snippets" . The term I think was coined from the press and printing industry, where they used actual "plates" and then re-used them as chunks again.. In modern-day internet it is a part of an ongoing (annoying IMHO) trend of using fancy terms for simple things in order to look more trendy and sophisticated . see RESPONSIVE = adaptable / fluid.

Debugging in Maven?

I thought I would expand on these answers for OSX and Linux folks (not that they need it):

I prefer to use mvnDebug too. But after OSX maverick destroyed my Java dev environment, I am starting from scratch and stubbled upon this post, and thought I would add to it.

$ mvnDebug vertx:runMod
-bash: mvnDebug: command not found

DOH! I have not set it up on this box after the new SSD drive and/or the reset of everything Java when I installed Maverick.

I use a package manager for OSX and Linux so I have no idea where mvn really lives. (I know for brief periods of time.. thanks brew.. I like that I don't know this.)

Let's see:

$ which mvn
/usr/local/bin/mvn

There you are... you little b@stard.

Now where did you get installed to:

$ ls -l /usr/local/bin/mvn

lrwxr-xr-x  1 root  wheel  39 Oct 31 13:00 /
                  /usr/local/bin/mvn -> /usr/local/Cellar/maven30/3.0.5/bin/mvn

Aha! So you got installed in /usr/local/Cellar/maven30/3.0.5/bin/mvn. You cheeky little build tool. No doubt by homebrew...

Do you have your little buddy mvnDebug with you?

$ ls /usr/local/Cellar/maven30/3.0.5/bin/mvnDebug 
/usr/local/Cellar/maven30/3.0.5/bin/mvnDebug

Good. Good. Very good. All going as planned.

Now move that little b@stard where I can remember him more easily.

$ ln -s /usr/local/Cellar/maven30/3.0.5/bin/mvnDebug /usr/local/bin/mvnDebug
  ln: /usr/local/bin/mvnDebug: Permission denied

Darn you computer... You will submit to my will. Do you know who I am? I am SUDO! BOW!

$ sudo ln -s /usr/local/Cellar/maven30/3.0.5/bin/mvnDebug /usr/local/bin/mvnDebug

Now I can use it from Eclipse (but why would I do that when I have IntelliJ!!!!)

$ mvnDebug vertx:runMod
Preparing to Execute Maven in Debug Mode
Listening for transport dt_socket at address: 8000

Internally mvnDebug uses this:

MAVEN_DEBUG_OPTS="-Xdebug -Xnoagent -Djava.compiler=NONE  \
-Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000"

So you could modify it (I usually debug on port 9090).

This blog explains how to setup Eclipse remote debugging (shudder)

http://javarevisited.blogspot.com/2011/02/how-to-setup-remote-debugging-in.html

Ditto Netbeans

https://blogs.oracle.com/atishay/entry/use_netbeans_to_debug_a

Ditto IntelliJ http://www.jetbrains.com/idea/webhelp/run-debug-configuration-remote.html

Here is some good docs on the -Xdebug command in general.

http://docs.oracle.com/cd/E13150_01/jrockit_jvm/jrockit/jrdocs/refman/optionX.html

"-Xdebug enables debugging capabilities in the JVM which are used by the Java Virtual Machine Tools Interface (JVMTI). JVMTI is a low-level debugging interface used by debuggers and profiling tools. With it, you can inspect the state and control the execution of applications running in the JVM."

"The subset of JVMTI that is most typically used by profilers is always available. However, the functionality used by debuggers to be able to step through the code and set breakpoints has some overhead associated with it and is not always available. To enable this functionality you must use the -Xdebug option."

-Xrunjdwp:transport=dt_socket,server=y,suspend=n myApp

Check out the docs on -Xrunjdwp too. You can enable it only when a certain exception is thrown for example. You can start it up suspended or running. Anyway.. I digress.

HTML5 Pre-resize images before uploading

Resizing images in a canvas element is generally bad idea since it uses the cheapest box interpolation. The resulting image noticeable degrades in quality. I'd recommend using http://nodeca.github.io/pica/demo/ which can perform Lanczos transformation instead. The demo page above shows difference between canvas and Lanczos approaches.

It also uses web workers for resizing images in parallel. There is also WEBGL implementation.

There are some online image resizers that use pica for doing the job, like https://myimageresizer.com

Getting the WordPress Post ID of current post

Try:

$post = $wp_query->post;

Then pass the function:

$post->ID

SQL RANK() over PARTITION on joined tables

As the rank doesn't depend at all from the contacts

RANKED_RSLTS

 QRY_ID  |  RES_ID  |  SCORE |  RANK
-------------------------------------
   A     |    1     |    15  |   3
   A     |    2     |    32  |   1
   A     |    3     |    29  |   2
   C     |    7     |    61  |   1
   C     |    9     |    30  |   2

Thus :

SELECT
    C.*
    ,R.SCORE
    ,MYRANK
FROM CONTACTS C LEFT JOIN
(SELECT  *,
 MYRANK = RANK() OVER (PARTITION BY QRY_ID ORDER BY SCORE DESC)
  FROM RSLTS)  R
ON C.RES_ID = R.RES_ID
AND C.QRY_ID = R.QRY_ID

CodeIgniter htaccess and URL rewrite issues

There are 3 steps to remove index.php.

  1. Make below changes in application/config.php file

    $config['base_url'] = 'http://'.$_SERVER['SERVER_NAME'].'/Your Ci folder_name';
    $config['index_page'] = '';
    $config['uri_protocol'] = 'AUTO';
    
  2. Make .htaccess file in your root directory using below code

    RewriteEngine on
    RewriteCond $1 !^(index\.php|resources|robots\.txt)
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)$ index.php/$1 [L,QSA]
    
  3. Enable the rewrite engine (if not already enabled)

    i. First, initiate it with the following command:

    a2enmod rewrite
    

    ii. Edit the file /etc/apache2/sites-enabled/000-default

    Change all AllowOverride None to AllowOverride All.

    Note: In latest version you need to change in /etc/apache2/apache2.conf file

    iii. Restart your server with the following command:

    sudo /etc/init.d/apache2 restart
    

Simulate a specific CURL in PostMan

A simpler approach would be:

  1. Open POSTMAN
  2. Click on "import" tab on the upper left side.
  3. Select the Raw Text option and paste your cURL command.
  4. Hit import and you will have the command in your Postman builder!
  5. Click Send to post the command

Hope this helps!

How to convert An NSInteger to an int?

Ta da:

NSInteger myInteger = 42;
int myInt = (int) myInteger;

NSInteger is nothing more than a 32/64 bit int. (it will use the appropriate size based on what OS/platform you're running)

How do I use a compound drawable instead of a LinearLayout that contains an ImageView and a TextView

if for some reason you need to add via code, you can use this:

mTextView.setCompoundDrawablesWithIntrinsicBounds(left, top, right, bottom);

where left, top, right bottom are Drawables

Deleting specific rows from DataTable

If you delete an item from a collection, that collection has been changed and you can't continue to enumerate through it.

Instead, use a For loop, such as:

for(int i = dtPerson.Rows.Count-1; i >= 0; i--)
{
    DataRow dr = dtPerson.Rows[i];
    if (dr["name"] == "Joe")
        dr.Delete();
}
dtPerson.AcceptChanges();

Note that you are iterating in reverse to avoid skipping a row after deleting the current index.

List files in local git repo?

This command:

git ls-tree --full-tree -r --name-only HEAD

lists all of the already committed files being tracked by your git repo.

Has Windows 7 Fixed the 255 Character File Path Limit?

You can get around that limit by using subst if you need to.

How do I check if the user is pressing a key?

Try this:

import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import javax.swing.JFrame;
import javax.swing.JTextField;

public class Main {

    public static void main(String[] argv) throws Exception {

    JTextField textField = new JTextField();

    textField.addKeyListener(new Keychecker());

    JFrame jframe = new JFrame();

    jframe.add(textField);

    jframe.setSize(400, 350);

    jframe.setVisible(true);

}

class Keychecker extends KeyAdapter {

    @Override
    public void keyPressed(KeyEvent event) {

        char ch = event.getKeyChar();

        System.out.println(event.getKeyChar());

    }

}

Could not find the main class, program will exit

I had this problem when I "upgraded" to Windows 7, which is 64-bit. My go to Java JRE is a 64-bit JVM. I had a 32-bit JRE on my machine for my browser, so I set up a system variable:

JRE32=C:\Program Files\Java\jre7

When I run:

"%JRE32\bin\java" -version

I get:

java version "1.7.0_51"
Java(TM) SE Runtime Environment (build 1.7.0_51-b13)
Java HotSpot(TM) Client VM (build 24.51-b03, mixed mode, sharing)

Which is a 32-bit JVM. It would say "Java HotSpot(TM) 64-Bit" otherwise.

I edited the "squirrel-sql.bat" file, REMarking out line 4 and adding line 5 as follows:

(4) rem set "IZPACK_JAVA=%JAVA_HOME%"
(5) set IZPACK_JAVA=%JRE32%

And now everything works, fine and dandy.

HAX kernel module is not installed

Actual error

enter image description here

follow bellow two simple steps to fix.

Step 1:- update "Intel x86 Emulator Accelerator (HAXM installer)" Ref. bellow img enter image description here

Step2:-

After installing the installer, you have to run it to install it on your system. Open the directory where your Android SDK is located. Go inside the extras\Intel\Hardware_Accelerated_Execution_Manager directory and you should see the intelhaxm-android.exe file.

enter image description here

If you got the error "This computer meets requirements for HAXM, but VT-x is not turned on..." during installation try to turn it on in your BIOS and check your antivirus software settings also. (Check this stackoverflow post). Thats it! its working for me.

SQL like search string starts with

Aside from using %, age of empires III to lower case is age of empires iii so your query should be:

select *
from games
where lower(title) like 'age of empires iii%'

How to disable JavaScript in Chrome Developer Tools?

The fast way:

1) just click on CTRL + SHIFT + P

2) fill the field by the 3 letters dis and will appear this box and select the item Disable Javascript

disable javascript .

that's all folks!

Servlet Mapping using web.xml

It allows servlets to have multiple servlet mappings:

<servlet>
    <servlet-name>Servlet1</servlet-name>
    <servlet-path>foo.Servlet</servlet-path>
</servlet>
<servlet-mapping>
    <servlet-name>Servlet1</servlet-name>
    <url-pattern>/enroll</url-pattern>
</servlet-mapping>
<servlet-mapping>
    <servlet-name>Servlet1</servlet-name>
    <url-pattern>/pay</url-pattern>
</servlet-mapping>
<servlet-mapping>
    <servlet-name>Servlet1</servlet-name>
    <url-pattern>/bill</url-pattern>
</servlet-mapping>

It allows filters to be mapped on the particular servlet:

<filter-mapping>
    <filter-name>Filter1</filter-name>
    <servlet-name>Servlet1</servlet-name>
</filter-mapping>

Your proposal would support neither of them. Note that the web.xml is read and parsed only once during application's startup, not on every HTTP request as you seem to think.

Since Servlet 3.0, there's the @WebServlet annotation which minimizes this boilerplate:

@WebServlet("/enroll")
public class Servlet1 extends HttpServlet {

See also:

Best design for a changelog / auditing database table?

We also log old and new values and the column they are from as well as the primary key of the table being audited in an audit detail table. Think what you need the audit table for? Not only do you want to know who made a change and when, but when a bad change happens, you want a fast way to put the data back.

While you are designing, you should write the code to recover data. When you need to recover, it is usually in a hurry, best to already be prepared.

How can I pass selected row to commandLink inside dataTable or ui:repeat?

In my view page:

<p:dataTable  ...>
<p:column>
<p:commandLink actionListener="#{inquirySOController.viewDetail}" 
               process="@this" update=":mainform:dialog_content"
           oncomplete="dlg2.show()">
    <h:graphicImage library="images" name="view.png"/>
    <f:param name="trxNo" value="#{item.map['trxNo']}"/>
</p:commandLink>
</p:column>
</p:dataTable>

backing bean

 public void viewDetail(ActionEvent e) {

    String trxNo = getFacesContext().getRequestParameterMap().get("trxNo");

    for (DTO item : list) {
        if (item.get("trxNo").toString().equals(trxNo)) {
            System.out.println(trxNo);
            setSelectedItem(item);
            break;
        }
    }
}

How to convert JSON to CSV format and store in a variable

I just wanted to add some code here for people in the future since I was trying to export JSON to a CSV document and download it.

I use $.getJSON to pull json data from an external page, but if you have a basic array, you can just use that.

This uses Christian Landgren's code to create the csv data.

$(document).ready(function() {
    var JSONData = $.getJSON("GetJsonData.php", function(data) {
        var items = data;
        const replacer = (key, value) => value === null ? '' : value; // specify how you want to handle null values here
        const header = Object.keys(items[0]);
        let csv = items.map(row => header.map(fieldName => JSON.stringify(row[fieldName], replacer)).join(','));
        csv.unshift(header.join(','));
        csv = csv.join('\r\n');

        //Download the file as CSV
        var downloadLink = document.createElement("a");
        var blob = new Blob(["\ufeff", csv]);
        var url = URL.createObjectURL(blob);
        downloadLink.href = url;
        downloadLink.download = "DataDump.csv";  //Name the file here
        document.body.appendChild(downloadLink);
        downloadLink.click();
        document.body.removeChild(downloadLink);
    });
});

Edit: It's worth noting that JSON.stringify will escape quotes in quotes by adding \". If you view the CSV in excel, it doesn't like that as an escape character.

You can add .replace(/\\"/g, '""') to the end of JSON.stringify(row[fieldName], replacer) to display this properly in excel (this will replace \" with "" which is what excel prefers).

Full Line: let csv = items.map(row => header.map(fieldName => (JSON.stringify(row[fieldName], replacer).replace(/\\"/g, '""'))).join(','));

Global variable Python classes

What you have is correct, though you will not call it global, it is a class attribute and can be accessed via class e.g Shape.lolwut or via an instance e.g. shape.lolwut but be careful while setting it as it will set an instance level attribute not class attribute

class Shape(object):
    lolwut = 1

shape = Shape()

print Shape.lolwut,  # 1
print shape.lolwut,  # 1

# setting shape.lolwut would not change class attribute lolwut 
# but will create it in the instance
shape.lolwut = 2

print Shape.lolwut,  # 1
print shape.lolwut,  # 2

# to change class attribute access it via class
Shape.lolwut = 3

print Shape.lolwut,  # 3
print shape.lolwut   # 2 

output:

1 1 1 2 3 2

Somebody may expect output to be 1 1 2 2 3 3 but it would be incorrect

How to read json file into java with simple JSON library

You can use jackson library and simply use these 3 lines to convert your json file to Java Object.

ObjectMapper mapper = new ObjectMapper();
InputStream is = Test.class.getResourceAsStream("/test.json");
testObj = mapper.readValue(is, Test.class);

How to dynamically update labels captions in VBA form?

If you want to use this in VBA:

For i = 1 To X
    UserForm1.Controls("Label" & i).Caption =  MySheet.Cells(i + 1, i).Value
Next

Remove all unused resources from an android project

Since Support for the ADT in Eclipse has ended, we have to use Android Studio.

In Android Studio 2.0+ use Refactor > Remove Unused Resources...

enter image description here

How do you overcome the HTML form nesting limitation?

In response to a question posted by Yar in a comment to his own answer, I present some JavaScript which will resize an iframe. For the case of a form button, it is safe to assume the iframe will be on the same domain. This is the code I use. You will have to alter the maths/constants for your own site:

function resizeIFrame(frame)
{
    try {
        innerDoc = ('contentDocument' in frame) ? frame.contentDocument : frame.contentWindow.document;
        if('style' in frame) {
            frame.style.width = Math.min(755, Math.ceil(innerDoc.body.scrollWidth)) + 'px';
            frame.style.height = Math.ceil(innerDoc.body.scrollHeight) + 'px';
        } else {
            frame.width = Math.ceil(innerDoc.body.scrollWidth);
            frame.height = Math.ceil(innerDoc.body.scrollHeight);
        }
    } catch(err) {
        window.status = err.message;
    }
}

Then call it like this:

<iframe ... frameborder="0" onload="if(window.parent && window.parent.resizeIFrame){window.parent.resizeIFrame(this);}"></iframe>

How to update/upgrade a package using pip?

use this code in teminal :

python -m pip install --upgrade PAKAGE_NAME #instead of PAKAGE_NAME 

for example i want update pip pakage :

 python -m pip install --upgrade pip

more example :

python -m pip install --upgrade selenium
python -m pip install --upgrade requests
...

What are "res" and "req" parameters in Express functions?

Request and response.

To understand the req, try out console.log(req);.

How to find length of dictionary values

Lets do some experimentation, to see how we could get/interpret the length of different dict/array values in a dict.

create our test dict, see list and dict comprehensions:

>>> my_dict = {x:[i for i in range(x)] for x in range(4)}
>>> my_dict
{0: [], 1: [0], 2: [0, 1], 3: [0, 1, 2]}

Get the length of the value of a specific key:

>>> my_dict[3]
[0, 1, 2]
>>> len(my_dict[3])
3

Get a dict of the lengths of the values of each key:

>>> key_to_value_lengths = {k:len(v) for k, v in my_dict.items()}
{0: 0, 1: 1, 2: 2, 3: 3}
>>> key_to_value_lengths[2]
2

Get the sum of the lengths of all values in the dict:

>>> [len(x) for x in my_dict.values()]
[0, 1, 2, 3]
>>> sum([len(x) for x in my_dict.values()])
6

Passing a local variable from one function to another

You can very easily use this to re-use the value of the variable in another function.

// Use this in source window.var1= oEvent.getSource().getBindingContext();

// Get value of var1 in destination var var2= window.var1;

Detecting Windows or Linux?

apache commons lang has a class SystemUtils.java you can use :

SystemUtils.IS_OS_LINUX
SystemUtils.IS_OS_WINDOWS

How to open a txt file and read numbers in Java

Read file, parse each line into an integer and store into a list:

List<Integer> list = new ArrayList<Integer>();
File file = new File("file.txt");
BufferedReader reader = null;

try {
    reader = new BufferedReader(new FileReader(file));
    String text = null;

    while ((text = reader.readLine()) != null) {
        list.add(Integer.parseInt(text));
    }
} catch (FileNotFoundException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
} finally {
    try {
        if (reader != null) {
            reader.close();
        }
    } catch (IOException e) {
    }
}

//print out the list
System.out.println(list);

UIImage: Resize, then Crop

This question seems to have been put to rest, but in my quest for a solution that I could more easily understand (and written in Swift), I arrived at this (also posted to: How to crop the UIImage?)


I wanted to be able to crop from a region based on an aspect ratio, and scale to a size based on a outer bounding extent. Here is my variation:

import AVFoundation
import ImageIO

class Image {

    class func crop(image:UIImage, crop source:CGRect, aspect:CGSize, outputExtent:CGSize) -> UIImage {

        let sourceRect = AVMakeRectWithAspectRatioInsideRect(aspect, source)
        let targetRect = AVMakeRectWithAspectRatioInsideRect(aspect, CGRect(origin: CGPointZero, size: outputExtent))

        let opaque = true, deviceScale:CGFloat = 0.0 // use scale of device's main screen
        UIGraphicsBeginImageContextWithOptions(targetRect.size, opaque, deviceScale)

        let scale = max(
            targetRect.size.width / sourceRect.size.width,
            targetRect.size.height / sourceRect.size.height)

        let drawRect = CGRect(origin: -sourceRect.origin * scale, size: image.size * scale)
        image.drawInRect(drawRect)

        let scaledImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()

        return scaledImage
    }
}

There are a couple things that I found confusing, the separate concerns of cropping and resizing. Cropping is handled with the origin of the rect that you pass to drawInRect, and scaling is handled by the size portion. In my case, I needed to relate the size of the cropping rect on the source, to my output rect of the same aspect ratio. The scale factor is then output / input, and this needs to be applied to the drawRect (passed to drawInRect).

One caveat is that this approach effectively assumes that the image you are drawing is larger than the image context. I have not tested this, but I think you can use this code to handle cropping / zooming, but explicitly defining the scale parameter to be the aforementioned scale parameter. By default, UIKit applies a multiplier based on the screen resolution.

Finally, it should be noted that this UIKit approach is higher level than CoreGraphics / Quartz and Core Image approaches, and seems to handle image orientation issues. It is also worth mentioning that it is pretty fast, second to ImageIO, according to this post here: http://nshipster.com/image-resizing/

How do I lock the orientation to portrait mode in a iPhone Web Application?

I like the idea of telling the user to put his phone back into portrait mode. Like it's mentioned here: http://tech.sarathdr.com/featured/prevent-landscape-orientation-of-iphone-web-apps/ ...but utilising CSS instead of JavaScript.

How to store .pdf files into MySQL as BLOBs using PHP?

//Pour inserer :
            $pdf = addslashes(file_get_contents($_FILES['inputname']['tmp_name']));
            $filetype = addslashes($_FILES['inputname']['type']);//pour le test 
            $namepdf = addslashes($_FILES['inputname']['name']);            
            if (substr($filetype, 0, 11) == 'application'){
            $mysqli->query("insert into tablepdf(pdf_nom,pdf)value('$namepdf','$pdf')");
            }
//Pour afficher :
            $row = $mysqli->query("SELECT * FROM tablepdf where id=(select max(id) from tablepdf)");
            foreach($row as $result){
                 $file=$result['pdf'];
            }
            header('Content-type: application/pdf');
            echo file_get_contents('data:application/pdf;base64,'.base64_encode($file));

How to read integer value from the standard input in Java

You can use java.util.Scanner (API):

import java.util.Scanner;

//...

Scanner in = new Scanner(System.in);
int num = in.nextInt();

It can also tokenize input with regular expression, etc. The API has examples and there are many others in this site (e.g. How do I keep a scanner from throwing exceptions when the wrong type is entered?).

java.lang.ClassCastException: java.util.LinkedHashMap cannot be cast to com.testing.models.Account

The way I could mitigate the JSON Array to collection of LinkedHashMap objects problem was by using CollectionType rather than a TypeReference . This is what I did and worked:

public <T> List<T> jsonArrayToObjectList(String json, Class<T> tClass) throws IOException {
    ObjectMapper mapper = new ObjectMapper();
    CollectionType listType = mapper.getTypeFactory().constructCollectionType(ArrayList.class, tClass);
    List<T> ts = mapper.readValue(json, listType);
    LOGGER.debug("class name: {}", ts.get(0).getClass().getName());
    return ts;
}

Using the TypeReference, I was still getting an ArrayList of LinkedHashMaps, i.e. does not work:

public <T> List<T> jsonArrayToObjectList(String json, Class<T> tClass) throws IOException {
    ObjectMapper mapper = new ObjectMapper();
    List<T> ts = mapper.readValue(json, new TypeReference<List<T>>(){});
    LOGGER.debug("class name: {}", ts.get(0).getClass().getName());
    return ts;
}

How to regex in a MySQL query

In my case (Oracle), it's WHERE REGEXP_LIKE(column, 'regex.*'). See here:

SQL Function

Description


REGEXP_LIKE

This function searches a character column for a pattern. Use this function in the WHERE clause of a query to return rows matching the regular expression you specify.

...

REGEXP_REPLACE

This function searches for a pattern in a character column and replaces each occurrence of that pattern with the pattern you specify.

...

REGEXP_INSTR

This function searches a string for a given occurrence of a regular expression pattern. You specify which occurrence you want to find and the start position to search from. This function returns an integer indicating the position in the string where the match is found.

...

REGEXP_SUBSTR

This function returns the actual substring matching the regular expression pattern you specify.

(Of course, REGEXP_LIKE only matches queries containing the search string, so if you want a complete match, you'll have to use '^$' for a beginning (^) and end ($) match, e.g.: '^regex.*$'.)

Big-oh vs big-theta

There are a lot of good answers here but I noticed something was missing. Most answers seem to be implying that the reason why people use Big O over Big Theta is a difficulty issue, and in some cases this may be true. Often a proof that leads to a Big Theta result is far more involved than one that results in Big O. This usually holds true, but I do not believe this has a large relation to using one analysis over the other.

When talking about complexity we can say many things. Big O time complexity is just telling us what an algorithm is guarantied to run within, an upper bound. Big Omega is far less often discussed and tells us the minimum time an algorithm is guarantied to run, a lower bound. Now Big Theta tells us that both of these numbers are in fact the same for a given analysis. This tells us that the application has a very strict run time, that can only deviate by a value asymptoticly less than our complexity. Many algorithms simply do not have upper and lower bounds that happen to be asymptoticly equivalent.

So as to your question using Big O in place of Big Theta would technically always be valid, while using Big Theta in place of Big O would only be valid when Big O and Big Omega happened to be equal. For instance insertion sort has a time complexity of Big ? at n^2, but its best case scenario puts its Big Omega at n. In this case it would not be correct to say that its time complexity is Big Theta of n or n^2 as they are two different bounds and should be treated as such.

Import XXX cannot be resolved for Java SE standard classes

This is an issue relating JRE.In my case (eclipse Luna with Maven plugin, JDK 7) I solved this by making following change in pom.xml and then Maven Update Project.

from:

 <configuration>
        <source>1.8</source>
        <target>1.8</target>
</configuration>

to:

 <configuration>
        <source>1.7</source>
        <target>1.7</target>
</configuration>

Screenshot showing problem in JRE: enter image description here

How to find out "The most popular repositories" on Github?

Ranking by stars or forks is not working. Each promoted or created by a famous company repository is popular at the beginning. Also it is possible to have a number of them which are in trend right now (publications, marketing, events). It doesn't mean that those repositories are useful/popular.

The gitmostwanted.com project (repo at github) analyses GH Archive data in order to highlight the most interesting repositories and exclude others. Just compare the results with mentioned resources.

Open a folder using Process.Start

You're escaping the backslash when the at sign does that for you.

System.Diagnostics.Process.Start("explorer.exe",@"c:\teste");

How to include SCSS file in HTML

You can't have a link to SCSS File in your HTML page.You have to compile it down to CSS First. No there are lots of video tutorials you might want to check out. Lynda provides great video tutorials on SASS. there are also free screencasts you can google...

For official documentation visit this site http://sass-lang.com/documentation/file.SASS_REFERENCE.html And why have you chosen notepad to write Sass?? you can easily download some free text editors for better code handling.

Sending data back to the Main Activity in Android

I have created simple demo class for your better reference.

FirstActivity.java

 public class FirstActivity extends AppCompatActivity {

    private static final String TAG = FirstActivity.class.getSimpleName();
    private static final int REQUEST_CODE = 101;
    private Button btnMoveToNextScreen;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        btnMoveToNextScreen = (Button) findViewById(R.id.btnMoveToNext);
        btnMoveToNextScreen.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent mIntent = new Intent(FirstActivity.this, SecondActivity.class);
                startActivityForResult(mIntent, REQUEST_CODE);
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if(resultCode == RESULT_OK){
            if(requestCode == REQUEST_CODE && data !=null) {
                String strMessage = data.getStringExtra("keyName");
                Log.i(TAG, "onActivityResult: message >>" + strMessage);
            }
        }

    }
}

And here is SecondActivity.java

public class SecondActivity extends AppCompatActivity {

    private static final String TAG = SecondActivity.class.getSimpleName();
    private Button btnMoveToPrevious;
    private EditText editText;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_second);

        editText = (EditText) findViewById(R.id.editText);

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

                String message = editText.getEditableText().toString();

                Intent mIntent = new Intent();
                mIntent.putExtra("keyName", message);
                setResult(RESULT_OK, mIntent);
                finish();

            }
        });

    }
}

CSS transition between left -> right and top -> bottom positions

In more modern browsers (including IE 10+) you can now use calc():

.moveto {
  top: 0px;
  left: calc(100% - 50px);
}

Compare 2 JSON objects

Simply parsing the JSON and comparing the two objects is not enough because it wouldn't be the exact same object references (but might be the same values).

You need to do a deep equals.

From http://threebit.net/mail-archive/rails-spinoffs/msg06156.html - which seems the use jQuery.

Object.extend(Object, {
   deepEquals: function(o1, o2) {
     var k1 = Object.keys(o1).sort();
     var k2 = Object.keys(o2).sort();
     if (k1.length != k2.length) return false;
     return k1.zip(k2, function(keyPair) {
       if(typeof o1[keyPair[0]] == typeof o2[keyPair[1]] == "object"){
         return deepEquals(o1[keyPair[0]], o2[keyPair[1]])
       } else {
         return o1[keyPair[0]] == o2[keyPair[1]];
       }
     }).all();
   }
});

Usage:

var anObj = JSON.parse(jsonString1);
var anotherObj= JSON.parse(jsonString2);

if (Object.deepEquals(anObj, anotherObj))
   ...

How to get current date in jquery?

The jQuery plugin page is down. So manually:

function strpad00(s)
{
    s = s + '';
    if (s.length === 1) s = '0'+s;
    return s;
}

var now = new Date();
var currentDate = now.getFullYear()+ "/" + strpad00(now.getMonth()+1) + "/" + strpad00(now.getDate());
console.log(currentDate );

Adding Lombok plugin to IntelliJ project

To add the Lombok IntelliJ plugin to add lombok support IntelliJ:

  • Go to File > Settings > Plugins
  • Click on Browse repositories...
  • Search for Lombok Plugin
  • Click on Install plugin
  • Restart IntelliJ IDEA

java: HashMap<String, int> not working

You cannot use primitive types in HashMap. int, or double don't work. You have to use its enclosing type. for an example

Map<String,Integer> m = new HashMap<String,Integer>();

Now both are objects, so this will work.

How to do a HTTP HEAD request from the windows command line?

There is a Win32 port of wget that works decently.

PowerShell's Invoke-WebRequest -Method Head would work as well.

Check if checkbox is checked with jQuery

IDs must be unique in your document, meaning that you shouldn't do this:

<input type="checkbox" name="chk[]" id="chk[]" value="Apples" />
<input type="checkbox" name="chk[]" id="chk[]" value="Bananas" />

Instead, drop the ID, and then select them by name, or by a containing element:

<fieldset id="checkArray">
    <input type="checkbox" name="chk[]" value="Apples" />

    <input type="checkbox" name="chk[]" value="Bananas" />
</fieldset>

And now the jQuery:

var atLeastOneIsChecked = $('#checkArray:checkbox:checked').length > 0;
//there should be no space between identifier and selector

// or, without the container:

var atLeastOneIsChecked = $('input[name="chk[]"]:checked').length > 0;

Parameter in like clause JPQL

  1. Use below JPQL query.
select i from Instructor i where i.address LIKE CONCAT('%',:address ,'%')");
  1. Use below Criteria code for the same:
@Test
public void findAllHavingAddressLike() {
    CriteriaBuilder cb = criteriaUtils.criteriaBuilder();
    CriteriaQuery<Instructor> cq = cb.createQuery(Instructor.class);
    Root<Instructor> root = cq.from(Instructor.class);
    printResultList(cq.select(root).where(
        cb.like(root.get(Instructor_.address), "%#1074%")));
}

/usr/lib/x86_64-linux-gnu/libstdc++.so.6: version CXXABI_1.3.8' not found

For all those stuck with a similar problem, run the following:

LD_LIBRARY_PATH=/usr/local/lib64/:$LD_LIBRARY_PATH
export LD_LIBRARY_PATH

When you compile and install GCC it does put the libraries here but that's it. As the FAQs say ( http://gcc.gnu.org/onlinedocs/libstdc++/faq.html#faq.how_to_set_paths ) you need to add it.

I assumed "How do I insure that the dynamically linked library will be found? " meant "how do I make sure it is always found" not "it wont be found, you need to do this"

For those who don't bother setting a prefix, it is /usr/local/lib64

You can find this mentioned briefly when you install gcc if you read the make output:

Libraries have been installed in:
   /usr/local/lib/../lib32
If you ever happen to want to link against installed libraries
in a given directory, LIBDIR, you must either use libtool, and
specify the full pathname of the library, or use the `-LLIBDIR'
flag during linking and do at least one of the following:
   - add LIBDIR to the `LD_LIBRARY_PATH' environment variable
     during execution
   - add LIBDIR to the `LD_RUN_PATH' environment variable
     during linking
   - use the `-Wl,-rpath -Wl,LIBDIR' linker flag
   - have your system administrator add LIBDIR to `/etc/ld.so.conf'

See any operating system documentation about shared libraries for
more information, such as the ld(1) and ld.so(8) manual pages. 

Grr that was simple! Also "if you ever happen to want to link against the installed libraries" - seriously?

Static nested class in Java, why?

Non static inner classes can result in memory leaks while static inner class will protect against them. If the outer class holds considerable data, it can lower the performance of the application.

Getting rid of bullet points from <ul>

The following code

_x000D_
_x000D_
#menu li{
  list-style-type: none;
}
_x000D_
<ul id="menu">
    <li>Root node 1</li>
    <li>Root node 2</li>
</ul>
_x000D_
_x000D_
_x000D_

will produce this output:

output is

HTML: How to center align a form

simple way:Add a "center" tag before the form tag

JAX-WS - Adding SOAP Headers

I'm adding this answer because none of the others worked for me.

I had to add a Header Handler to the Proxy:

import java.util.Set;
import java.util.TreeSet;

import javax.xml.namespace.QName;
import javax.xml.soap.SOAPElement;
import javax.xml.soap.SOAPEnvelope;
import javax.xml.soap.SOAPFactory;
import javax.xml.soap.SOAPHeader;
import javax.xml.ws.handler.MessageContext;
import javax.xml.ws.handler.soap.SOAPHandler;
import javax.xml.ws.handler.soap.SOAPMessageContext;

public class SOAPHeaderHandler implements SOAPHandler<SOAPMessageContext> {

    private final String authenticatedToken;

    public SOAPHeaderHandler(String authenticatedToken) {
        this.authenticatedToken = authenticatedToken;
    }

    public boolean handleMessage(SOAPMessageContext context) {
        Boolean outboundProperty =
                (Boolean) context.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY);
        if (outboundProperty.booleanValue()) {
            try {
                SOAPEnvelope envelope = context.getMessage().getSOAPPart().getEnvelope();
                SOAPFactory factory = SOAPFactory.newInstance();
                String prefix = "urn";
                String uri = "urn:xxxx";
                SOAPElement securityElem =
                        factory.createElement("Element", prefix, uri);
                SOAPElement tokenElem =
                        factory.createElement("Element2", prefix, uri);
                tokenElem.addTextNode(authenticatedToken);
                securityElem.addChildElement(tokenElem);
                SOAPHeader header = envelope.addHeader();
                header.addChildElement(securityElem);
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            // inbound
        }
        return true;
    }

    public Set<QName> getHeaders() {
        return new TreeSet();
    }

    public boolean handleFault(SOAPMessageContext context) {
        return false;
    }

    public void close(MessageContext context) {
        //
    }
}

In the proxy, I just add the Handler:

BindingProvider bp =(BindingProvider)basicHttpBindingAuthentication;
bp.getBinding().getHandlerChain().add(new SOAPHeaderHandler(authenticatedToken));
bp.getBinding().getHandlerChain().add(new SOAPLoggingHandler());

How to convert any date format to yyyy-MM-dd

Try this code:

 lblUDate.Text = DateTime.Parse(ds.Tables[0].Rows[0]["AppMstRealPaidTime"].ToString()).ToString("yyyy-MM-dd");

Typescript interface default values

My solution:

I have created wrapper over Object.assign to fix typing issues.

export function assign<T>(...args: T[] | Partial<T>[]): T {
  return Object.assign.apply(Object, [{}, ...args]);
}

Usage:

env.base.ts

export interface EnvironmentValues {
export interface EnvironmentValues {
  isBrowser: boolean;
  apiURL: string;
}

export const enviromentBaseValues: Partial<EnvironmentValues> = {
  isBrowser: typeof window !== 'undefined',
};

export default enviromentBaseValues;

env.dev.ts

import { EnvironmentValues, enviromentBaseValues } from './env.base';
import { assign } from '../utilities';

export const enviromentDevValues: EnvironmentValues = assign<EnvironmentValues>(
  {
    apiURL: '/api',
  },
  enviromentBaseValues
);

export default enviromentDevValues;

How to globally replace a forward slash in a JavaScript string?

Use a regex literal with the g modifier, and escape the forward slash with a backslash so it doesn't clash with the delimiters.

var str = 'some // slashes', replacement = '';
var replaced = str.replace(/\//g, replacement);

How to split data into trainset and testset randomly?

A quick note for the answer from @subin sahayam

 import random
 file=open("datafile.txt","r")
 data=list()
 for line in file:
    data.append(line.split(#your preferred delimiter))
 file.close()
 random.shuffle(data)
 train_data = data[:int((len(data)+1)*.80)] #Remaining 80% to training set
 test_data = data[int(len(data)*.80+1):] #Splits 20% data to test set

If your list size is a even number, you should not add the 1 in the code below. Instead, you need to check the size of the list first and then determine if you need to add the 1.

test_data = data[int(len(data)*.80+1):]

No grammar constraints (DTD or XML schema) detected for the document

Have you tried to add a schema to xml catalog?

in eclipse to avoid the "no grammar constraints (dtd or xml schema) detected for the document." i use to add an xsd schema file to the xml catalog under

"Window \ preferences \ xml \ xml catalog \ User specified entries".

Click "Add" button on the right.


Example:

<?xml version="1.0" encoding="UTF-8"?>
<HolidayRequest xmlns="http://mycompany.com/hr/schemas">
    <Holiday>
        <StartDate>2006-07-03</StartDate>
        <EndDate>2006-07-07</EndDate>
    </Holiday>
    <Employee>
        <Number>42</Number>
        <FirstName>Arjen</FirstName>
        <LastName>Poutsma</LastName>
    </Employee>
</HolidayRequest>

From this xml i have generated and saved an xsd under: /home/my_user/xsd/my_xsd.xsd

As Location: /home/my_user/xsd/my_xsd.xsd

As key type: Namespace name

As key: http://mycompany.com/hr/schemas


Close and reopen the xml file and do some changes to violate the schema, you should be notified

Using Caps Lock as Esc in Mac OS X

Seil isn't yet available on macOS Sierra (10.12 beta). As such, I've been using Keyboard Maestro with these settings: enter image description here

Credit to this github comment: https://github.com/tekezo/Seil/issues/68#issuecomment-230131664

Should I use 'has_key()' or 'in' on Python dicts?

Expanding on Alex Martelli's performance tests with Adam Parkin's comments...

$ python3.5 -mtimeit -s'd=dict.fromkeys(range( 99))' 'd.has_key(12)'
Traceback (most recent call last):
  File "/usr/local/Cellar/python3/3.5.2_3/Frameworks/Python.framework/Versions/3.5/lib/python3.5/timeit.py", line 301, in main
    x = t.timeit(number)
  File "/usr/local/Cellar/python3/3.5.2_3/Frameworks/Python.framework/Versions/3.5/lib/python3.5/timeit.py", line 178, in timeit
    timing = self.inner(it, self.timer)
  File "<timeit-src>", line 6, in inner
    d.has_key(12)
AttributeError: 'dict' object has no attribute 'has_key'

$ python2.7 -mtimeit -s'd=dict.fromkeys(range(  99))' 'd.has_key(12)'
10000000 loops, best of 3: 0.0872 usec per loop

$ python2.7 -mtimeit -s'd=dict.fromkeys(range(1999))' 'd.has_key(12)'
10000000 loops, best of 3: 0.0858 usec per loop

$ python3.5 -mtimeit -s'd=dict.fromkeys(range(  99))' '12 in d'
10000000 loops, best of 3: 0.031 usec per loop

$ python3.5 -mtimeit -s'd=dict.fromkeys(range(1999))' '12 in d'
10000000 loops, best of 3: 0.033 usec per loop

$ python3.5 -mtimeit -s'd=dict.fromkeys(range(  99))' '12 in d.keys()'
10000000 loops, best of 3: 0.115 usec per loop

$ python3.5 -mtimeit -s'd=dict.fromkeys(range(1999))' '12 in d.keys()'
10000000 loops, best of 3: 0.117 usec per loop

What does the following Oracle error mean: invalid column index

It sounds like you're trying to SELECT a column that doesn't exist.

Perhaps you're trying to ORDER BY a column that doesn't exist?

Any typos in your SQL statement?

Can scripts be inserted with innerHTML?

Execute (Java Script) tag from innerHTML

Replace your script element with div having a class attribute class="javascript" and close it with </div>

Don't change the content that you want to execute (previously it was in script tag and now it is in div tag)

Add a style in your page...

<style type="text/css"> .javascript { display: none; } </style>

Now run eval using jquery(Jquery js should be already included)

   $('.javascript').each(function() {
      eval($(this).text());

    });`

You can explore more here, at my blog.

EditText, clear focus on touch outside

To lose the focus when other view is touched , both views should be set as view.focusableInTouchMode(true).

But it seems that use focuses in touch mode are not recommended. Please take a look here: http://android-developers.blogspot.com/2008/12/touch-mode.html

printf() formatting for hex

The # part gives you a 0x in the output string. The 0 and the x count against your "8" characters listed in the 08 part. You need to ask for 10 characters if you want it to be the same.

int i = 7;

printf("%#010x\n", i);  // gives 0x00000007
printf("0x%08x\n", i);  // gives 0x00000007
printf("%#08x\n", i);   // gives 0x000007

Also changing the case of x, affects the casing of the outputted characters.

printf("%04x", 4779); // gives 12ab
printf("%04X", 4779); // gives 12AB

Angular2 Material Dialog css, dialog size

You can inspect the dialog element with dev tools and see what classes are applied on mdDialog.

For example, .md-dialog-container is the main classe of the MDDialog and has padding: 24px

you can create a custom CSS to overwrite whatever you want

.md-dialog-container {
      background-color: #000;
      width: 250px;
      height: 250px
}

In my opinion this is not a good option and probably goes against Material guide but since it doesn't have all features it has in it's previous version, you should do what you think is best for you.

Reading file line by line (with space) in Unix Shell scripting - Issue

Try this,

IFS=''
while read line
do
    echo $line
done < file.txt

EDIT:

From man bash

IFS - The Internal Field Separator that is used for word
splitting after expansion and to split lines into words
with  the  read  builtin  command. The default value is
``<space><tab><newline>''

How to check the version of GitLab?

The easiest way is to paste the following command:

cat /opt/gitlab/version-manifest.txt | head -n 1

and there you get the version installed. :)

create a trusted self-signed SSL cert for localhost (for use with Express/Node)

Here's what's working for me

on windows

1) Add this to your %WINDIR%\System32\drivers\etc\hosts file: 127.0.0.1 localdev.YOURSITE.net (cause browser have issues with 'localhost' (for cross origin scripting)

Windows Vista and Windows 7 Vista and Windows 7 use User Account Control (UAC) so Notepad must be run as Administrator.

  1. Click Start -> All Programs -> Accessories

  2. Right click Notepad and select Run as administrator

  3. Click Continue on the "Windows needs your permission" UAC window.

  4. When Notepad opens Click File -> Open

  5. In the filename field type C:\Windows\System32\Drivers\etc\hosts

  6. Click Open

  7. Add this to your %WINDIR%\System32\drivers\etc\hosts file: 127.0.0.1 localdev.YOURSITE.net

  8. Save

  9. Close and restart browsers

On Mac or Linux:

  1. Open /etc/hosts with su permission
  2. Add 127.0.0.1 localdev.YOURSITE.net
  3. Save it

When developing you use localdev.YOURSITE.net instead of localhost so if you are using run/debug configurations in your ide be sure to update it.

Use ".YOURSITE.net" as cookiedomain (with a dot in the beginning) when creating the cookiem then it should work with all subdomains.

2) create the certificate using that localdev.url

TIP: If you have issues generating certificates on windows, use a VirtualBox or Vmware machine instead.

3) import the certificate as outlined on http://www.charlesproxy.com/documentation/using-charles/ssl-certificates/

Failed to load resource: the server responded with a status of 404 (Not Found) css

you have defined the public dir in app root/public

app.use(express.static(__dirname + '/public')); 

so you have to use:

./css/main.css

Change a web.config programmatically with C# (.NET)

Since web.config file is xml file you can open web.config using xmldocument class. Get the node from that xml file that you want to update and then save xml file.

here is URL that explains in more detail how you can update web.config file programmatically.

http://patelshailesh.com/index.php/update-web-config-programmatically

Note: if you make any changes to web.config, ASP.NET detects that changes and it will reload your application(recycle application pool) and effect of that is data kept in Session, Application, and Cache will be lost (assuming session state is InProc and not using a state server or database).

Can a website detect when you are using Selenium with chromedriver?

Example of how it's implemented on wellsfargo.com:

try {
 if (window.document.documentElement.getAttribute("webdriver")) return !+[]
} catch (IDLMrxxel) {}
try {
 if ("_Selenium_IDE_Recorder" in window) return !+""
} catch (KknKsUayS) {}
try {
 if ("__webdriver_script_fn" in document) return !+""

How can I search (case-insensitive) in a column using LIKE wildcard?

You can use the following method

 private function generateStringCondition($value = '',$field = '', $operator = '', $regex = '', $wildcardStart = '', $wildcardEnd = ''){
        if($value != ''){
            $where = " $field $regex '$wildcardStart".strtolower($value)."$wildcardEnd' ";

            $searchArray = explode(' ', $value);

            if(sizeof($searchArray) > 1){

                foreach ($searchArray as $key=>$value){
                    $where .="$operator $field $regex '$wildcardStart".strtolower($value)."$wildcardEnd'";
                }

            }

        }else{
            $where = '';
        }
        return $where;
    }

use this method like below

   $where =  $this->generateStringCondition($yourSearchString,  'LOWER(columnName)','or', 'like',  '%', '%');
  $sql = "select * from table $where";

CSS to make HTML page footer stay at bottom of the page with a minimum height, but not overlap the page

A very simple approach which works great cross browser is this:

http://matthewjamestaylor.com/blog/keeping-footers-at-the-bottom-of-the-page

_x000D_
_x000D_
html,_x000D_
body {_x000D_
   margin:0;_x000D_
   padding:0;_x000D_
   height:100%;_x000D_
}_x000D_
#container {_x000D_
   min-height:100%;_x000D_
   position:relative;_x000D_
}_x000D_
#header {_x000D_
   background:#ff0;_x000D_
   padding:10px;_x000D_
}_x000D_
#body {_x000D_
   padding:10px;_x000D_
   padding-bottom:60px;   /* Height of the footer */_x000D_
}_x000D_
#footer {_x000D_
   position:absolute;_x000D_
   bottom:0;_x000D_
   width:100%;_x000D_
   height:60px;   /* Height of the footer */_x000D_
   background:#6cf;_x000D_
}
_x000D_
<div id="container">_x000D_
   <div id="header">header</div>_x000D_
   <div id="body">body</div>_x000D_
   <div id="footer">footer</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to send a Post body in the HttpClient request in Windows Phone 8?

I implemented it in the following way. I wanted a generic MakeRequest method that could call my API and receive content for the body of the request - and also deserialise the response into the desired type. I create a Dictionary<string, string> object to house the content to be submitted, and then set the HttpRequestMessage Content property with it:

Generic method to call the API:

    private static T MakeRequest<T>(string httpMethod, string route, Dictionary<string, string> postParams = null)
    {
        using (var client = new HttpClient())
        {
            HttpRequestMessage requestMessage = new HttpRequestMessage(new HttpMethod(httpMethod), $"{_apiBaseUri}/{route}");

            if (postParams != null)
                requestMessage.Content = new FormUrlEncodedContent(postParams);   // This is where your content gets added to the request body


            HttpResponseMessage response = client.SendAsync(requestMessage).Result;

            string apiResponse = response.Content.ReadAsStringAsync().Result;
            try
            {
                // Attempt to deserialise the reponse to the desired type, otherwise throw an expetion with the response from the api.
                if (apiResponse != "")
                    return JsonConvert.DeserializeObject<T>(apiResponse);
                else
                    throw new Exception();
            }
            catch (Exception ex)
            {
                throw new Exception($"An error ocurred while calling the API. It responded with the following message: {response.StatusCode} {response.ReasonPhrase}");
            }
        }
    }

Call the method:

    public static CardInformation ValidateCard(string cardNumber, string country = "CAN")
    { 
        // Here you create your parameters to be added to the request content
        var postParams = new Dictionary<string, string> { { "cardNumber", cardNumber }, { "country", country } };
        // make a POST request to the "cards" endpoint and pass in the parameters
        return MakeRequest<CardInformation>("POST", "cards", postParams);
    }

How to center horizontally div inside parent div

You can use the "auto" value for the left and right margins to let the browser distribute the available space equally at both sides of the inner div:

<div id='parent' style='width: 100%;'>
   <div id='child' style='width: 50px; height: 100px; margin-left: auto; margin-right: auto'>Text</div>
</div>

How do I specify row heights in CSS Grid layout?

One of the Related posts gave me the (simple) answer.

Apparently the auto value on the grid-template-rows property does exactly what I was looking for.

.grid {
    display:grid;
    grid-template-columns: 1fr 1.5fr 1fr;
    grid-template-rows: auto auto 1fr 1fr 1fr auto auto;
    grid-gap:10px;
    height: calc(100vh - 10px);
}

Displaying a Table in Django from Database

$ pip install django-tables2

settings.py

INSTALLED_APPS , 'django_tables2'
TEMPLATES.OPTIONS.context-processors , 'django.template.context_processors.request'

models.py

class hotel(models.Model):
     name = models.CharField(max_length=20)

views.py

from django.shortcuts import render

def people(request):
    istekler = hotel.objects.all()
    return render(request, 'list.html', locals())

list.html

{# yonetim/templates/list.html #}
{% load render_table from django_tables2 %}
{% load static %}
<!doctype html>
<html>
    <head>
        <link rel="stylesheet" href="{% static 
'ticket/static/css/screen.css' %}" />
    </head>
    <body>
        {% render_table istekler %}
    </body>
</html>

How to get values from IGrouping

var groups = list.GroupBy(x => x.ID);

Can anybody suggest how to get the values (List) from an IGrouping<int, smth> in such a context?

"IGrouping<int, smth> group" is actually an IEnumerable with a key, so you either:

  • iterate on the group or
  • use group.ToList() to convert it to a List
foreach (IGrouping<int, smth> group in groups)
{
   var thisIsYourGroupKey = group.Key; 
   List<smth> list = group.ToList();     // or use directly group.foreach
}

Show tables, describe tables equivalent in redshift

I had to select from the information schema to get details of my tables and columns; in case it helps anyone:

SELECT * FROM information_schema.tables
WHERE table_schema = 'myschema'; 

SELECT * FROM information_schema.columns
WHERE table_schema = 'myschema' AND table_name = 'mytable'; 

Date to milliseconds and back to date in Swift

As @Travis Solution works but in some cases

var millisecondsSince1970:Int WILL CAUSE CRASH APPLICATION ,

with error

Double value cannot be converted to Int because the result would be greater than Int.max if it occurs Please update your answer with Int64

Here is Updated Answer

extension Date {
 var millisecondsSince1970:Int64 {
        return Int64((self.timeIntervalSince1970 * 1000.0).rounded()) 
        //RESOLVED CRASH HERE
    }

    init(milliseconds:Int) {
        self = Date(timeIntervalSince1970: TimeInterval(milliseconds / 1000))
    }
}

About Int definitions.

On 32-bit platforms, Int is the same size as Int32, and on 64-bit platforms, Int is the same size as Int64.

Generally, I encounter this problem in iPhone 5, which runs in 32-bit env. New devices run 64-bit env now. Their Int will be Int64.

Hope it is helpful to someone who also has same problem

Create a date from day month and year with T-SQL

You can also use

select DATEFROMPARTS(year, month, day) as ColDate, Col2, Col3 
From MyTable Where DATEFROMPARTS(year, month, day) Between @DateIni and @DateEnd

Works in SQL since ver.2012 and AzureSQL

How to run docker-compose up -d at system start up?

If your docker.service enabled on system startup

$ sudo systemctl enable docker

and your services in your docker-compose.yml has

restart: always

all of the services run when you reboot your system if you run below command only once

docker-compose up -d

Cannot open local file - Chrome: Not allowed to load local resource

If you have php installed - you can use built-in server. Just open target dir with files and run

php -S localhost:8001

How to set environment via `ng serve` in Angular 6

For Angular 2 - 5 refer the article Multiple Environment in angular

For Angular 6 use ng serve --configuration=dev

Note: Refer the same article for angular 6 as well. But wherever you find --env instead use --configuration. That's works well for angular 6.

Difference between Subquery and Correlated Subquery

Correlated Subquery is a sub-query that uses values from the outer query. In this case the inner query has to be executed for every row of outer query.

See example here http://en.wikipedia.org/wiki/Correlated_subquery

Simple subquery doesn't use values from the outer query and is being calculated only once:

SELECT id, first_name 
FROM student_details 
WHERE id IN (SELECT student_id
FROM student_subjects 
WHERE subject= 'Science'); 

CoRelated Subquery Example -

Query To Find all employees whose salary is above average for their department

 SELECT employee_number, name
       FROM employees emp
       WHERE salary > (
         SELECT AVG(salary)
           FROM employees
           WHERE department = emp.department);

sending mail from Batch file

bmail. Just install the EXE and run a line like this:

bmail -s myMailServer -f [email protected] -t [email protected] -a "Production Release Performed"

"echo -n" prints "-n"

Try with

echo -e "Some string...\c"

It works for me as expected (as I understood from your question).

Note that I got this information from the man page. The man page also notes the shell may have its own version of echo, and I am not sure if bash has its own version.

HTTP POST with URL query parameters -- good idea or not?

You want reasons? Here's one:

A web form can't be used to send a request to a page that uses a mix of GET and POST. If you set the form's method to GET, all the parameters are in the query string. If you set the form's method to POST, all the parameters are in the request body.

Source: HTML 4.01 standard, section 17.13 Form Submission

How can I catch an error caused by mail()?

According to http://php.net/manual/en/function.error-get-last.php, use:

print_r(error_get_last());

Which will return an array of the last error generated. You can access the [message] element to display the error.

How to decode a QR-code image in (preferably pure) Python?

The following code works fine with me:

brew install zbar
pip install pyqrcode
pip install pyzbar

For QR code image creation:

import pyqrcode
qr = pyqrcode.create("test1")
qr.png("test1.png", scale=6)

For QR code decoding:

from PIL import Image
from pyzbar.pyzbar import decode
data = decode(Image.open('test1.png'))
print(data)

that prints the result:

[Decoded(data=b'test1', type='QRCODE', rect=Rect(left=24, top=24, width=126, height=126), polygon=[Point(x=24, y=24), Point(x=24, y=150), Point(x=150, y=150), Point(x=150, y=24)])]

Writing JSON object to a JSON file with fs.writeFileSync

When sending data to a web server, the data has to be a string (here). You can convert a JavaScript object into a string with JSON.stringify(). Here is a working example:

var fs = require('fs');

var originalNote = {
  title: 'Meeting',
  description: 'Meeting John Doe at 10:30 am'
};

var originalNoteString = JSON.stringify(originalNote);

fs.writeFileSync('notes.json', originalNoteString);

var noteString = fs.readFileSync('notes.json');

var note = JSON.parse(noteString);

console.log(`TITLE: ${note.title} DESCRIPTION: ${note.description}`);

Hope it could help.

How to list only files and not directories of a directory Bash?

Using find:

find . -maxdepth 1 -type f

Using the -maxdepth 1 option ensures that you only look in the current directory (or, if you replace the . with some path, that directory). If you want a full recursive listing of all files in that and subdirectories, just remove that option.

Can we convert a byte array into an InputStream in Java?

Use ByteArrayInputStream:

InputStream is = new ByteArrayInputStream(decodedBytes);

Bad Request - Invalid Hostname IIS7

For Visual Studio 2017 and Visual Studio 2015, IIS Express settings is stored in the hidden .vs directory and the path is something like this .vs\config\applicationhost.config, add binding like below will work

<bindings>
    <binding protocol="http" bindingInformation="*:8802:localhost" />
    <binding protocol="http" bindingInformation="*:8802:127.0.0.1" />
</bindings>

Syntax: https://docs.microsoft.com/en-us/dotnet/api/microsoft.web.administration.binding.bindinginformation?view=iis-dotnet

send checkbox value in PHP form

if(isset($_POST["newsletter"]) && $_POST["newsletter"] == "newsletter"){
    //checked
}

Retrieving a Foreign Key value with django-rest-framework serializers

this worked fine for me:

class ItemSerializer(serializers.ModelSerializer):
    category_name = serializers.ReadOnlyField(source='category.name')
    class Meta:
        model = Item
        fields = "__all__"

How to represent e^(-t^2) in MATLAB?

All the 3 first ways are identical. You have make sure that if t is a matrix you add . before using multiplication or the power.

for matrix:

t= [1 2 3;2 3 4;3 4 5];
tp=t.*t;
x=exp(-(t.^2));
y=exp(-(t.*t));
z=exp(-(tp));

gives the results:

x =

0.3679    0.0183    0.0001
0.0183    0.0001    0.0000
0.0001    0.0000    0.0000

y =

0.3679    0.0183    0.0001
0.0183    0.0001    0.0000
0.0001    0.0000    0.0000

z=

0.3679    0.0183    0.0001
0.0183    0.0001    0.0000
0.0001    0.0000    0.0000

And using a scalar:

p=3;
pp=p^2;
x=exp(-(p^2));
y=exp(-(p*p));
z=exp(-pp);

gives the results:

x =

1.2341e-004

y =

1.2341e-004

z =

1.2341e-004

How to solve static declaration follows non-static declaration in GCC C code?

You have declared a function as nonstatic in some file and you have implemented as static in another file or somewhere in the same file can cause this problem also. For example, the following code will produce this error.

void inlet_update_my_ratio(object_t *myobject);
//some where the implementation is like this
static void inlet_update_my_ratio(object_t *myobject) {
//code
}

If you remove the static from the implementation, the error will go away as below.

 void inlet_update_my_ratio(object_t *myobject) {
    //code
    }

How to deal with http status codes other than 200 in Angular 2

Yes you can handle with the catch operator like this and show alert as you want but firstly you have to import Rxjs for the same like this way

import {Observable} from 'rxjs/Rx';

return this.http.request(new Request(this.requestoptions))
            .map((res: Response) => {
                if (res) {
                    if (res.status === 201) {
                        return [{ status: res.status, json: res }]
                    }
                    else if (res.status === 200) {
                        return [{ status: res.status, json: res }]
                    }
                }
            }).catch((error: any) => {
                if (error.status === 500) {
                    return Observable.throw(new Error(error.status));
                }
                else if (error.status === 400) {
                    return Observable.throw(new Error(error.status));
                }
                else if (error.status === 409) {
                    return Observable.throw(new Error(error.status));
                }
                else if (error.status === 406) {
                    return Observable.throw(new Error(error.status));
                }
            });
    }

also you can handel error (with err block) that is throw by catch block while .map function,

like this -

...
.subscribe(res=>{....}
           err => {//handel here});

Update

as required for any status without checking particluar one you can try this: -

return this.http.request(new Request(this.requestoptions))
            .map((res: Response) => {
                if (res) {
                    if (res.status === 201) {
                        return [{ status: res.status, json: res }]
                    }
                    else if (res.status === 200) {
                        return [{ status: res.status, json: res }]
                    }
                }
            }).catch((error: any) => {
                if (error.status < 400 ||  error.status ===500) {
                    return Observable.throw(new Error(error.status));
                }
            })
            .subscribe(res => {...},
                       err => {console.log(err)} );

How do I include negative decimal numbers in this regular expression?

Some Regular expression examples:

Positive Integers:

^\d+$

Negative Integers:

^-\d+$

Integer:

^-?\d+$

Positive Number:

^\d*\.?\d+$

Negative Number:

^-\d*\.?\d+$

Positive Number or Negative Number:

^-?\d*\.{0,1}\d+$

Phone number:

^\+?[\d\s]{3,}$

Phone with code:

^\+?[\d\s]+\(?[\d\s]{10,}$

Year 1900-2099:

^(19|20)[\d]{2,2}$

Date (dd mm yyyy, d/m/yyyy, etc.):

^([1-9]|0[1-9]|[12][0-9]|3[01])\D([1-9]|0[1-9]|1[012])\D(19[0-9][0-9]|20[0-9][0-9])$

IP v4:

^(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5]){3}$

How to filter JSON Data in JavaScript or jQuery?

No need for jQuery unless you target old browsers and don't want to use shims.

var yahooOnly = JSON.parse(jsondata).filter(function (entry) {
    return entry.website === 'yahoo';
});

In ES2015:

const yahooOnly = JSON.parse(jsondata).filter(({website}) => website === 'yahoo');

Does uninstalling a package with "pip" also remove the dependent packages?

You may have a try for https://github.com/cls1991/pef. It will remove package with its all dependencies.

getCurrentPosition() and watchPosition() are deprecated on insecure origins

You could use the https://ipinfo.io API for this (it's my service). It's free for up to 1,000 req/day (with or without SSL support). It gives you coordinates, name and more. Here's an example:

curl ipinfo.io
{
  "ip": "172.56.39.47",
  "hostname": "No Hostname",
  "city": "Oakland",
  "region": "California",
  "country": "US",
  "loc": "37.7350,-122.2088",
  "org": "AS21928 T-Mobile USA, Inc.",
  "postal": "94621"
}

Here's an example which constructs a coords object with the API response that matches what you get from getCurrentPosition():

$.getJSON('https://ipinfo.io/geo', function(response) { 
    var loc = response.loc.split(',');
    var coords = {
        latitude: loc[0],
        longitude: loc[1]
    };
});

And here's a detailed example that shows how you can use it as a fallback for getCurrentPosition():

function do_something(coords) {
    // Do something with the coords here
}

navigator.geolocation.getCurrentPosition(function(position) { 
    do_something(position.coords);
    },
    function(failure) {
        $.getJSON('https://ipinfo.io/geo', function(response) { 
        var loc = response.loc.split(',');
        var coords = {
            latitude: loc[0],
            longitude: loc[1]
        };
        do_something(coords);
        });  
    };
});

See http://ipinfo.io/developers/replacing-navigator-geolocation-getcurrentposition for more details.

inner join in linq to entities

public IList<Splitting> get(Guid companyId, long customrId) {    
    var res=from c in Customers_data_source
            where c.CustomerId = customrId && c.CompanyID == companyId
            from s in Splittings_data_srouce
            where s.CustomerID = c.CustomerID
            select s;

    return res.ToList();
}

How to trim whitespace from a Bash variable?

Let's define a variable containing leading, trailing, and intermediate whitespace:

FOO=' test test test '
echo -e "FOO='${FOO}'"
# > FOO=' test test test '
echo -e "length(FOO)==${#FOO}"
# > length(FOO)==16

How to remove all whitespace (denoted by [:space:] in tr):

FOO=' test test test '
FOO_NO_WHITESPACE="$(echo -e "${FOO}" | tr -d '[:space:]')"
echo -e "FOO_NO_WHITESPACE='${FOO_NO_WHITESPACE}'"
# > FOO_NO_WHITESPACE='testtesttest'
echo -e "length(FOO_NO_WHITESPACE)==${#FOO_NO_WHITESPACE}"
# > length(FOO_NO_WHITESPACE)==12

How to remove leading whitespace only:

FOO=' test test test '
FOO_NO_LEAD_SPACE="$(echo -e "${FOO}" | sed -e 's/^[[:space:]]*//')"
echo -e "FOO_NO_LEAD_SPACE='${FOO_NO_LEAD_SPACE}'"
# > FOO_NO_LEAD_SPACE='test test test '
echo -e "length(FOO_NO_LEAD_SPACE)==${#FOO_NO_LEAD_SPACE}"
# > length(FOO_NO_LEAD_SPACE)==15

How to remove trailing whitespace only:

FOO=' test test test '
FOO_NO_TRAIL_SPACE="$(echo -e "${FOO}" | sed -e 's/[[:space:]]*$//')"
echo -e "FOO_NO_TRAIL_SPACE='${FOO_NO_TRAIL_SPACE}'"
# > FOO_NO_TRAIL_SPACE=' test test test'
echo -e "length(FOO_NO_TRAIL_SPACE)==${#FOO_NO_TRAIL_SPACE}"
# > length(FOO_NO_TRAIL_SPACE)==15

How to remove both leading and trailing spaces--chain the seds:

FOO=' test test test '
FOO_NO_EXTERNAL_SPACE="$(echo -e "${FOO}" | sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//')"
echo -e "FOO_NO_EXTERNAL_SPACE='${FOO_NO_EXTERNAL_SPACE}'"
# > FOO_NO_EXTERNAL_SPACE='test test test'
echo -e "length(FOO_NO_EXTERNAL_SPACE)==${#FOO_NO_EXTERNAL_SPACE}"
# > length(FOO_NO_EXTERNAL_SPACE)==14

Alternatively, if your bash supports it, you can replace echo -e "${FOO}" | sed ... with sed ... <<<${FOO}, like so (for trailing whitespace):

FOO_NO_TRAIL_SPACE="$(sed -e 's/[[:space:]]*$//' <<<${FOO})"

Vertical divider doesn't work in Bootstrap 3

I find using the pipe character with some top and bottom padding works well. Using a div with a border will require more CSS to vertically align it and get the horizontal spacing even with the other elements.

CSS

.divider-vertical {
    padding-top: 14px;
    padding-bottom: 14px;
}

HTML

<ul class="nav navbar-nav">
    <li class="active"><a href="#">Home</a></li>
    <li class="divider-vertical">&#124;</li>
    <li><a href="#">Faq</a></li>
    <li class="divider-vertical">&#124;</li>
    <li><a href="#">News</a></li>
    <li class="divider-vertical">&#124;</li>
    <li><a href="#">Contact</a></li>
</ul>

Styling twitter bootstrap buttons

I found the simplest way is to put this in your overrides. Sorry for my unimaginative color choice

Bootstrap 4-Alpha SASS

.my-btn {
  //@include button-variant($btn-primary-color, $btn-primary-bg, $btn-primary-border);
  @include button-variant(red, white, blue);
}

Bootstrap 4 Alpha SASS Example

Bootstrap 3 LESS

.my-btn {
  //.button-variant(@btn-primary-color; @btn-primary-bg; @btn-primary-border);
  .button-variant(red; white; blue);
}

Bootstrap 3 LESS Example

Bootstrap 3 SASS

.my-btn {
  //@include button-variant($btn-primary-color, $btn-primary-bg, $btn-primary-border);
  @include button-variant(red, white, blue);
}

Bootstrap 3 SASS Example

Bootstrap 2.3 LESS

.btn-primary {
  //.buttonBackground(@btnBackground, @btnBackgroundHighlight, @grayDark, 0 1px 1px rgba(255,255,255,.75));
  .buttonBackground(red, white);
}

Bootstrap 2.3 LESS Example

Bootstrap 2.3 SASS

.btn-primary {
  //@include buttonBackground($btnPrimaryBackground, $btnPrimaryBackgroundHighlight); 
  @include buttonBackground(red, white); 
}

It will take care of the hover/actives for you

From the comments, if you want to lighten the button instead of darken when using black (or just want to inverse) you need to extend the class a bit further like so:

Bootstrap 3 SASS Ligthen

.my-btn {
  // @include button-variant($btn-primary-color, $btn-primary-bg, $btn-primary-border);
  $color: #fff;
  $background: #000;
  $border: #333;
  @include button-variant($color, $background, $border);
  // override the default darkening with lightening
  &:hover,
  &:focus,
  &.focus,
  &:active,
  &.active,
  .open > &.dropdown-toggle {
    color: $color;
    background-color: lighten($background, 20%); //10% default
    border-color: lighten($border, 22%); // 12% default
  }
}

Bootstrap 3 SASS Lighten Example

Detect user scroll down or scroll up in jQuery

To differentiate between scroll up/down in jQuery, you could use:

var mousewheelevt = (/Firefox/i.test(navigator.userAgent)) ? "DOMMouseScroll" : "mousewheel" //FF doesn't recognize mousewheel as of FF3.x
$('#yourDiv').bind(mousewheelevt, function(e){

    var evt = window.event || e //equalize event object     
    evt = evt.originalEvent ? evt.originalEvent : evt; //convert to originalEvent if possible               
    var delta = evt.detail ? evt.detail*(-40) : evt.wheelDelta //check for detail first, because it is used by Opera and FF

    if(delta > 0) {
        //scroll up
    }
    else{
        //scroll down
    }   
});

This method also works in divs that have overflow:hidden.

I successfully tested it in FireFox, IE and Chrome.

Template not provided using create-react-app

"If you've previously installed create-react-app globally via npm install -g create-react-app, we recommend you uninstall the package using npm uninstall -g create-react-app to ensure that npx always uses the latest version"

This is reported at https://create-react-app.dev/docs/getting-started/. For me, this did not work. I had to re-install create-react-app globally instead.

My steps to fix this problem were to:

  1. npm uninstall -g create-react-app
  2. npm install -g create-react-app
  3. npx create-react-app my-app

Reflection generic get field value

    ` 
//Here is the example I used for get the field name also the field value
//Hope This will help to someone
TestModel model = new TestModel ("MyDate", "MyTime", "OUT");
//Get All the fields of the class
 Field[] fields = model.getClass().getDeclaredFields();
//If the field is private make the field to accessible true
fields[0].setAccessible(true);
//Get the field name
  System.out.println(fields[0].getName());
//Get the field value
System.out.println(fields[0].get(model));
`

How can I get form data with JavaScript/jQuery?

I wrote a function that takes care of multiple checkboxes and multiple selects. In those cases it returns an array.

function getFormData(formId) {
    return $('#' + formId).serializeArray().reduce(function (obj, item) {
        var name = item.name,
            value = item.value;

        if (obj.hasOwnProperty(name)) {
            if (typeof obj[name] == "string") {
                obj[name] = [obj[name]];
                obj[name].push(value);
            } else {
                obj[name].push(value);
            }
        } else {
            obj[name] = value;
        }
        return obj;
    }, {});
}

Php artisan make:auth command is not defined

If you using >5 version of laravel then you will use.

composer require laravel/ui --dev **or** composer require laravel/ui

And then

php artisan ui:auth

excel - if cell is not blank, then do IF statement

You need to use AND statement in your formula

=IF(AND(IF(NOT(ISBLANK(Q2));TRUE;FALSE);Q2<=R2);"1";"0")

And if both conditions are met, return 1.

You could also add more conditions in your AND statement.

Apply .gitignore on an existing repository already tracking large number of files

As specified here You can update the index:

git update-index --assume-unchanged /path/to/file

By doing this, the files will not show up in git status or git diff.

To begin tracking the files again you can run:

git update-index --no-assume-unchanged /path/to/file

Impact of Xcode build options "Enable bitcode" Yes/No

Make sure to select "All" to find the enable bitcode build settings:

Build settings

Why are elementwise additions much faster in separate loops than in a combined loop?

The first loop alternates writing in each variable. The second and third ones only make small jumps of element size.

Try writing two parallel lines of 20 crosses with a pen and paper separated by 20 cm. Try once finishing one and then the other line and try another time by writting a cross in each line alternately.

Case insensitive regular expression without re.compile?

In imports

import re

In run time processing:

RE_TEST = r'test'
if re.match(RE_TEST, 'TeSt', re.IGNORECASE):

It should be mentioned that not using re.compile is wasteful. Every time the above match method is called, the regular expression will be compiled. This is also faulty practice in other programming languages. The below is the better practice.

In app initialization:

self.RE_TEST = re.compile('test', re.IGNORECASE)

In run time processing:

if self.RE_TEST.match('TeSt'):

How to fix java.net.SocketException: Broken pipe?

All the open streams & connections need to be properly closed, so the next time we try to use the urlConnection object, it does not throw an error. As an example, the following code change fixed the error for me.

Before:

OutputStream out = new BufferedOutputStream(urlConnection.getOutputStream());
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(out));
bw.write("Some text");
bw.close();
out.close();

After:

OutputStream os = urlConnection.getOutputStream();
OutputStream out = new BufferedOutputStream(os);
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(out));
bw.write("Some text");
bw.close();
out.close();
os.close(); // This is a must.

Return a `struct` from a function in C

There is no issue in passing back a struct. It will be passed by value

But, what if the struct contains any member which has a address of a local variable

struct emp {
    int id;
    char *name;
};

struct emp get() {
    char *name = "John";

    struct emp e1 = {100, name};

    return (e1);
}

int main() {

    struct emp e2 = get();

    printf("%s\n", e2.name);
}

Now, here e1.name contains a memory address local to the function get(). Once get() returns, the local address for name would have been freed up. SO, in the caller if we try to access that address, it may cause segmentation fault, as we are trying a freed address. That is bad..

Where as the e1.id will be perfectly valid as its value will be copied to e2.id

So, we should always try to avoid returning local memory addresses of a function.

Anything malloced can be returned as and when wanted

What's the Linq to SQL equivalent to TOP or LIMIT/OFFSET?

This way it worked for me:

var noticias = from n in db.Noticias.Take(6)
                       where n.Atv == 1
                       orderby n.DatHorLan descending
                       select n;

Git - How to close commit editor?

Save the file in the editor. If it's Emacs: CTRLX CTRLS to save then CTRLX CTRLC to quit or if it's vi: :wq

Press esc first to get out from editing. (in windows/vi)

Can I pass variable to select statement as column name in SQL Server

You can't use variable names to bind columns or other system objects, you need dynamic sql

DECLARE @value varchar(10)  
SET @value = 'intStep'  
DECLARE @sqlText nvarchar(1000); 

SET @sqlText = N'SELECT ' + @value + ' FROM dbo.tblBatchDetail'
Exec (@sqlText)

Comparing Dates in Oracle SQL

You can use trunc and to_date as follows:

select TO_CHAR (g.FECHA, 'DD-MM-YYYY HH24:MI:SS') fecha_salida, g.NUMERO_GUIA, g.BOD_ORIGEN, g.TIPO_GUIA, dg.DOC_NUMERO, dg.* 
from ils_det_guia dg, ils_guia g
where dg.NUMERO_GUIA = g.NUMERO_GUIA and dg.TIPO_GUIA = g.TIPO_GUIA and dg.BOD_ORIGEN = g.BOD_ORIGEN
and dg.LAB_CODIGO = 56 
and trunc(g.FECHA) > to_date('01/02/15','DD/MM/YY')
order by g.FECHA;

VBA collection: list of keys

You can snoop around in your memory using RTLMoveMemory and retrieve the desired information directly from there:

32-Bit:

Option Explicit

'Provide direct memory access:
Public Declare Sub MemCopy Lib "kernel32" Alias "RtlMoveMemory" ( _
    ByVal Destination As Long, _
    ByVal Source As Long, _
    ByVal Length As Long)


Function CollectionKeys(oColl As Collection) As String()

    'Declare Pointer- / Memory-Address-Variables
    Dim CollPtr As Long
    Dim KeyPtr As Long
    Dim ItemPtr As Long

    'Get MemoryAddress of Collection Object
    CollPtr = VBA.ObjPtr(oColl)

    'Peek ElementCount
    Dim ElementCount As Long
    ElementCount = PeekLong(CollPtr + 16)

        'Verify ElementCount
        If ElementCount <> oColl.Count Then
            'Something's wrong!
            Stop
        End If

    'Declare Simple Counter
    Dim index As Long

    'Declare Temporary Array to hold our keys
    Dim Temp() As String
    ReDim Temp(ElementCount)

    'Get MemoryAddress of first CollectionItem
    ItemPtr = PeekLong(CollPtr + 24)

    'Loop through all CollectionItems in Chain
    While Not ItemPtr = 0 And index < ElementCount

        'increment Index
        index = index + 1

        'Get MemoryAddress of Element-Key
        KeyPtr = PeekLong(ItemPtr + 16)

        'Peek Key and add to temporary array (if present)
        If KeyPtr <> 0 Then
           Temp(index) = PeekBSTR(KeyPtr)
        End If

        'Get MemoryAddress of next Element in Chain
        ItemPtr = PeekLong(ItemPtr + 24)

    Wend

    'Assign temporary array as Return-Value
    CollectionKeys = Temp

End Function


'Peek Long from given MemoryAddress
Public Function PeekLong(Address As Long) As Long

  If Address = 0 Then Stop
  Call MemCopy(VBA.VarPtr(PeekLong), Address, 4&)

End Function

'Peek String from given MemoryAddress
Public Function PeekBSTR(Address As Long) As String

    Dim Length As Long

    If Address = 0 Then Stop
    Length = PeekLong(Address - 4)

    PeekBSTR = Space(Length \ 2)
    Call MemCopy(VBA.StrPtr(PeekBSTR), Address, Length)

End Function

64-Bit:

Option Explicit

'Provide direct memory access:
Public Declare PtrSafe Sub MemCopy Lib "kernel32" Alias "RtlMoveMemory" ( _
     ByVal Destination As LongPtr, _
     ByVal Source As LongPtr, _
     ByVal Length As LongPtr)



Function CollectionKeys(oColl As Collection) As String()

    'Declare Pointer- / Memory-Address-Variables
    Dim CollPtr As LongPtr
    Dim KeyPtr As LongPtr
    Dim ItemPtr As LongPtr

    'Get MemoryAddress of Collection Object
    CollPtr = VBA.ObjPtr(oColl)

    'Peek ElementCount
    Dim ElementCount As Long
    ElementCount = PeekLong(CollPtr + 28)

        'Verify ElementCount
        If ElementCount <> oColl.Count Then
            'Something's wrong!
            Stop
        End If

    'Declare Simple Counter
    Dim index As Long

    'Declare Temporary Array to hold our keys
    Dim Temp() As String
    ReDim Temp(ElementCount)

    'Get MemoryAddress of first CollectionItem
    ItemPtr = PeekLongLong(CollPtr + 40)

    'Loop through all CollectionItems in Chain
    While Not ItemPtr = 0 And index < ElementCount

        'increment Index
        index = index + 1

        'Get MemoryAddress of Element-Key
        KeyPtr = PeekLongLong(ItemPtr + 24)

        'Peek Key and add to temporary array (if present)
        If KeyPtr <> 0 Then
           Temp(index) = PeekBSTR(KeyPtr)
        End If

        'Get MemoryAddress of next Element in Chain
        ItemPtr = PeekLongLong(ItemPtr + 40)

    Wend

    'Assign temporary array as Return-Value
    CollectionKeys = Temp

End Function


'Peek Long from given Memory-Address
Public Function PeekLong(Address As LongPtr) As Long

  If Address = 0 Then Stop
  Call MemCopy(VBA.VarPtr(PeekLong), Address, 4^)

End Function

'Peek LongLong from given Memory Address
Public Function PeekLongLong(Address As LongPtr) As LongLong

  If Address = 0 Then Stop
  Call MemCopy(VBA.VarPtr(PeekLongLong), Address, 8^)

End Function

'Peek String from given MemoryAddress
Public Function PeekBSTR(Address As LongPtr) As String

    Dim Length As Long

    If Address = 0 Then Stop
    Length = PeekLong(Address - 4)

    PeekBSTR = Space(Length \ 2)
    Call MemCopy(VBA.StrPtr(PeekBSTR), Address, CLngLng(Length))

End Function

C# Convert a Base64 -> byte[]

You have to use Convert.FromBase64String to turn a Base64 encoded string into a byte[].