Programs & Examples On #Chickenfoot

Chickenfoot is a Firefox extension which provides an end-user API for editing web pages.

Why am I getting InputMismatchException?

I encountered the same problem. Strange, but the reason was that the object Scanner interprets fractions depending on localization of system. If the current localization uses a comma to separate parts of the fractions, the fraction with the dot will turn into type String. Hence the error ...

How do I get the localhost name in PowerShell?

Long form:

get-content env:computername

Short form:

gc env:computername

Difference between the Apache HTTP Server and Apache Tomcat?

Tomcat is primarily an application server, which serves requests to custom-built Java servlets or JSP files on your server. It is usually used in conjunction with the Apache HTTP server (at least in my experience). Use it to manually process incoming requests.

The HTTP server, by itself, is best for serving up static content... html files, images, etc.

Line break in HTML with '\n'

You should consider replacing your line breaks with <br/>. In HTML a line break will only stand for new line in your code.

Alternatively you can use some other HTML markups like placing your lines in paragraphs:

<p>Sample line</p>
<p>Another line</p>

or other wrappers like for instance <div>sample</div> with CSS attribute: display: block.

You can also use <pre>. The content of pre will have its HTML styling ignored. In other words it will display pure HTML with normal \n line breaks.

Map over object preserving keys

A mix fix for the underscore map bug :P

_.mixin({ 
    mapobj : function( obj, iteratee, context ) {
        if (obj == null) return [];
        iteratee = _.iteratee(iteratee, context);
        var keys = obj.length !== +obj.length && _.keys(obj),
            length = (keys || obj).length,
            results = {},
            currentKey;
        for (var index = 0; index < length; index++) {
          currentKey = keys ? keys[index] : index;
          results[currentKey] = iteratee(obj[currentKey], currentKey, obj);
        }
        if ( _.isObject( obj ) ) {
            return _.object( results ) ;
        } 
        return results;
    }
}); 

A simple workaround that keeps the right key and return as object It is still used the same way as i guest you could used this function to override the bugy _.map function

or simply as me used it as a mixin

_.mapobj ( options , function( val, key, list ) 

How do I delay a function call for 5 seconds?

You can use plain javascript, this will call your_func once, after 5 seconds:

setTimeout(function() { your_func(); }, 5000);

If your function has no parameters and no explicit receiver you can call directly setTimeout(func, 5000)

There is also a plugin I've used once. It has oneTime and everyTime methods.

How to calculate md5 hash of a file using javascript

I've made a library that implements incremental md5 in order to hash large files efficiently. Basically you read a file in chunks (to keep memory low) and hash it incrementally. You got basic usage and examples in the readme.

Be aware that you need HTML5 FileAPI, so be sure to check for it. There is a full example in the test folder.

https://github.com/satazor/SparkMD5

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

Several answers show dangerous examples. OP's example [ $a == $b ] specifically used unquoted variable substitution (as of Oct '17 edit). For [...] that is safe for string equality.

But if you're going to enumerate alternatives like [[...]], you must inform also that the right-hand-side must be quoted. If not quoted, it is a pattern match! (From bash man page: "Any part of the pattern may be quoted to force it to be matched as a string.").

Here in bash, the two statements yielding "yes" are pattern matching, other three are string equality:

$ rht="A*"
$ lft="AB"
$ [ $lft = $rht ] && echo yes
$ [ $lft == $rht ] && echo yes
$ [[ $lft = $rht ]] && echo yes
yes
$ [[ $lft == $rht ]] && echo yes
yes
$ [[ $lft == "$rht" ]] && echo yes
$

What are unit tests, integration tests, smoke tests, and regression tests?

Unit test: testing of an individual module or independent component in an application is known to be unit testing. The unit testing will be done by the developer.

Integration test: combining all the modules and testing the application to verify the communication and the data flow between the modules are working properly or not. This testing also performed by developers.

Smoke test In a smoke test they check the application in a shallow and wide manner. In smoke testing they check the main functionality of the application. If there is any blocker issue in the application they will report to developer team, and the developing team will fix it and rectify the defect, and give it back to the testing team. Now testing team will check all the modules to verify that changes made in one module will impact the other module or not. In smoke testing the test cases are scripted.

Regression testing executing the same test cases repeatedly to ensure tat the unchanged module does not cause any defect. Regression testting comes under functional testing

Javascript getElementById based on a partial string

Given that what you want is to determine the full id of the element based upon just the prefix, you're going to have to do a search of the entire DOM (or at least, a search of an entire subtree if you know of some element that is always guaranteed to contain your target element). You can do this with something like:

function findChildWithIdLike(node, prefix) {
    if (node && node.id && node.id.indexOf(prefix) == 0) {
        //match found
        return node;
    }

    //no match, check child nodes
    for (var index = 0; index < node.childNodes.length; index++) {
        var child = node.childNodes[index];
        var childResult = findChildWithIdLike(child, prefix);
        if (childResult) {
            return childResult;
        }
    }
};

Here is an example: http://jsfiddle.net/xwqKh/

Be aware that dynamic element ids like the ones you are working with are typically used to guarantee uniqueness of element ids on a single page. Meaning that it is likely that there are multiple elements that share the same prefix. Probably you want to find them all.

If you want to find all of the elements that have a given prefix, instead of just the first one, you can use something like what is demonstrated here: http://jsfiddle.net/xwqKh/1/

What is the difference between SQL and MySQL?

SQL stands for Structured Query Language, and it is a programming language designed for querying data from a database. MySQL is a relational database management system, which is a completely different thing.

MySQL is an open-source platform that uses SQL, just like MSSQL, which is Microsoft's product (not open-source) that uses SQL for database management.

How do I read a text file of about 2 GB?

Try Glogg. the fast, smart log explorer.

I have opened log file of size around 2 GB, and the search is also very fast.

How to change the default background color white to something else in twitter bootstrap

Its not recommended to overwrite bootstrap file, just in your local style.css use

body{background: your color !important;

here !important declaration overwrite bootstrap value.

TypeError: module.__init__() takes at most 2 arguments (3 given)

Even after @Mickey Perlstein's answer and his 3 hours of detective work, it still took me a few more minutes to apply this to my own mess. In case anyone else is like me and needs a little more help, here's what was going on in my situation.

  • responses is a module
  • Response is a base class within the responses module
  • GeoJsonResponse is a new class derived from Response

Initial GeoJsonResponse class:

from pyexample.responses import Response

class GeoJsonResponse(Response):

    def __init__(self, geo_json_data):

Looks fine. No problems until you try to debug the thing, which is when you get a bunch of seemingly vague error messages like this:

from pyexample.responses import GeoJsonResponse ..\pyexample\responses\GeoJsonResponse.py:12: in (module) class GeoJsonResponse(Response):

E TypeError: module() takes at most 2 arguments (3 given)

=================================== ERRORS ====================================

___________________ ERROR collecting tests/test_geojson.py ____________________

test_geojson.py:2: in (module) from pyexample.responses import GeoJsonResponse ..\pyexample\responses \GeoJsonResponse.py:12: in (module)

class GeoJsonResponse(Response): E TypeError: module() takes at most 2 arguments (3 given)

ERROR: not found: \PyExample\tests\test_geojson.py::TestGeoJson::test_api_response

C:\Python37\lib\site-packages\aenum__init__.py:163

(no name 'PyExample\ tests\test_geojson.py::TestGeoJson::test_api_response' in any of [])

The errors were doing their best to point me in the right direction, and @Mickey Perlstein's answer was dead on, it just took me a minute to put it all together in my own context:

I was importing the module:

from pyexample.responses import Response

when I should have been importing the class:

from pyexample.responses.Response import Response

Hope this helps someone. (In my defense, it's still pretty early.)

How to fill 100% of remaining height?

I added this for pages that were too short.

html:

<section id="secondary-foot"></section>

css:

section#secondary-foot {
    height: 100%;
    background-color: #000000;
    position: fixed;
    width: 100%;
}

git: fatal: Could not read from remote repository

i just wanted to share that i found a easy fix for that:

Access denied. fatal: Could not read from remote repository. Please make sure you have the correct access rights and the repository exists.

just logout from gitlab and login again. The problems should then be fixed.

How do I pass an object from one activity to another on Android?

It depends on the type of data you need access to. If you have some kind of data pool that needs to persist across Activitys then Erich's answer is the way to go. If you just need to pass a few objects from one activity to another then you can have them implement Serializable and pass them in the extras of the Intent to start the new Activity.

How can I use custom fonts on a website?

You have to import the font in your stylesheet like this:

@font-face{
    font-family: "Thonburi-Bold";
    src: url('Thonburi-Bold.ttf'),
    url('Thonburi-Bold.eot'); /* IE */
}

AES Encrypt and Decrypt

Swift4:

let key = "ccC2H19lDDbQDfakxcrtNMQdd0FloLGG" // length == 32
let iv = "ggGGHUiDD0Qjhuvv" // length == 16
func encryptFile(_ path: URL) -> Bool{
    do{
        let data = try Data.init(contentsOf: path)
        let encodedData = try data.aesEncrypt(key: key, iv: iv)
        try encodedData.write(to: path)
        return true
    }catch{
        return false
    }
}

func decryptFile(_ path: URL) -> Bool{
    do{
        let data = try Data.init(contentsOf: path)
        let decodedData = try data.aesDecrypt(key: key, iv: iv)
        try decodedData.write(to: path)
        return true
    }catch{
        return false
    }
}

Install CryptoSwift

import CryptoSwift
extension Data {
    func aesEncrypt(key: String, iv: String) throws -> Data{
        let encypted = try AES(key: key.bytes, blockMode: CBC(iv: iv.bytes), padding: .pkcs7).encrypt(self.bytes)
        return Data(bytes: encypted)
    }

    func aesDecrypt(key: String, iv: String) throws -> Data {
        let decrypted = try AES(key: key.bytes, blockMode: CBC(iv: iv.bytes), padding: .pkcs7).decrypt(self.bytes)
        return Data(bytes: decrypted)
    }
}

How to position a DIV in a specific coordinates?

You don't have to use Javascript to do this. Using plain-old css:

div.blah {
  position:absolute;
  top: 0; /*[wherever you want it]*/
  left:0; /*[wherever you want it]*/
}

If you feel you must use javascript, or are trying to do this dynamically Using JQuery, this affects all divs of class "blah":

var blahclass =  $('.blah'); 
blahclass.css('position', 'absolute');
blahclass.css('top', 0); //or wherever you want it
blahclass.css('left', 0); //or wherever you want it

Alternatively, if you must use regular old-javascript you can grab by id

var domElement = document.getElementById('myElement');// don't go to to DOM every time you need it. Instead store in a variable and manipulate.
domElement.style.position = "absolute";
domElement.style.top = 0; //or whatever 
domElement.style.left = 0; // or whatever

Python 2.7: %d, %s, and float()

Try the following:

print "First is: %f" % (first)
print "Second is: %f" % (second)

I am unsure what answer is. But apart from that, this will be:

print "DONE: %f DIVIDED BY %f EQUALS %f, SWEET MATH BRO!" % (first, second, ans)

There's a lot of text on Format String Specifiers. You can google it and get a list of specifiers. One thing I forgot to note:

If you try this:

print "First is: %s" % (first)

It converts the float value in first to a string. So that would work as well.

Fix GitLab error: "you are not allowed to push code to protected branches on this project"?

for the GitLab Enterprise Edition 9.3.0

By default, master branch is protected so unprotect :)

1-Select you "project"

2-Select "Repository"

3-Select "branches"

4-Select "Project Settings"

5-In "Protected Branches" click to "expand"

6-and after click in "unprotect" button

How to add an image in the title bar using html?

I tried in my angular7 project by writing these lines and worked.

<link rel="icon" type="image/x-icon" href="filepath/filename.ico">

please be noted that the image file should be in icon format (.ico)

Rounded corners for <input type='text' /> using border-radius.htc for IE

That won't work in IE<9 though, however, you can make IEs support that using:

CSS3Pie

PIE makes Internet Explorer 6-8 capable of rendering several of the most useful CSS3 decoration features.

How to select the nth row in a SQL database table?

I'm a bit late to the party here but I have done this without the need for windowing or using

WHERE x IN (...)
SELECT TOP 1
--select the value needed from t1
[col2]
FROM
(
   SELECT TOP 2 --the Nth row, alter this to taste
   UE2.[col1],
   UE2.[col2],
   UE2.[date],
   UE2.[time],
   UE2.[UID]
   FROM
   [table1] AS UE2
   WHERE
   UE2.[col1] = ID --this is a subquery 
   AND
   UE2.[col2] IS NOT NULL
   ORDER BY
   UE2.[date] DESC, UE2.[time] DESC --sorting by date and time newest first
) AS t1
ORDER BY t1.[date] ASC, t1.[time] ASC --this reverses the order of the sort in t1

It seems to work fairly fast although to be fair I only have around 500 rows of data

This works in MSSQL

Unable to instantiate default tuplizer [org.hibernate.tuple.entity.PojoEntityTuplizer]

I had the same problem and resolved it adding this dependency.

<dependency>
    <groupId>javassist</groupId>
    <artifactId>javassist</artifactId>
    <version>3.12.1.GA</version>
</dependency>   

I am using hibernate 3.6 version.

ps command doesn't work in docker container

In case you can't install the procps package (don't have proper permissions) you can use /proc directory.

The first few directories (named as numbers) are PIDs of your processes. Inside directories, you can find additional information useful to decipher which process is connected to each PID. For example, you can use the cat command to view "cmdline" file to check which process is connected to PID.

$ ls /proc
1 10 11 ...

$ ls -1 /proc/22
attr
autogroup
auxv
cgroup
clear_refs
cmdline
...

$ cat /proc/22/cmdline 
/bin/sh

How to pass arguments to Shell Script through docker run

If you want to run it @build time :

CMD /bin/bash /file.sh arg1

if you want to run it @run time :

ENTRYPOINT ["/bin/bash"]
CMD ["/file.sh", "arg1"]

Then in the host shell

docker build -t test .
docker run -i -t test

Is it possible to have a multi-line comments in R?

R Studio (and Eclipse + StatET): Highlight the text and use CTRL+SHIFT+C to comment multiple lines in Windows. Or, command+SHIFT+C in OS-X.

ALTER TABLE ADD COLUMN IF NOT EXISTS in SQLite

select * from sqlite_master where type = 'table' and tbl_name = 'TableName' and sql like '%ColumnName%'

Logic: sql column in sqlite_master contains table definition, so it certainly contains string with column name.

As you are searching for a sub-string, it has its obvious limitations. So I would suggest to use even more restrictive sub-string in ColumnName, for example something like this (subject to testing as '`' character is not always there):

select * from sqlite_master where type = 'table' and tbl_name = 'MyTable' and sql like '%`MyColumn` TEXT%'

How to truncate milliseconds off of a .NET DateTime

I know the answer is quite late, but the best way to get rid of milliseconds is

var currentDateTime = DateTime.Now.ToString("s");

Try printing the value of the variable, it will show the date time, without milliseconds.

How can I convert a stack trace to a string?

 import java.io.PrintWriter;
import java.io.StringWriter;

public class PrintStackTrace {

    public static void main(String[] args) {

        try {
            int division = 0 / 0;
        } catch (ArithmeticException e) {
            StringWriter sw = new StringWriter();
            e.printStackTrace(new PrintWriter(sw));
            String exceptionAsString = sw.toString();
            System.out.println(exceptionAsString);
        }
    }
}

When you run the program, the output will be something similar:

java.lang.ArithmeticException: / by zero
at PrintStackTrace.main(PrintStackTrace.java:9)

Replace words in the body text

I had the same problem. I wrote my own function using replace on innerHTML, but it would screw up anchor links and such.

To make it work correctly I used a library to get this done.

The library has an awesome API. After including the script I called it like this:

findAndReplaceDOMText(document.body, {
  find: 'texttofind',
  replace: 'texttoreplace'
  }
);

How to delete a localStorage item when the browser window/tab is closed?

why not used sessionStorage?

"The sessionStorage object is equal to the localStorage object, except that it stores the data for only one session. The data is deleted when the user closes the browser window."

http://www.w3schools.com/html/html5_webstorage.asp

WELD-001408: Unsatisfied dependencies for type Customer with qualifiers @Default

Your Customer class has to be discovered by CDI as a bean. For that you have two options:

  1. Put a bean defining annotation on it. As @Model is a stereotype it's why it does the trick. A qualifier like @Named is not a bean defining annotation, reason why it doesn't work

  2. Change the bean discovery mode in your bean archive from the default "annotated" to "all" by adding a beans.xml file in your jar.

Keep in mind that @Named has only one usage : expose your bean to the UI. Other usages are for bad practice or compatibility with legacy framework.

Python: How to check a string for substrings from a list?

Try this test:

any(substring in string for substring in substring_list)

It will return True if any of the substrings in substring_list is contained in string.

Note that there is a Python analogue of Marc Gravell's answer in the linked question:

from itertools import imap
any(imap(string.__contains__, substring_list)) 

In Python 3, you can use map directly instead:

any(map(string.__contains__, substring_list))

Probably the above version using a generator expression is more clear though.

"Thinking in AngularJS" if I have a jQuery background?

Those are some very nice, but lengthy answers.

To sum up my experiences:

  1. Controllers and providers (services, factories, etc.) are for modifying the data model, NOT HTML.
  2. HTML and directives define the layout and binding to the model.
  3. If you need to share data between controllers, create a service or factory - they are singletons that are shared across the application.
  4. If you need an HTML widget, create a directive.
  5. If you have some data and are now trying to update HTML... STOP! update the model, and make sure your HTML is bound to the model.

DB2 Query to retrieve all table names for a given schema

This should work:

select * from syscat.tables

Open a URL without using a browser from a batch file

Try winhttpjs.bat. It uses a winhttp request object that should be faster than
Msxml2.XMLHTTP as there isn't any DOM parsing of the response. It is capable to do requests with body and all HTTP methods.

call winhttpjs.bat  http://somelink.com/something.html -saveTo c:\something.html

MySQL 1062 - Duplicate entry '0' for key 'PRIMARY'

For me, i forget to add AUTO_INCREMENT to my primary field and inserted data without id.

How to break nested loops in JavaScript?

You return to "break" you nested for loop.

function foo ()
{
    //dance:
    for(var k = 0; k < 4; k++){
        for(var m = 0; m < 4; m++){
            if(m == 2){
                //break dance;
                return;
            }
        }
    }
}
foo();

IBOutlet and IBAction

IBAction and IBOutlets are used to hook up your interface made in Interface Builder with your controller. If you wouldn't use Interface Builder and build your interface completely in code, you could make a program without using them. But in reality most of us use Interface Builder, once you want to get some interactivity going in your interface, you will have to use IBActions and IBoutlets.

Cleanest way to write retry logic?

Or how about doing it a bit neater....

int retries = 3;
while (retries > 0)
{
  if (DoSomething())
  {
    retries = 0;
  }
  else
  {
    retries--;
  }
}

I believe throwing exceptions should generally be avoided as a mechanism unless your a passing them between boundaries (such as building a library other people can use). Why not just have the DoSomething() command return true if it was successful and false otherwise?

EDIT: And this can be encapsulated inside a function like others have suggested as well. Only problem is if you are not writing the DoSomething() function yourself

Drawing Circle with OpenGL

#include <Windows.h>
#include <GL/glu.h>
#include <GL/glut.h>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define window_width  1080  
#define window_height 720 
void drawFilledSun(){
    //static float angle;
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    glLoadIdentity();
    glTranslatef(0, 0, -10);
    int i, x, y;
    double radius = 0.30;
    //glColor3ub(253, 184, 19);     
    glColor3ub(255, 0, 0);
    double twicePi = 2.0 * 3.142;
    x = 0, y = 0;
    glBegin(GL_TRIANGLE_FAN); //BEGIN CIRCLE
    glVertex2f(x, y); // center of circle
    for (i = 0; i <= 20; i++)   {
        glVertex2f (
            (x + (radius * cos(i * twicePi / 20))), (y + (radius * sin(i * twicePi / 20)))
            );
    }
    glEnd(); //END
}
void DrawCircle(float cx, float cy, float r, int num_segments) {
    glBegin(GL_LINE_LOOP);
    for (int ii = 0; ii < num_segments; ii++)   {
        float theta = 2.0f * 3.1415926f * float(ii) / float(num_segments);//get the current angle 
        float x = r * cosf(theta);//calculate the x component 
        float y = r * sinf(theta);//calculate the y component 
        glVertex2f(x + cx, y + cy);//output vertex 
    }
    glEnd();
}
void main_loop_function() {
    int c;
    drawFilledSun();
    DrawCircle(0, 0, 0.7, 100);
    glutSwapBuffers();
    c = getchar();
}
void GL_Setup(int width, int height) {
    glViewport(0, 0, width, height);
    glMatrixMode(GL_PROJECTION);
    glEnable(GL_DEPTH_TEST);
    gluPerspective(45, (float)width / height, .1, 100);
    glMatrixMode(GL_MODELVIEW);
}
int main(int argc, char** argv) {
    glutInit(&argc, argv);
    glutInitWindowSize(window_width, window_height);
    glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE);
    glutCreateWindow("GLUT Example!!!");
    glutIdleFunc(main_loop_function);
    GL_Setup(window_width, window_height);
    glutMainLoop();
}

This is what I did. I hope this helps. Two types of circle are here. Filled and unfilled.

Why doesn't RecyclerView have onItemClickListener()?

I wrote a library to handle android recycler view item click event. You can find whole tutorial in https://github.com/ChathuraHettiarachchi/RecycleClick

RecycleClick.addTo(YOUR_RECYCLEVIEW).setOnItemClickListener(new RecycleClick.OnItemClickListener() {
            @Override
            public void onItemClicked(RecyclerView recyclerView, int position, View v) {
                // YOUR CODE
            }
        });

or to handle item long press you can use

RecycleClick.addTo(YOUR_RECYCLEVIEW).setOnItemLongClickListener(new RecycleClick.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClicked(RecyclerView recyclerView, int position, View v) {
                // YOUR CODE
                return true;
            }
        });

Correct Semantic tag for copyright info - html5

The <footer> tag seems like a good candidate:

<footer>&copy; 2011 Some copyright message</footer>

How do I use a char as the case in a switch-case?

Using a char when the variable is a string won't work. Using

switch (hello.charAt(0)) 

you will extract the first character of the hello variable instead of trying to use the variable as it is, in string form. You also need to get rid of your space inside

case 'a '

Convert php array to Javascript

Spudley's answer is fine.

Security Notice: The following should not be necessary any longer for you

If you don't have PHP 5.2 you can use something like this:

function js_str($s)
{
    return '"' . addcslashes($s, "\0..\37\"\\") . '"';
}

function js_array($array)
{
    $temp = array_map('js_str', $array);
    return '[' . implode(',', $temp) . ']';
}

echo 'var cities = ', js_array($php_cities_array), ';';

reading from app.config file

ConfigurationSettings.AppSettings is deprecated, see here:

http://msdn.microsoft.com/en-us/library/system.configuration.configurationsettings.appsettings.aspx

That said, it should still work.

Just a suggestion, but have you confirmed that your application configuration is the one your executable is using?

Try attaching a debugger and checking the following value:

AppDomain.CurrentDomain.SetupInformation.ConfigurationFile

And then opening the configuration file and verifying the section is there as you expected.

How to download files using axios

This Worked for me. i implemented this solution in reactJS

const requestOptions = {`enter code here`
method: 'GET',
headers: { 'Content-Type': 'application/json' }
};

fetch(`${url}`, requestOptions)
.then((res) => {
    return res.blob();
})
.then((blob) => {
    const href = window.URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = href;
    link.setAttribute('download', 'config.json'); //or any other extension
    document.body.appendChild(link);
    link.click();
})
.catch((err) => {
    return Promise.reject({ Error: 'Something Went Wrong', err });
})

Beamer: How to show images as step-by-step images

This is a sample code I used to counter the problem.

\begin{frame}{Topic 1}
Topic of the figures
\begin{figure}
\captionsetup[subfloat]{position=top,labelformat=empty}
\only<1>{\subfloat[Fig. 1]{\includegraphics{figure1.jpg}}}
\only<2>{\subfloat[Fig. 2]{\includegraphics{figure2.jpg}}}
\only<3>{\subfloat[Fig. 3]{\includegraphics{figure3.jpg}}}
\end{figure}
\end{frame}

How do you calculate log base 2 in Java for integers?

If you are thinking about using floating-point to help with integer arithmetics, you have to be careful.

I usually try to avoid FP calculations whenever possible.

Floating-point operations are not exact. You can never know for sure what will (int)(Math.log(65536)/Math.log(2)) evaluate to. For example, Math.ceil(Math.log(1<<29) / Math.log(2)) is 30 on my PC where mathematically it should be exactly 29. I didn't find a value for x where (int)(Math.log(x)/Math.log(2)) fails (just because there are only 32 "dangerous" values), but it does not mean that it will work the same way on any PC.

The usual trick here is using "epsilon" when rounding. Like (int)(Math.log(x)/Math.log(2)+1e-10) should never fail. The choice of this "epsilon" is not a trivial task.

More demonstration, using a more general task - trying to implement int log(int x, int base):

The testing code:

static int pow(int base, int power) {
    int result = 1;
    for (int i = 0; i < power; i++)
        result *= base;
    return result;
}

private static void test(int base, int pow) {
    int x = pow(base, pow);
    if (pow != log(x, base))
        System.out.println(String.format("error at %d^%d", base, pow));
    if(pow!=0 && (pow-1) != log(x-1, base))
        System.out.println(String.format("error at %d^%d-1", base, pow));
}

public static void main(String[] args) {
    for (int base = 2; base < 500; base++) {
        int maxPow = (int) (Math.log(Integer.MAX_VALUE) / Math.log(base));
        for (int pow = 0; pow <= maxPow; pow++) {
            test(base, pow);
        }
    }
}

If we use the most straight-forward implementation of logarithm,

static int log(int x, int base)
{
    return (int) (Math.log(x) / Math.log(base));
}

this prints:

error at 3^5
error at 3^10
error at 3^13
error at 3^15
error at 3^17
error at 9^5
error at 10^3
error at 10^6
error at 10^9
error at 11^7
error at 12^7
...

To completely get rid of errors I had to add epsilon which is between 1e-11 and 1e-14. Could you have told this before testing? I definitely could not.

How can I open multiple files using "with open" in Python?

From Python 3.10 there is a new feature of Parenthesized context managers, which permits syntax like:

with (
    open("a", "w") as a,
    open("b", "w") as b
):
    do_something()

Running MSBuild fails to read SDKToolsPath

CMD wrapper
I have tried all the stuff from here and even more. Nothing helped me.

I applied a CMD wrappers for MSBuild and DevEnv.com.
Main idea inside of such a wrapper is to make a prepared environment by calling Command Prompts from Visual Studio supply. And then pass the standard input parameters to a call of MSBuild or DevEnv.com.

Anyway, on my build-server now I can build projects from different Visual Studio versions.

How to use
I had to substitute calls to MSBuild and DevEnv by a call to my batch file wrappers.
And I didn't change any input parameters. As an example for my MSBuild wrapper call:

MsBuild_Wrapper.bat MySolution.sln /target Build /property:Configuration=Release

Ready solution
In fact, I got much more troubles with a migration from VS 2010 to VS 2015. But this one was the first and the toughest.
So, my modest rescue recipe for a Build Server is here. Possibly it is difficult to understand all this CMD style there from a first moment but any logic is obvious, I hope.

Hints
There are
MSBuild Command Prompt for Visual Studio and Developer Command Prompt for Visual Studio
I use them appropriately for MSBuild and DevEnv.com. But probably the MSBuild Command Prompt will be enough.

For VS 2015 those command prompts are here C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\Tools\. Or look through the Windows programs menu.

To pass all input parameters to MSBuild or DevEnv inside a batch file I used CALL MSBuild %*

How to get Current Timestamp from Carbon in Laravel 5

It may be a little late, but you could use the helper function time() to get the current timestamp. I tried this function and it did the job, no need for classes :).

You can find this in the official documentation at https://laravel.com/docs/5.0/templates

Regards.

Does a favicon have to be 32x32 or 16x16?

The favicon doesn't have to be 16x16 or 32x32. You can create a favicon that is 80x80 or 100x100, just make sure that both values are the same size, and obviously don't make it too large or too small, choose a reasonable size.

Random number in range [min - max] using PHP

In a new PHP7 there is a finally a support for a cryptographically secure pseudo-random integers.

int random_int ( int $min , int $max )

random_int — Generates cryptographically secure pseudo-random integers

which basically makes previous answers obsolete.

Clear dropdownlist with JQuery

<select id="ddlvalue" name="ddlvaluename">
<option value='0' disabled selected>Select Value</option>
<option value='1' >Value 1</option>
<option value='2' >Value 2</option>
</select>

<input type="submit" id="btn_submit" value="click me"/>



<script>
$('#btn_submit').on('click',function(){
      $('#ddlvalue').val(0);
});
</script>

Stripping everything but alphanumeric chars from a string in Python

How about:

def ExtractAlphanumeric(InputString):
    from string import ascii_letters, digits
    return "".join([ch for ch in InputString if ch in (ascii_letters + digits)])

This works by using list comprehension to produce a list of the characters in InputString if they are present in the combined ascii_letters and digits strings. It then joins the list together into a string.

Is there a way to use use text as the background with CSS?

I hope this might help you

_x000D_
_x000D_
<!DOCTYPE html>
<html>
<head>
<style>

 :root:after { 
         
            content: "Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark   Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark "; 
            position: fixed; 
            transform: rotate(300deg); 
            -webkit-transform: rotate(300deg); 
            color: rgb(187, 182, 182); 
            top:0;                     
            z-index: -1; 
        } 
</style>
</head>
<body>
<p>hey my name is JHM</p>
</body>
</html>
_x000D_
_x000D_
_x000D_

Firebase onMessageReceived not called when app in background

Override the handleIntent Method of the FirebaseMessageService works for me.

here the code in C# (Xamarin)

public override void HandleIntent(Intent intent)
{
    try
    {
        if (intent.Extras != null)
        {
            var builder = new RemoteMessage.Builder("MyFirebaseMessagingService");

            foreach (string key in intent.Extras.KeySet())
            {
                builder.AddData(key, intent.Extras.Get(key).ToString());
            }

            this.OnMessageReceived(builder.Build());
        }
        else
        {
            base.HandleIntent(intent);
        }
    }
    catch (Exception)
    {
        base.HandleIntent(intent);
    }
}

and thats the Code in Java

public void handleIntent(Intent intent)
{
    try
    {
        if (intent.getExtras() != null)
        {
            RemoteMessage.Builder builder = new RemoteMessage.Builder("MyFirebaseMessagingService");

            for (String key : intent.getExtras().keySet())
            {
                builder.addData(key, intent.getExtras().get(key).toString());
            }

            onMessageReceived(builder.build());
        }
        else
        {
            super.handleIntent(intent);
        }
    }
    catch (Exception e)
    {
        super.handleIntent(intent);
    }
}

Read file-contents into a string in C++

Like this:

#include <fstream>
#include <string>

int main(int argc, char** argv)
{

  std::ifstream ifs("myfile.txt");
  std::string content( (std::istreambuf_iterator<char>(ifs) ),
                       (std::istreambuf_iterator<char>()    ) );

  return 0;
}

The statement

  std::string content( (std::istreambuf_iterator<char>(ifs) ),
                       (std::istreambuf_iterator<char>()    ) );

can be split into

std::string content;
content.assign( (std::istreambuf_iterator<char>(ifs) ),
                (std::istreambuf_iterator<char>()    ) );

which is useful if you want to just overwrite the value of an existing std::string variable.

Create a new workspace in Eclipse

You can create multiple workspaces in Eclipse. You have to just specify the path of the workspace during Eclipse startup. You can even switch workspaces via File?Switch workspace.

You can then import project to your workspace, copy paste project to your new workspace folder, then

File?Import?Existing project in to workspace?select project.

How to write a function that takes a positive integer N and returns a list of the first N natural numbers

Here are a few ways to create a list with N of continuous natural numbers starting from 1.

1 range:

def numbers(n): 
    return range(1, n+1);

2 List Comprehensions:

def numbers(n):
    return [i for i in range(1, n+1)]

You may want to look into the method xrange and the concepts of generators, those are fun in python. Good luck with your Learning!

What does "hard coded" mean?

The antonym of Hard-Coding is Soft-Coding. For a better understanding of Hard Coding, I will introduce both terms.

  • Hard-coding: feature is coded to the system not allowing for configuration;
  • Parametric: feature is configurable via table driven, or properties files with limited parametric values ;
  • Soft-coding: feature uses “engines” that derive results based on any number of parametric values (e.g. business rules in BRE); rules are coded but exist as parameters in system, written in script form

Examples:

// firstName has a hard-coded value of "hello world"
string firstName = "hello world";

// firstName has a non-hard-coded provided as input
Console.WriteLine("first name :");
string firstName = Console.ReadLine();

A hard-coded constant[1]:

float areaOfCircle(int radius)
{
    float area = 0;
    area = 3.14*radius*radius;  //  3.14 is a hard-coded value
    return area;
}

Additionally, hard-coding and soft-coding could be considered to be anti-patterns[2]. Thus, one should strive for balance between hard and soft-coding.

  1. Hard CodingHard coding” is a well-known antipattern against which most web development books warns us right in the preface. Hard coding is the unfortunate practice in which we store configuration or input data, such as a file path or a remote host name, in the source code rather than obtaining it from a configuration file, a database, a user input, or another external source.

    The main problem with hard code is that it only works properly in a certain environment, and at any time the conditions change, we need to modify the source code, usually in multiple separate places.

  2. Soft Coding
    If we try very hard to avoid the pitfall of hard coding, we can easily run into another antipattern called “soft coding”, which is its exact opposite.

    In soft coding, we put things that should be in the source code into external sources, for example we store business logic in the database. The most common reason why we do so, is the fear that business rules will change in the future, therefore we will need to rewrite the code.

    In extreme cases, a soft coded program can become so abstract and convoluted that it is almost impossible to comprehend it (especially for new team members), and extremely hard to maintain and debug.

Sources and Citations:

1: Quora: What does hard-coded something mean in computer programming context?
2: Hongkiat: The 10 Coding Antipatterns You Must Avoid

Further Reading:

Software Engineering SE: Is it ever a good idea to hardcode values into our applications?
Wikipedia: Hardcoding
Wikipedia: Soft-coding

jQuery.click() vs onClick

Difference in works. If you use click(), you can add several functions, but if you use an attribute, only one function will be executed - the last one.

DEMO

HTML

<span id="JQueryClick">Click #JQuery</span> </br>
<span id="JQueryAttrClick">Click #Attr</span> </br>

JavaScript

$('#JQueryClick').click(function(){alert('1')})
$('#JQueryClick').click(function(){alert('2')})

$('#JQueryAttrClick').attr('onClick'," alert('1')" ) //This doesn't work
$('#JQueryAttrClick').attr('onClick'," alert('2')" )

If we are talking about performance, in any case directly using is always faster, but using of an attribute, you will be able to assign only one function.

How can I pretty-print JSON using Go?

package cube

import (
    "encoding/json"
    "fmt"
    "github.com/magiconair/properties/assert"
    "k8s.io/api/rbac/v1beta1"
    v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
    "testing"
)

func TestRole(t *testing.T)  {
    clusterRoleBind := &v1beta1.ClusterRoleBinding{
        ObjectMeta: v1.ObjectMeta{
            Name: "serviceaccounts-cluster-admin",
        },
        RoleRef: v1beta1.RoleRef{
            APIGroup: "rbac.authorization.k8s.io",
            Kind:     "ClusterRole",
            Name:     "cluster-admin",
        },
        Subjects: []v1beta1.Subject{{
            Kind:     "Group",
            APIGroup: "rbac.authorization.k8s.io",
            Name:     "system:serviceaccounts",
        },
        },
    }
    b, err := json.MarshalIndent(clusterRoleBind, "", "  ")
    assert.Equal(t, nil, err)
    fmt.Println(string(b))
}

How it looks like

Fade Effect on Link Hover?

Nowadays people are just using CSS3 transitions because it's a lot easier than messing with JS, browser support is reasonably good and it's merely cosmetic so it doesn't matter if it doesn't work.

Something like this gets the job done:

a {
  color:blue;
  /* First we need to help some browsers along for this to work.
     Just because a vendor prefix is there, doesn't mean it will
     work in a browser made by that vendor either, it's just for
     future-proofing purposes I guess. */
  -o-transition:.5s;
  -ms-transition:.5s;
  -moz-transition:.5s;
  -webkit-transition:.5s;
  /* ...and now for the proper property */
  transition:.5s;
}
a:hover { color:red; }

You can also transition specific CSS properties with different timings and easing functions by separating each declaration with a comma, like so:

a {
  color:blue; background:white;
  -o-transition:color .2s ease-out, background 1s ease-in;
  -ms-transition:color .2s ease-out, background 1s ease-in;
  -moz-transition:color .2s ease-out, background 1s ease-in;
  -webkit-transition:color .2s ease-out, background 1s ease-in;
  /* ...and now override with proper CSS property */
  transition:color .2s ease-out, background 1s ease-in;
}
a:hover { color:red; background:yellow; }

Demo here

Is it possible to compile a program written in Python?

Avoiding redundancy I don't repeat my answer here again.

Please refer to my answer here. (note that answer only covers compiling to python bytecode.)

ruby LoadError: cannot load such file

For security & other reasons, ruby does not by default include the current directory in the load_path. You may want to check this for more details - Why does Ruby 1.9.2 remove "." from LOAD_PATH, and what's the alternative?

Google Maps API - Get Coordinates of address

A Nuget solved my problem:Geocoding.Google 4.0.0. Install it so not necessary to write extra classes etc.

https://www.nuget.org/packages/Geocoding.Google/

What is the difference between concurrent programming and parallel programming?

Classic scheduling of tasks can be serial, parallel or concurrent.

  • Serial: tasks must be executed one after the other in a known tricked order or it will not work. Easy enough.

  • Parallel: tasks must be executed at the same time or it will not work.

    • Any failure of any of the tasks - functionally or in time - will result in total system failure.
    • All tasks must have a common reliable sense of time.

    Try to avoid this or we will have tears by tea time.

  • Concurrent: we do not care. We are not careless, though: we have analysed it and it doesn't matter; we can therefore execute any task using any available facility at any time. Happy days.

Often, the available scheduling changes at known events which we call a state change.

People often think this is about software, but it is in fact a systems design concept that pre-dates computers; software systems were a little slow in the uptake, very few software languages even attempt to address the problem. You might try looking up the transputer language occam if you are interested.

Succinctly, systems design addresses the following:

  • the verb - what you are doing (operation or algorithm)
  • the noun - what you are doing it to (data or interface)
  • when - initiation, schedule, state changes
  • how - serial, parallel, concurrent
  • where - once you know when things happen, you can say where they can happen and not before.
  • why - is this the way to do it? Are there other ways, and more importantly, a better way? What happens if you don't do it?

Good luck.

How to add image for button in android?

You can create an ImageButton in your android activity_main.xml and which image you want to place in your button just paste that image in your drawable folder below is the sample code for your reference.

<ImageButton
    android:id="@+id/button"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"

    android:layout_alignParentBottom="true"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true"
    android:layout_marginBottom="49dp"
    android:layout_weight="1"
    android:onClick="prev"
    android:src="@drawable/prev"
    />

How do you create a read-only user in PostgreSQL?

CREATE USER username SUPERUSER  password 'userpass';
ALTER USER username set default_transaction_read_only = on;

Determine if two rectangles overlap each other?

Here's how it's done in the Java API:

public boolean intersects(Rectangle r) {
    int tw = this.width;
    int th = this.height;
    int rw = r.width;
    int rh = r.height;
    if (rw <= 0 || rh <= 0 || tw <= 0 || th <= 0) {
        return false;
    }
    int tx = this.x;
    int ty = this.y;
    int rx = r.x;
    int ry = r.y;
    rw += rx;
    rh += ry;
    tw += tx;
    th += ty;
    //      overflow || intersect
    return ((rw < rx || rw > tx) &&
            (rh < ry || rh > ty) &&
            (tw < tx || tw > rx) &&
            (th < ty || th > ry));
}

DataGridView - how to set column width?

i suggest to give a width to all the grid's columns like this :

DataGridViewTextBoxColumn col = new DataGridViewTextBoxColumn();
col.HeaderText = "phone"            
col.Width = 120;
col.DataPropertyName = (if you use a datasource)
thegrid.Columns.Add(col);    

and for the main(or the longest) column(let's say address) do this :

col = new DataGridViewTextBoxColumn();
col.HeaderText = "address";
col.Width = 120;

tricky part

col.MinimumWidth = 120;
col.AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;

tricky part

col.DataPropertyName = (same as above)
thegrid.Columns.Add(col);

In this way, if you stretch the form (and the grid is "dock filled" in his container) the main column, in this case the address column, takes all the space available, but it never goes less than col.MinimumWidth, so it's the only one that is resized.

I use it, when i have a grid and its last column is used for display an image (like icon detail or icon delete..) and it doesn't have the header and it has to be always the smallest one.

django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module: No module named MySQLdb

For Ubuntu 16.04 and 18.04 or python 3 versions

sudo apt-get install python3-mysqldb

How do you specify the Java compiler version in a pom.xml file?

<plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.3</version>
            <configuration>
                <fork>true</fork>
                <source>1.8</source>
                <target>1.8</target>
            </configuration>
        </plugin> 

How can I disable a button in a jQuery dialog from a function?

According to the documentation:

https://api.jqueryui.com/dialog/#option-buttons

// Setter
$( ".selector" ).button( "option", "disabled", true );

To be able to simply select the button, you could add an own CSS class to the button, that should be enabled / disabled.

// while initializing
$("#dialog").dialog({
...
buttons: [{
    disabled: true,
    text: "Add to request list",
    click: function (e: JQueryEventObject) {
        // Some logic
    },
    "class": "myDialogButton"
}]
...
});

Then the enabling / disabling would look like this:

$(".myDialogButton" ).button( "option", "disabled", (SOME_CONDITION) ? true : false);

Can a class member function template be virtual?

While an older question that has been answered by many I believe a succinct method, not so different from the others posted, is to use a minor macro to help ease the duplication of class declarations.

// abstract.h

// Simply define the types that each concrete class will use
#define IMPL_RENDER() \
    void render(int a, char *b) override { render_internal<char>(a, b); }   \
    void render(int a, short *b) override { render_internal<short>(a, b); } \
    // ...

class Renderable
{
public:
    // Then, once for each on the abstract
    virtual void render(int a, char *a) = 0;
    virtual void render(int a, short *b) = 0;
    // ...
};

So now, to implement our subclass:

class Box : public Renderable
{
public:
    IMPL_RENDER() // Builds the functions we want

private:
    template<typename T>
    void render_internal(int a, T *b); // One spot for our logic
};

The benefit here is that, when adding a newly supported type, it can all be done from the abstract header and forego possibly rectifying it in multiple source/header files.

Copy Data from a table in one Database to another separate database

Im prefer this one.

INSERT INTO 'DB_NAME' 
(SELECT * from 'DB_NAME@DB_LINK')
MINUS 
(SELECT * FROM 'DB_NAME');

Which means will insert whatsoever that not included on DB_NAME but included at DB_NAME@DB_LINK. Hope this help.

Java Loop every minute

Use Thread.sleep(long millis).

Causes the currently executing thread to sleep (temporarily cease execution) for the specified number of milliseconds, subject to the precision and accuracy of system timers and schedulers. The thread does not lose ownership of any monitors.

One minute would be (60*1000) = 60000 milliseconds.


For example, this loop will print the current time once every 5 seconds:

    try {
        while (true) {
            System.out.println(new Date());
            Thread.sleep(5 * 1000);
        }
    } catch (InterruptedException e) {
        e.printStackTrace();
    }

If your sleep period becomes too large for int, explicitly compute in long (e.g. 1000L).

Can't append <script> element

Your script is executing , you just can't use document.write from it. Use an alert to test it and avoid using document.write. The statements of your js file with document.write will not be executed and the rest of the function will be executed.

How to include *.so library in Android Studio?

Solution 1 : Creation of a JniLibs folder

Create a folder called “jniLibs” into your app and the folders containing your *.so inside. The "jniLibs" folder needs to be created in the same folder as your "Java" or "Assets" folders.

Solution 2 : Modification of the build.gradle file

If you don’t want to create a new folder and keep your *.so files into the libs folder, it is possible !

In that case, just add your *.so files into the libs folder (please respect the same architecture as the solution 1 : libs/armeabi/.so for instance) and modify the build.gradle file of your app to add the source directory of the jniLibs.

sourceSets {
    main {
        jniLibs.srcDirs = ["libs"]
    }
}

You will have more explanations, with screenshots to help you here ( Step 6 ):

http://blog.guillaumeagis.eu/setup-andengine-with-android-studio/

EDIT It had to be jniLibs.srcDirs, not jni.srcDirs - edited the code. The directory can be a [relative] path that points outside of the project directory.

Remove file extension from a file name string

    /// <summary>
    /// Get the extension from the given filename
    /// </summary>
    /// <param name="fileName">the given filename ie:abc.123.txt</param>
    /// <returns>the extension ie:txt</returns>
    public static string GetFileExtension(this string fileName)
    {
        string ext = string.Empty;
        int fileExtPos = fileName.LastIndexOf(".", StringComparison.Ordinal);
        if (fileExtPos >= 0)
            ext = fileName.Substring(fileExtPos, fileName.Length - fileExtPos);

        return ext;
    }

How to define static constant in a class in swift

What about using computed properties?

class MyClass {
  class var myConstant: String { return "What is Love? Baby don't hurt me" }
}

MyClass.myConstant

java.lang.NullPointerException: Attempt to invoke virtual method 'int android.view.View.getImportantForAccessibility()' on a null object reference

#use return convertView;

Code:

public View getView(final int position, View convertView, ViewGroup parent) {

    //convertView = null;

    if (convertView == null) {

        LayoutInflater mInflater = (LayoutInflater) context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
        convertView = mInflater.inflate(R.layout.list_item, null);     

        TextView tv = (TextView) convertView.findViewById(R.id.name);
        Button rm_btn = (Button) convertView.findViewById(R.id.rm_btn);

        Model m = modelList.get(position);
        tv.setText(m.getName());

        // click listener for remove button  ??????????
        rm_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                modelList.remove(position);
                notifyDataSetChanged();
            }
        });
    }

    ///#use    return convertView;
    return convertView;
}

Testing javascript with Mocha - how can I use console.log to debug a test?

What Mocha options are you using?

Maybe it is something to do with reporter (-R) or ui (-ui) being used?

console.log(msg);

works fine during my test runs, though sometimes mixed in a little goofy. Presumably due to the async nature of the test run.

Here are the options (mocha.opts) I'm using:

--require should
-R spec
--ui bdd

Hmm..just tested without any mocha.opts and console.log still works.

MySQL LEFT JOIN Multiple Conditions

SELECT * FROM a WHERE a.group_id IN 
(SELECT group_id FROM b WHERE b.user_id!=$_SESSION{'[user_id']} AND b.group_id = a.group_id)
WHERE a.keyword LIKE '%".$keyword."%';

Working with select using AngularJS's ng-options

It can be useful. Bindings do not always work.

<select id="product" class="form-control" name="product" required
        ng-model="issue.productId"
        ng-change="getProductVersions()"
        ng-options="p.id as p.shortName for p in products"></select>

For example, you fill the options list source model from a REST service. A selected value was known before filling the list, and it was set. After executing the REST request with $http, the list option is done.

But the selected option is not set. For unknown reasons AngularJS in shadow $digest executing does not bind selected as it should be. I have got to use jQuery to set the selected. It`s important! AngularJS, in shadow, adds the prefix to the value of the attr "value" for generated by ng-repeat options. For int it is "number:".

$scope.issue.productId = productId;
function activate() {
    $http.get('/product/list')
       .then(function (response) {
           $scope.products = response.data;

           if (productId) {
               console.log("" + $("#product option").length);//for clarity
               $timeout(function () {
                   console.log("" + $("#product option").length);//for clarity
                   $('#product').val('number:'+productId);

               }, 200);
           }
       });
}

python capitalize first letter only

I came up with this:

import re

regex = re.compile("[A-Za-z]") # find a alpha
str = "1st str"
s = regex.search(str).group() # find the first alpha
str = str.replace(s, s.upper(), 1) # replace only 1 instance
print str

How to perform OR condition in django queryset?

Just adding this for multiple filters attaching to Q object, if someone might be looking to it. If a Q object is provided, it must precede the definition of any keyword arguments. Otherwise its an invalid query. You should be careful when doing it.

an example would be

from django.db.models import Q
User.objects.filter(Q(income__gte=5000) | Q(income__isnull=True),category='income')

Here the OR condition and a filter with category of income is taken into account

How to write :hover condition for a:before and a:after?

Write a:hover::before instead of a::before:hover: example.

List<T> or IList<T>

Interface is a promise (or a contract).

As it is always with the promises - smaller the better.

Change the Blank Cells to "NA"

My function takes into account factor, character vector and potential attributes, if you use haven or foreign package to read external files. Also it allows matching different self-defined na.strings. To transform all columns, simply use lappy: df[] = lapply(df, blank2na, na.strings=c('','NA','na','N/A','n/a','NaN','nan'))

See more the comments:

#' Replaces blank-ish elements of a factor or character vector to NA
#' @description Replaces blank-ish elements of a factor or character vector to NA
#' @param x a vector of factor or character or any type
#' @param na.strings case sensitive strings that will be coverted to NA. The function will do a trimws(x,'both') before conversion. If NULL, do only trimws, no conversion to NA.
#' @return Returns a vector trimws (always for factor, character) and NA converted (if matching na.strings). Attributes will also be kept ('label','labels', 'value.labels').
#' @seealso \code{\link{ez.nan2na}}
#' @export
blank2na = function(x,na.strings=c('','.','NA','na','N/A','n/a','NaN','nan')) {
    if (is.factor(x)) {
        lab = attr(x, 'label', exact = T)
        labs1 <- attr(x, 'labels', exact = T)
        labs2 <- attr(x, 'value.labels', exact = T)

        # trimws will convert factor to character
        x = trimws(x,'both')
        if (! is.null(lab)) lab = trimws(lab,'both')
        if (! is.null(labs1)) labs1 = trimws(labs1,'both')
        if (! is.null(labs2)) labs2 = trimws(labs2,'both')

        if (!is.null(na.strings)) {
            # convert to NA
            x[x %in% na.strings] = NA
            # also remember to remove na.strings from value labels 
            labs1 = labs1[! labs1 %in% na.strings]
            labs2 = labs2[! labs2 %in% na.strings]
        }

        # the levels will be reset here
        x = factor(x)

        if (! is.null(lab)) attr(x, 'label') <- lab
        if (! is.null(labs1)) attr(x, 'labels') <- labs1
        if (! is.null(labs2)) attr(x, 'value.labels') <- labs2
    } else if (is.character(x)) {
        lab = attr(x, 'label', exact = T)
        labs1 <- attr(x, 'labels', exact = T)
        labs2 <- attr(x, 'value.labels', exact = T)

        # trimws will convert factor to character
        x = trimws(x,'both')
        if (! is.null(lab)) lab = trimws(lab,'both')
        if (! is.null(labs1)) labs1 = trimws(labs1,'both')
        if (! is.null(labs2)) labs2 = trimws(labs2,'both')

        if (!is.null(na.strings)) {
            # convert to NA
            x[x %in% na.strings] = NA
            # also remember to remove na.strings from value labels 
            labs1 = labs1[! labs1 %in% na.strings]
            labs2 = labs2[! labs2 %in% na.strings]
        }

        if (! is.null(lab)) attr(x, 'label') <- lab
        if (! is.null(labs1)) attr(x, 'labels') <- labs1
        if (! is.null(labs2)) attr(x, 'value.labels') <- labs2
    } else {
        x = x
    }
    return(x)
}

How to see the CREATE VIEW code for a view in PostgreSQL?

select definition from pg_views where viewname = 'my_view'

C++ Remove new line from multiline string

Use std::algorithms. This question has some suitably reusable suggestions Remove spaces from std::string in C++

How can I see all the "special" characters permissible in a varchar or char field in SQL Server?

You probably just need to see the ASCII and EXTENDED ASCII character sets. As far as I know any of these are allowed in a char/varchar field.

If you use nchar/nvarchar then it's pretty much any character in any unicode set in the world.

enter image description here

enter image description here

MySQL limit from descending order

No, you shouldn't do this. Without an ORDER BY clause you shouldn't rely on the order of the results being the same from query to query. It might work nicely during testing but the order is indeterminate and could break later. Use an order by.

SELECT * FROM table1 ORDER BY id LIMIT 5

By the way, another way of getting the last 3 rows is to reverse the order and select the first three rows:

SELECT * FROM table1 ORDER BY id DESC LIMIT 3

This will always work even if the number of rows in the result set isn't always 8.

How can I write an anonymous function in Java?

Anonymous inner classes implementing or extending the interface of an existing type has been done in other answers, although it is worth noting that multiple methods can be implemented (often with JavaBean-style events, for instance).

A little recognised feature is that although anonymous inner classes don't have a name, they do have a type. New methods can be added to the interface. These methods can only be invoked in limited cases. Chiefly directly on the new expression itself and within the class (including instance initialisers). It might confuse beginners, but it can be "interesting" for recursion.

private static String pretty(Node node) {
    return "Node: " + new Object() {
        String print(Node cur) {
            return cur.isTerminal() ?
                cur.name() :
                ("("+print(cur.left())+":"+print(cur.right())+")");
        }
    }.print(node);
}

(I originally wrote this using node rather than cur in the print method. Say NO to capturing "implicitly final" locals?)

Git Checkout warning: unable to unlink files, permission denied

In my case the permission problem solved by setting www-data as an owner:

chown -R www-data project_folder_name

How To Create Table with Identity Column

CREATE TABLE [dbo].[History](
    [ID] [int] IDENTITY(1,1) NOT NULL,
    [RequestID] [int] NOT NULL,
    [EmployeeID] [varchar](50) NOT NULL,
    [DateStamp] [datetime] NOT NULL,
 CONSTRAINT [PK_History] PRIMARY KEY CLUSTERED 
(
    [ID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON)
) ON [PRIMARY]

Can not connect to local PostgreSQL

If you're getting a similar error:

psql: could not connect to server: No such file or directory
Is the server running locally and accepting
connections on Unix domain socket "/tmp/.s.PGSQL.5432"?

This might do the trick (it did for me):

initdb /usr/local/var/postgres -E utf8

The directory specified should be different if you're not using OSX/Brew.

Note: This is not the exact error message seen above, but this thread is the first result for that error message.

MySQL Event Scheduler on a specific time everyday

Try this

CREATE EVENT event1
ON SCHEDULE EVERY '1' DAY
STARTS '2012-04-17 13:00:00' -- should be in the future
DO
-- your statements
END

Setting default value in select drop-down using Angularjs

This is an old question and you might have got the answer already.

My plnkr explains on my approach to accomplish selecting a default dropdown value. Basically, I have a service which would return the dropdown values [hard coded to test]. I was not able to select the value by default and almost spend a day and finally figured out that I should have set $scope.proofGroupId = "47"; instead of $scope.proofGroupId = 47; in the script.js file. It was my bad and I did not notice that I was setting an integer 47 instead of the string "47". I retained the plnkr as it is just in case if some one would like to see. Hopefully, this would help some one.

How is Docker different from a virtual machine?

There are many answers which explain more detailed on the differences, but here is my very brief explanation.

One important difference is that VMs use a separate kernel to run the OS. That's the reason it is heavy and takes time to boot, consuming more system resources.

In Docker, the containers share the kernel with the host; hence it is lightweight and can start and stop quickly.

In Virtualization, the resources are allocated in the beginning of set up and hence the resources are not fully utilized when the virtual machine is idle during many of the times. In Docker, the containers are not allocated with fixed amount of hardware resources and is free to use the resources depending on the requirements and hence it is highly scalable.

Docker uses UNION File system .. Docker uses a copy-on-write technology to reduce the memory space consumed by containers. Read more here

SQL Server 2005 Using DateAdd to add a day to a date

DECLARE @date DateTime
SET @date = GetDate()
SET @date = DateAdd(day, 1, @date)

SELECT @date

Set System.Drawing.Color values

You must use Color.FromArgb method to create new color structure

var newColor = Color.FromArgb(0xCC,0xBB,0xAA);

How to resolve "must be an instance of string, string given" prior to PHP 7?

As of PHP 7.0 type declarations allow scalar types, so these types are now available: self, array, callable, bool, float, int, string. The first three were available in PHP 5, but the last four are new in PHP 7. If you use anything else (e.g. integer or boolean) that will be interpreted as a class name.

See the PHP manual for more information.

ASP.NET MVC Html.ValidationSummary(true) does not display model errors

@Html.ValidationSummary(false,"", new { @class = "text-danger" })

Using this line may be helpful

Delete worksheet in Excel using VBA

You could use On Error Resume Next then there is no need to loop through all the sheets in the workbook.

With On Error Resume Next the errors are not propagated, but are suppressed instead. So here when the sheets does't exist or when for any reason can't be deleted, nothing happens. It is like when you would say : delete this sheets, and if it fails I don't care. Excel is supposed to find the sheet, you will not do any searching.

Note: When the workbook would contain only those two sheets, then only the first sheet will be deleted.

Dim book
Dim sht as Worksheet

set book= Workbooks("SomeBook.xlsx")

On Error Resume Next

Application.DisplayAlerts=False 

Set sht = book.Worksheets("ID Sheet")
sht.Delete

Set sht = book.Worksheets("Summary")
sht.Delete

Application.DisplayAlerts=True 

On Error GoTo 0

Python Turtle, draw text with on screen with larger font

You can also use "bold" and "italic" instead of "normal" here. "Verdana" can be used for fontname..

But another question is this: How do you set the color of the text You write?

Answer: You use the turtle.color() method or turtle.fillcolor(), like this:

turtle.fillcolor("blue")

or just:

turtle.color("orange")

These calls must come before the turtle.write() command..

Move column by name to front of table in pandas

You can use the df.reindex() function in pandas. df is

                      Net  Upper   Lower  Mid  Zsore
Answer option                                      
More than once a day  0%  0.22%  -0.12%    2     65
Once a day            0%  0.32%  -0.19%    3     45
Several times a week  2%  2.45%   1.10%    4     78
Once a week           1%  1.63%  -0.40%    6     65

define an list of column names

cols = df.columns.tolist()
cols
Out[13]: ['Net', 'Upper', 'Lower', 'Mid', 'Zsore']

move the column name to wherever you want

cols.insert(0, cols.pop(cols.index('Mid')))
cols
Out[16]: ['Mid', 'Net', 'Upper', 'Lower', 'Zsore']

then use df.reindex() function to reorder

df = df.reindex(columns= cols)

out put is: df

                      Mid  Upper   Lower Net  Zsore
Answer option                                      
More than once a day    2  0.22%  -0.12%  0%     65
Once a day              3  0.32%  -0.19%  0%     45
Several times a week    4  2.45%   1.10%  2%     78
Once a week             6  1.63%  -0.40%  1%     65

Git refusing to merge unrelated histories on rebase

I got this error when I set up a local repository first. Then I went to GitHub and created a new repository. Then I ran

git remote add origin <repository url>

When I tried to push or pull, I got the same fatal: unrelated_histories error every time.

Here is how I fixed it:

git pull origin master --allow-unrelated-histories
git merge origin origin/master
... add and commit here...
git push origin master

How to create a template function within a class? (C++)

The easiest way is to put the declaration and definition in the same file, but it may cause over-sized excutable file. E.g.

class Foo
{
public:
template <typename T> void some_method(T t) {//...}
}

Also, it is possible to put template definition in the separate files, i.e. to put them in .cpp and .h files. All you need to do is to explicitly include the template instantiation to the .cpp files. E.g.

// .h file
class Foo
{
public:
template <typename T> void some_method(T t);
}

// .cpp file
//...
template <typename T> void Foo::some_method(T t) 
{//...}
//...

template void Foo::some_method<int>(int);
template void Foo::some_method<double>(double);

Write to Windows Application Event Log

This is the logger class that I use. The private Log() method has EventLog.WriteEntry() in it, which is how you actually write to the event log. I'm including all of this code here because it's handy. In addition to logging, this class will also make sure the message isn't too long to write to the event log (it will truncate the message). If the message was too long, you'd get an exception. The caller can also specify the source. If the caller doesn't, this class will get the source. Hope it helps.

By the way, you can get an ObjectDumper from the web. I didn't want to post all that here. I got mine from here: C:\Program Files (x86)\Microsoft Visual Studio 10.0\Samples\1033\CSharpSamples.zip\LinqSamples\ObjectDumper

using System;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
using Xanico.Core.Utilities;

namespace Xanico.Core
{
    /// <summary>
    /// Logging operations
    /// </summary>
    public static class Logger
    {
        // Note: The actual limit is higher than this, but different Microsoft operating systems actually have
        //       different limits. So just use 30,000 to be safe.
        private const int MaxEventLogEntryLength = 30000;

        /// <summary>
        /// Gets or sets the source/caller. When logging, this logger class will attempt to get the
        /// name of the executing/entry assembly and use that as the source when writing to a log.
        /// In some cases, this class can't get the name of the executing assembly. This only seems
        /// to happen though when the caller is in a separate domain created by its caller. So,
        /// unless you're in that situation, there is no reason to set this. However, if there is
        /// any reason that the source isn't being correctly logged, just set it here when your
        /// process starts.
        /// </summary>
        public static string Source { get; set; }

        /// <summary>
        /// Logs the message, but only if debug logging is true.
        /// </summary>
        /// <param name="message">The message.</param>
        /// <param name="debugLoggingEnabled">if set to <c>true</c> [debug logging enabled].</param>
        /// <param name="source">The name of the app/process calling the logging method. If not provided,
        /// an attempt will be made to get the name of the calling process.</param>
        public static void LogDebug(string message, bool debugLoggingEnabled, string source = "")
        {
            if (debugLoggingEnabled == false) { return; }

            Log(message, EventLogEntryType.Information, source);
        }

        /// <summary>
        /// Logs the information.
        /// </summary>
        /// <param name="message">The message.</param>
        /// <param name="source">The name of the app/process calling the logging method. If not provided,
        /// an attempt will be made to get the name of the calling process.</param>
        public static void LogInformation(string message, string source = "")
        {
            Log(message, EventLogEntryType.Information, source);
        }

        /// <summary>
        /// Logs the warning.
        /// </summary>
        /// <param name="message">The message.</param>
        /// <param name="source">The name of the app/process calling the logging method. If not provided,
        /// an attempt will be made to get the name of the calling process.</param>
        public static void LogWarning(string message, string source = "")
        {
            Log(message, EventLogEntryType.Warning, source);
        }

        /// <summary>
        /// Logs the exception.
        /// </summary>
        /// <param name="ex">The ex.</param>
        /// <param name="source">The name of the app/process calling the logging method. If not provided,
        /// an attempt will be made to get the name of the calling process.</param>
        public static void LogException(Exception ex, string source = "")
        {
            if (ex == null) { throw new ArgumentNullException("ex"); }

            if (Environment.UserInteractive)
            {
                Console.WriteLine(ex.ToString());
            }

            Log(ex.ToString(), EventLogEntryType.Error, source);
        }

        /// <summary>
        /// Recursively gets the properties and values of an object and dumps that to the log.
        /// </summary>
        /// <param name="theObject">The object to log</param>
        [SuppressMessage("Microsoft.Globalization", "CA1303:Do not pass literals as localized parameters", MessageId = "Xanico.Core.Logger.Log(System.String,System.Diagnostics.EventLogEntryType,System.String)")]
        [SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames", MessageId = "object")]
        public static void LogObjectDump(object theObject, string objectName, string source = "")
        {
            const int objectDepth = 5;
            string objectDump = ObjectDumper.GetObjectDump(theObject, objectDepth);

            string prefix = string.Format(CultureInfo.CurrentCulture,
                                          "{0} object dump:{1}",
                                          objectName,
                                          Environment.NewLine);

            Log(prefix + objectDump, EventLogEntryType.Warning, source);
        }

        private static void Log(string message, EventLogEntryType entryType, string source)
        {
            // Note: I got an error that the security log was inaccessible. To get around it, I ran the app as administrator
            //       just once, then I could run it from within VS.

            if (string.IsNullOrWhiteSpace(source))
            {
                source = GetSource();
            }

            string possiblyTruncatedMessage = EnsureLogMessageLimit(message);
            EventLog.WriteEntry(source, possiblyTruncatedMessage, entryType);

            // If we're running a console app, also write the message to the console window.
            if (Environment.UserInteractive)
            {
                Console.WriteLine(message);
            }
        }

        private static string GetSource()
        {
            // If the caller has explicitly set a source value, just use it.
            if (!string.IsNullOrWhiteSpace(Source)) { return Source; }

            try
            {
                var assembly = Assembly.GetEntryAssembly();

                // GetEntryAssembly() can return null when called in the context of a unit test project.
                // That can also happen when called from an app hosted in IIS, or even a windows service.

                if (assembly == null)
                {
                    assembly = Assembly.GetExecutingAssembly();
                }


                if (assembly == null)
                {
                    // From http://stackoverflow.com/a/14165787/279516:
                    assembly = new StackTrace().GetFrames().Last().GetMethod().Module.Assembly;
                }

                if (assembly == null) { return "Unknown"; }

                return assembly.GetName().Name;
            }
            catch
            {
                return "Unknown";
            }
        }

        // Ensures that the log message entry text length does not exceed the event log viewer maximum length of 32766 characters.
        private static string EnsureLogMessageLimit(string logMessage)
        {
            if (logMessage.Length > MaxEventLogEntryLength)
            {
                string truncateWarningText = string.Format(CultureInfo.CurrentCulture, "... | Log Message Truncated [ Limit: {0} ]", MaxEventLogEntryLength);

                // Set the message to the max minus enough room to add the truncate warning.
                logMessage = logMessage.Substring(0, MaxEventLogEntryLength - truncateWarningText.Length);

                logMessage = string.Format(CultureInfo.CurrentCulture, "{0}{1}", logMessage, truncateWarningText);
            }

            return logMessage;
        }
    }
}

How to extract base URL from a string in JavaScript?

I use a simple regex that extracts the host form the url:

function get_host(url){
    return url.replace(/^((\w+:)?\/\/[^\/]+\/?).*$/,'$1');
}

and use it like this

var url = 'http://www.sitename.com/article/2009/09/14/this-is-an-article/'
var host = get_host(url);

Note, if the url does not end with a / the host will not end in a /.

Here are some tests:

describe('get_host', function(){
    it('should return the host', function(){
        var url = 'http://www.sitename.com/article/2009/09/14/this-is-an-article/';
        assert.equal(get_host(url),'http://www.sitename.com/');
    });
    it('should not have a / if the url has no /', function(){
        var url = 'http://www.sitename.com';
        assert.equal(get_host(url),'http://www.sitename.com');
    });
    it('should deal with https', function(){
        var url = 'https://www.sitename.com/article/2009/09/14/this-is-an-article/';
        assert.equal(get_host(url),'https://www.sitename.com/');
    });
    it('should deal with no protocol urls', function(){
        var url = '//www.sitename.com/article/2009/09/14/this-is-an-article/';
        assert.equal(get_host(url),'//www.sitename.com/');
    });
    it('should deal with ports', function(){
        var url = 'http://www.sitename.com:8080/article/2009/09/14/this-is-an-article/';
        assert.equal(get_host(url),'http://www.sitename.com:8080/');
    });
    it('should deal with localhost', function(){
        var url = 'http://localhost/article/2009/09/14/this-is-an-article/';
        assert.equal(get_host(url),'http://localhost/');
    });
    it('should deal with numeric ip', function(){
        var url = 'http://192.168.18.1/article/2009/09/14/this-is-an-article/';
        assert.equal(get_host(url),'http://192.168.18.1/');
    });
});

"This operation requires IIS integrated pipeline mode."

GitHub solution solved the problem for me by adding

  • Global.asax.cs: Set AntiForgeryConfig.SuppressXFrameOptionsHeader = true; in Application_Start:
  • Manually add the X-Frame-Options header in Application_BeginRequest

How to SUM two fields within an SQL query

ID  VALUE1  VALUE2
===================
1   1       2

1   2       2
2   3       4
2   4       5

select ID, (coalesce(VALUE1 ,0) + coalesce(VALUE2 ,0) as Total from TableName

Python - List of unique dictionaries

I have summarized my favorites to try out:

https://repl.it/@SmaMa/Python-List-of-unique-dictionaries

# ----------------------------------------------
# Setup
# ----------------------------------------------

myList = [
  {"id":"1", "lala": "value_1"},
  {"id": "2", "lala": "value_2"}, 
  {"id": "2", "lala": "value_2"}, 
  {"id": "3", "lala": "value_3"}
]
print("myList:", myList)

# -----------------------------------------------
# Option 1 if objects has an unique identifier
# -----------------------------------------------

myUniqueList = list({myObject['id']:myObject for myObject in myList}.values())
print("myUniqueList:", myUniqueList)

# -----------------------------------------------
# Option 2 if uniquely identified by whole object
# -----------------------------------------------

myUniqueSet = [dict(s) for s in set(frozenset(myObject.items()) for myObject in myList)]
print("myUniqueSet:", myUniqueSet)

# -----------------------------------------------
# Option 3 for hashable objects (not dicts)
# -----------------------------------------------

myHashableObjects = list(set(["1", "2", "2", "3"]))
print("myHashAbleList:", myHashableObjects)

java: Class.isInstance vs Class.isAssignableFrom

clazz.isAssignableFrom(Foo.class) will be true whenever the class represented by the clazz object is a superclass or superinterface of Foo.

clazz.isInstance(obj) will be true whenever the object obj is an instance of the class clazz.

That is:

clazz.isAssignableFrom(obj.getClass()) == clazz.isInstance(obj)

is always true so long as clazz and obj are nonnull.

Use table name in MySQL SELECT "AS"

SELECT field1, field2, 'Test' AS field3 FROM Test; // replace with simple quote '

How do you make an array of structs in C?

That error means that the compiler is not able to find the definition of the type of your struct before the declaration of the array of structs, since you're saying you have the definition of the struct in a header file and the error is in nbody.c then you should check if you're including correctly the header file. Check your #include's and make sure the definition of the struct is done before declaring any variable of that type.

ActiveXObject creation error " Automation server can't create object"

i also have same problem and solve it. Please go through the link

add your site to trusted zone and change following options in ie Tools Menu -> Internet Options -> Security -> Custom level -> "Initialize and script ActiveX controls not marked as safe for scripting"

http://forums.codeguru.com/showthread.php?t=256114

How to print (using cout) a number in binary form?

Reusable function:

template<typename T>
static std::string toBinaryString(const T& x)
{
    std::stringstream ss;
    ss << std::bitset<sizeof(T) * 8>(x);
    return ss.str();
}

Usage:

int main(){
  uint16_t x=8;
  std::cout << toBinaryString(x);
}

This works with all kind of integers.

Tar error: Unexpected EOF in archive

Interesting. I have a few questions which may point out the problem.

1/ Are you untarring on the same platform as you're tarring on? They may be different versions of tar (e.g., GNU and old-unix)? If they're different, can you untar on the same box you tarred on?

2/ What happens when you simply gunzip myarchive.tar.gz? Does that work? Maybe your file is being corrupted/truncated. I'm assuming you would notice if the compression generated errors, yes?

Based on the GNU tar source, it will only print that message if find_next_block() returns 0 prematurely which is usually caused by truncated archive.

Alternative to deprecated getCellType

It looks that 3.15 offers no satisfying solution: either one uses the old style with Cell.CELL_TYPE_*, or we use the method getCellTypeEnum() which is marked as deprecated. A lot of disturbances for little add value...

Vue 2 - Mutating props vue-warn

Because Vue props is one way data flow, This prevents child components from accidentally mutating the parent’s state.

From the official Vue document, we will find 2 ways to solve this problems

  1. if child component want use props as local data, it is best to define a local data property.

      props: ['list'],
      data: function() {
        return {
          localList: JSON.parse(this.list);
        }
      }
    
    
  2. The prop is passed in as a raw value that needs to be transformed. In this case, it’s best to define a computed property using the prop’s value:

      props: ['list'],
      computed: {
        localList: function() {
           return JSON.parse(this.list);
        },
        //eg: if you want to filter this list
        validList: function() {
           return this.list.filter(product => product.isValid === true)
        }
        //...whatever to transform the list
      }
    
    
    

How to resize a VirtualBox vmdk file


VirtualBox for Windows

Resizing your disk file while preserving your virtual machine settings!


Step 1 - Resize the disk file

Start cmd.exe

cd to Oracle VM VirtualBox's dir (on 64-bit systems: "C:\Program Files\Oracle\VirtualBox\")

Run these commands (as above):

VBoxManage clonehd "C:\path\to\source.vmdk" "C:\path_to\cloned.vdi" --format vdi
VBoxManage modifyhd "C:\path\to\cloned.vdi" --resize 51200

Windows explorer and "copy address as text" via the address bar should help you get the path you need.

On windows system, The VirtaulBox VM directory underneath your user may contain an XML formatted database file of settings you've configured for your VM. Rename this file, with a .bak extension (it has a .vbox extension). Rename the original .vmdk file with a .bak extension as well to avoid another error. You can now safetly perform the third step without the error message to convert the machine back to .vmdk format, or the "duplicate disk" error.

VBoxManage clonehd "C:\path_to\cloned.vdi" "C:\path_to\source.vmdk" --format vmdk

You will be presented with a UID token. Copy this token by drag-highlighting it from the Windows Command Interpetor window and using the Ctrl+C keyboard shortcut.

Open the .vbox.bak file in a text editor such as Notepad++. You'll be presented with an XML-like database file. Look for these lines:

<VirtualBox xmlns="http://www.virtualbox.org/" version="1.16-windows">
  <Machine uuid="{some uid}" name="source disk name" OSType="the_vbox_OS" snapshotFolder="Snapshots" lastStateChange="2043-03-23T00:54:18Z">
    <MediaRegistry>
      <HardDisks>
        <HardDisk uuid="{some uid}" location="C:\path_to\source.vmdk" ...

On the line <HardDisk uuid="{some uid}" location="C:\path_to\source.vmdk" ..., delete the old UID token between the brackets and paste the one you copied from the command window. Make sure that you leave the brackets in place!

Save this file, and exit your text editor. Rename the .vbox.bak file to give it back its expected extension of .vbox.


Step 2 - Remove the junk

It is now safe to remove the .bak files remaining in the directory. What remains is a resized .vmdk with an updated .vbox database while with your previously preserved VirtualBox Manager settings.


Step 3 - Resize the disk's partition to fill the free space

You can now start the VirtualBox VM Manager and execute your VM, using the appropriate tools for the operating system to fill the new free space.

For Windows VMs, use diskpart from the command prompt booted from the Windows Recovery Consule (recovery partition) to SELECT DISK 1, LIST PARTITION and gather the partition number of your C:\ drive, then SELECT PARTITION #. You can use the EXTEND SIZE=mb to resize the Windows C:\ drive to the appropriate value. Make sure you leave room for the recovery and boot partitions! It's safe to subtract 4096 MB from your new virtual disk size to get this value, because of shadow copy and windows recovery files.

For Linux VMs, a live .ISO of gparted you can boot with the VM's disk file can be found at: http://gparted.org/ It will get you straight into a graphical user interface-based gparted-gtk, from where you can fill your free space.

For PPC / Mac VMs, Disk Utility from the Finder will asisst you in filling the free space, but you may want to consider the gparted Linux option, as currently the only method of which to boot MacOSX in VirtualBox is hackintosh, and you cannot extend your volume while booted into MacOSX. You may also want to seek out tweaking the VM's settings temporarily for gparted, to get it to boot. MacOSX partitions are recognized by gparted as HFS - "Heaping File System" partitions.


Step 4 - Cat Photos

Because the internet. ;) You're finished. Enjoy your new resized virtual .vmdk disk image with VirtualBox for Windows!

Static variable inside of a function in C

In C++11 at least, when the expression used to initialize a local static variable is not a 'constexpr' (cannot be evaluated by the compiler), then initialization must happen during the first call to the function. The simplest example is to directly use a parameter to intialize the local static variable. Thus the compiler must emit code to guess whether the call is the first one or not, which in turn requires a local boolean variable. I've compiled such example and checked this is true by seeing the assembly code. The example can be like this:

void f( int p )
{
  static const int first_p = p ;
  cout << "first p == " << p << endl ;
}

void main()
{
   f(1); f(2); f(3);
}

of course, when the expresion is 'constexpr', then this is not required and the variable can be initialized on program load by using a value stored by the compiler in the output assembly code.

`getchar()` gives the same output as the input string

Strings, by C definition, are terminated by '\0'. You have no "C strings" in your program.

Your program reads characters (buffered till ENTER) from the standard input (the keyboard) and writes them back to the standard output (the screen). It does this no matter how many characters you type or for how long you do this.

To stop the program you have to indicate that the standard input has no more data (huh?? how can a keyboard have no more data?).

You simply press Ctrl+D (Unix) or Ctrl+Z (Windows) to pretend the file has reached its end.
Ctrl+D (or Ctrl+Z) are not really characters in the C sense of the word.

If you run your program with input redirection, the EOF is the actual end of file, not a make belief one
./a.out < source.c

How to Delete a topic in apache kafka

Deletion of a topic has been supported since 0.8.2.x version. You have to enable topic deletion (setting delete.topic.enable to true) on all brokers first.

Note: Ever since 1.0.x, the functionality being stable, delete.topic.enable is by default true.

Follow this step by step process for manual deletion of topics

  1. Stop Kafka server
  2. Delete the topic directory, on each broker (as defined in the logs.dirs and log.dir properties) with rm -rf command
  3. Connect to Zookeeper instance: zookeeper-shell.sh host:port
  4. From within the Zookeeper instance:
    1. List the topics using: ls /brokers/topics
    2. Remove the topic folder from ZooKeeper using: rmr /brokers/topics/yourtopic
    3. Exit the Zookeeper instance (Ctrl+C)
  5. Restart Kafka server
  6. Confirm if it was deleted or not by using this command kafka-topics.sh --list --zookeeper host:port

How to put individual tags for a scatter plot

Perhaps use plt.annotate:

import numpy as np
import matplotlib.pyplot as plt

N = 10
data = np.random.random((N, 4))
labels = ['point{0}'.format(i) for i in range(N)]

plt.subplots_adjust(bottom = 0.1)
plt.scatter(
    data[:, 0], data[:, 1], marker='o', c=data[:, 2], s=data[:, 3] * 1500,
    cmap=plt.get_cmap('Spectral'))

for label, x, y in zip(labels, data[:, 0], data[:, 1]):
    plt.annotate(
        label,
        xy=(x, y), xytext=(-20, 20),
        textcoords='offset points', ha='right', va='bottom',
        bbox=dict(boxstyle='round,pad=0.5', fc='yellow', alpha=0.5),
        arrowprops=dict(arrowstyle = '->', connectionstyle='arc3,rad=0'))

plt.show()

enter image description here

Remove DEFINER clause from MySQL Dumps

I don't think there is a way to ignore adding DEFINERs to the dump. But there are ways to remove them after the dump file is created.

  1. Open the dump file in a text editor and replace all occurrences of DEFINER=root@localhost with an empty string ""

  2. Edit the dump (or pipe the output) using perl:

    perl -p -i.bak -e "s/DEFINER=\`\w.*\`@\`\d[0-3].*[0-3]\`//g" mydatabase.sql
    
  3. Pipe the output through sed:

    mysqldump ... | sed -e 's/DEFINER[ ]*=[ ]*[^*]*\*/\*/' > triggers_backup.sql
    

ld.exe: cannot open output file ... : Permission denied

If you think the executable is locked by a process, try Process Explorer from SysInternals. In the File/handle, enter Fibonacci.exe and you should see who holds the file.

If it is not enough, you can use Process Monitor (from SysInternals, again) to follow the activity of all processes on your system on Fibonacci.exe. With a little bit of analysis (call stacks), you'll may find out why the access to the file is denied and what make it disappear.

Implementing a simple file download servlet

That depends. If said file is publicly available via your HTTP server or servlet container you can simply redirect to via response.sendRedirect().

If it's not, you'll need to manually copy it to response output stream:

OutputStream out = response.getOutputStream();
FileInputStream in = new FileInputStream(my_file);
byte[] buffer = new byte[4096];
int length;
while ((length = in.read(buffer)) > 0){
    out.write(buffer, 0, length);
}
in.close();
out.flush();

You'll need to handle the appropriate exceptions, of course.

Angular and Typescript: Can't find names - Error: cannot find name

I found this very helpful doc at Angular 2's website. It finally let me get things working properly, whereas the other answers here, to install typings, failed me with various errors. (But helped lead me in the right direction.)

Instead of including es6-promise and es6-collections, it includes core-js, which did the trick for me... no conflicts with Angular2's core ts definitions. Additionally the document explained how to set up all this to happen automatically when installing NPM, and how to modify your typings.json file.

Using Predicate in Swift

In swift 2.2

func filterContentForSearchText(searchText: String, scope: String) {
    var resultPredicate = NSPredicate(format: "name contains[c]         %@", searchText)
    searchResults = (recipes as NSArray).filteredArrayUsingPredicate(resultPredicate)
}

In swift 3.0

func filterContent(forSearchText searchText: String, scope: String) {
        var resultPredicate = NSPredicate(format: "name contains[c]         %@", searchText)
        searchResults = recipes.filtered(using: resultPredicate)
    }

XPath - Selecting elements that equal a value

The XPath spec. defines the string value of an element as the concatenation (in document order) of all of its text-node descendents.

This explains the "strange results".

"Better" results can be obtained using the expressions below:

//*[text() = 'qwerty']

The above selects every element in the document that has at least one text-node child with value 'qwerty'.

//*[text() = 'qwerty' and not(text()[2])]

The above selects every element in the document that has only one text-node child and its value is: 'qwerty'.

What is a Subclass

Think of a class as a description of the members of a set of things. All of the members of that set have common characteristics (methods and properties).

A subclass is a class that describes the members of a particular subset of the original set. They share many of characteristics of the main class, but may have properties or methods that are unique to members of the subclass.

You declare that one class is subclass of another via the "extends" keyword in Java.

public class B extends A
{
...
}

B is a subclass of A. Instances of class B will automatically exhibit many of the same properties as instances of class A.

This is the main concept of inheritance in Object-Oriented programming.

Java - Opposite of .contains (does not contain)

It seems that Luiggi Mendoza and joey rohan both already answered this, but I think it can be clarified a little.

You can write it as a single if statement:

if (inventory.contains("bread") && !inventory.contains("water")) {
    // do something
}

How to convert a number to string and vice versa in C++

Update for C++11

As of the C++11 standard, string-to-number conversion and vice-versa are built in into the standard library. All the following functions are present in <string> (as per paragraph 21.5).

string to numeric

float              stof(const string& str, size_t *idx = 0);
double             stod(const string& str, size_t *idx = 0);
long double        stold(const string& str, size_t *idx = 0);
int                stoi(const string& str, size_t *idx = 0, int base = 10);
long               stol(const string& str, size_t *idx = 0, int base = 10);
unsigned long      stoul(const string& str, size_t *idx = 0, int base = 10);
long long          stoll(const string& str, size_t *idx = 0, int base = 10);
unsigned long long stoull(const string& str, size_t *idx = 0, int base = 10);

Each of these take a string as input and will try to convert it to a number. If no valid number could be constructed, for example because there is no numeric data or the number is out-of-range for the type, an exception is thrown (std::invalid_argument or std::out_of_range).

If conversion succeeded and idx is not 0, idx will contain the index of the first character that was not used for decoding. This could be an index behind the last character.

Finally, the integral types allow to specify a base, for digits larger than 9, the alphabet is assumed (a=10 until z=35). You can find more information about the exact formatting that can parsed here for floating-point numbers, signed integers and unsigned integers.

Finally, for each function there is also an overload that accepts a std::wstring as it's first parameter.

numeric to string

string to_string(int val);
string to_string(unsigned val);
string to_string(long val);
string to_string(unsigned long val);
string to_string(long long val);
string to_string(unsigned long long val);
string to_string(float val);
string to_string(double val);
string to_string(long double val);

These are more straightforward, you pass the appropriate numeric type and you get a string back. For formatting options you should go back to the C++03 stringsream option and use stream manipulators, as explained in an other answer here.

As noted in the comments these functions fall back to a default mantissa precision that is likely not the maximum precision. If more precision is required for your application it's also best to go back to other string formatting procedures.

There are also similar functions defined that are named to_wstring, these will return a std::wstring.

Python 3 - ValueError: not enough values to unpack (expected 3, got 2)

In this line:

for name, email, lastname in unpaidMembers.items():

unpaidMembers.items() must have only two values per iteration.

Here is a small example to illustrate the problem:

This will work:

for alpha, beta, delta in [("first", "second", "third")]:
    print("alpha:", alpha, "beta:", beta, "delta:", delta)

This will fail, and is what your code does:

for alpha, beta, delta in [("first", "second")]:
    print("alpha:", alpha, "beta:", beta, "delta:", delta)

In this last example, what value in the list is assigned to delta? Nothing, There aren't enough values, and that is the problem.

How do you determine a processing time in Python?

For some further information on how to determine the processing time, and a comparison of a few methods (some mentioned already in the answers of this post) - specifically, the difference between:

start = time.time()

versus the now obsolete (as of 3.3, time.clock() is deprecated)

start = time.clock()

see this other article on Stackoverflow here:

Python - time.clock() vs. time.time() - accuracy?

If nothing else, this will work good:

start = time.time()

... do something

elapsed = (time.time() - start)

Specify JDK for Maven to use

Yet another alternative to manage multiple jdk versions is jEnv

After installation, you can simply change java version "locally" i.e. for a specific project directory by:

jenv local 1.6

This will also make mvn use that version locally, when you enable the mvn plugin:

jenv enable-plugin maven

Convert List to Pandas Dataframe Column

Example:

['Thanks You',
 'Its fine no problem',
 'Are you sure']

code block:

import pandas as pd
df = pd.DataFrame(lst)

Output:

    0
0   Thanks You
1   Its fine no problem
2   Are you sure

It is not recommended to remove the column names of the panda dataframe. but if you still want your data frame without header(as per the format you posted in the question) you can do this:

df = pd.DataFrame(lst)    
df.columns = ['']

Output will be like this:

0   Thanks You
1   Its fine no problem
2   Are you sure

or

df = pd.DataFrame(lst).to_string(header=False)

But the output will be a list instead of a dataframe:

0           Thanks You
1  Its fine no problem
2         Are you sure

Hope this helps!!

How to declare strings in C

char *p = "String";   means pointer to a string type variable.

char p3[5] = "String"; means you are pre-defining the size of the array to consist of no more than 5 elements. Note that,for strings the null "\0" is also considered as an element.So,this statement would give an error since the number of elements is 7 so it should be:

char p3[7]= "String";

Laravel orderBy on a relationship

It is possible to extend the relation with query functions:

<?php
public function comments()
{
    return $this->hasMany('Comment')->orderBy('column');
}

[edit after comment]

<?php
class User
{
    public function comments()
    {
        return $this->hasMany('Comment');
    }
}

class Controller
{
    public function index()
    {
        $column = Input::get('orderBy', 'defaultColumn');
        $comments = User::find(1)->comments()->orderBy($column)->get();

        // use $comments in the template
    }
}

default User model + simple Controller example; when getting the list of comments, just apply the orderBy() based on Input::get(). (be sure to do some input-checking ;) )

Generate a dummy-variable

Convert your data to a data.table and use set by reference and row filtering

library(data.table)

dt <- as.data.table(your.dataframe.or.whatever)
dt[, is.1957 := 0]
dt[year == 1957, is.1957 := 1]

Proof-of-concept toy example:

library(data.table)

dt <- as.data.table(cbind(c(1, 1, 1), c(2, 2, 3)))
dt[, is.3 := 0]
dt[V2 == 3, is.3 := 1]

Stretch and scale CSS background

Use the border-image : yourimage property to set your image and scale it upto the entire border of your screen or window .

Can I check if Bootstrap Modal Shown / Hidden?

All Bootstrap versions:

var isShown = $('.modal').hasClass('in') || $('.modal').hasClass('show')

To just close it independent of state and version:

$('.modal button.close').click()

more info

Bootstrap 3 and before

var isShown = $('.modal').hasClass('in')

Bootstrap 4

var isShown = $('.modal').hasClass('show')

Convert a Unicode string to a string in Python (containing extra symbols)

Here is an example:

>>> u = u'€€€'
>>> s = u.encode('utf8')
>>> s
'\xe2\x82\xac\xe2\x82\xac\xe2\x82\xac'

Hide "NFC Tag type not supported" error on Samsung Galaxy devices

Before Android 4.4

What you are trying to do is simply not possible from an app (at least not on a non-rooted/non-modified device). The message "NFC tag type not supported" is displayed by the Android system (or more specifically the NFC system service) before and instead of dispatching the tag to your app. This means that the NFC system service filters MIFARE Classic tags and never notifies any app about them. Consequently, your app can't detect MIFARE Classic tags or circumvent that popup message.

On a rooted device, you may be able to bypass the message using either

  1. Xposed to modify the behavior of the NFC service, or
  2. the CSC (Consumer Software Customization) feature configuration files on the system partition (see /system/csc/. The NFC system service disables the popup and dispatches MIFARE Classic tags to apps if the CSC feature <CscFeature_NFC_EnableSecurityPromptPopup> is set to any value but "mifareclassic" or "all". For instance, you could use:

    <CscFeature_NFC_EnableSecurityPromptPopup>NONE</CscFeature_NFC_EnableSecurityPromptPopup>
    

    You could add this entry to, for instance, the file "/system/csc/others.xml" (within the section <FeatureSet> ... </FeatureSet> that already exists in that file).

Since, you asked for the Galaxy S6 (the question that you linked) as well: I have tested this method on the S4 when it came out. I have not verified if this still works in the latest firmware or on other devices (e.g. the S6).

Since Android 4.4

This is pure guessing, but according to this (link no longer available), it seems that some apps (e.g. NXP TagInfo) are capable of detecting MIFARE Classic tags on affected Samsung devices since Android 4.4. This might mean that foreground apps are capable of bypassing that popup using the reader-mode API (see NfcAdapter.enableReaderMode) possibly in combination with NfcAdapter.FLAG_READER_SKIP_NDEF_CHECK.

How do I fix "Expected to return a value at the end of arrow function" warning?

A map() creates an array, so a return is expected for all code paths (if/elses).

If you don't want an array or to return data, use forEach instead.

When to use .First and when to use .FirstOrDefault with LINQ?

First of all, Take is a completely different method. It returns an IEnumerable<T> and not a single T, so that's out.

Between First and FirstOrDefault, you should use First when you're sure that an element exists and if it doesn't, then there's an error.

By the way, if your sequence contains default(T) elements (e.g. null) and you need to distinguish between being empty and the first element being null, you can't use FirstOrDefault.

Difference between RegisterStartupScript and RegisterClientScriptBlock?

Here's a simplest example from ASP.NET Community, this gave me a clear understanding on the concept....

what difference does this make?

For an example of this, here is a way to put focus on a text box on a page when the page is loaded into the browser—with Visual Basic using the RegisterStartupScript method:

Page.ClientScript.RegisterStartupScript(Me.GetType(), "Testing", _ 
"document.forms[0]['TextBox1'].focus();", True)

This works well because the textbox on the page is generated and placed on the page by the time the browser gets down to the bottom of the page and gets to this little bit of JavaScript.

But, if instead it was written like this (using the RegisterClientScriptBlock method):

Page.ClientScript.RegisterClientScriptBlock(Me.GetType(), "Testing", _
"document.forms[0]['TextBox1'].focus();", True)

Focus will not get to the textbox control and a JavaScript error will be generated on the page

The reason for this is that the browser will encounter the JavaScript before the text box is on the page. Therefore, the JavaScript will not be able to find a TextBox1.

How can I modify a saved Microsoft Access 2007 or 2010 Import Specification?

Why so complicated?

Just check System Objects in Access-Options/Current Database/Navigation Options/Show System Objects

Open Table "MSysIMEXSpecs" and change according to your needs - its easy to read...

Disable time in bootstrap date time picker

$('#datetimepicker').datetimepicker({ 
    minView: 2, 
    pickTime: false, 
    language: 'pt-BR' 
});

Please try if it works for you as well

How do I reverse a commit in git?

Or you can try using git revert http://www.kernel.org/pub/software/scm/git/docs/git-revert.html. I think something like git revert HEAD~1 -m 1 will revert your last commit (if it's still the last commit).

What's the difference between passing by reference vs. passing by value?

Here is an example:

#include <iostream>

void by_val(int arg) { arg += 2; }
void by_ref(int&arg) { arg += 2; }

int main()
{
    int x = 0;
    by_val(x); std::cout << x << std::endl;  // prints 0
    by_ref(x); std::cout << x << std::endl;  // prints 2

    int y = 0;
    by_ref(y); std::cout << y << std::endl;  // prints 2
    by_val(y); std::cout << y << std::endl;  // prints 2
}

change values in array when doing foreach

Javascript is pass by value, and which essentially means part is a copy of the value in the array.

To change the value, access the array itself in your loop.

arr[index] = 'new value';

Insert using LEFT JOIN and INNER JOIN

you can't use VALUES clause when inserting data using another SELECT query. see INSERT SYNTAX

INSERT INTO user
(
 id, name, username, email, opted_in
)
(
    SELECT id, name, username, email, opted_in
    FROM user
         LEFT JOIN user_permission AS userPerm
            ON user.id = userPerm.user_id
);

AngularJS : How to watch service variables?

I stumbled upon this question looking for something similar, but I think it deserves a thorough explanation of what's going on, as well as some additional solutions.

When an angular expression such as the one you used is present in the HTML, Angular automatically sets up a $watch for $scope.foo, and will update the HTML whenever $scope.foo changes.

<div ng-controller="FooCtrl">
  <div ng-repeat="item in foo">{{ item }}</div>
</div>

The unsaid issue here is that one of two things are affecting aService.foo such that the changes are undetected. These two possibilities are:

  1. aService.foo is getting set to a new array each time, causing the reference to it to be outdated.
  2. aService.foo is being updated in such a way that a $digest cycle is not triggered on the update.

Problem 1: Outdated References

Considering the first possibility, assuming a $digest is being applied, if aService.foo was always the same array, the automatically set $watch would detect the changes, as shown in the code snippet below.

Solution 1-a: Make sure the array or object is the same object on each update

_x000D_
_x000D_
angular.module('myApp', [])_x000D_
  .factory('aService', [_x000D_
    '$interval',_x000D_
    function($interval) {_x000D_
      var service = {_x000D_
        foo: []_x000D_
      };_x000D_
_x000D_
      // Create a new array on each update, appending the previous items and _x000D_
      // adding one new item each time_x000D_
      $interval(function() {_x000D_
        if (service.foo.length < 10) {_x000D_
          var newArray = []_x000D_
          Array.prototype.push.apply(newArray, service.foo);_x000D_
          newArray.push(Math.random());_x000D_
          service.foo = newArray;_x000D_
        }_x000D_
      }, 1000);_x000D_
_x000D_
      return service;_x000D_
    }_x000D_
  ])_x000D_
  .factory('aService2', [_x000D_
    '$interval',_x000D_
    function($interval) {_x000D_
      var service = {_x000D_
        foo: []_x000D_
      };_x000D_
_x000D_
      // Keep the same array, just add new items on each update_x000D_
      $interval(function() {_x000D_
        if (service.foo.length < 10) {_x000D_
          service.foo.push(Math.random());_x000D_
        }_x000D_
      }, 1000);_x000D_
_x000D_
      return service;_x000D_
    }_x000D_
  ])_x000D_
  .controller('FooCtrl', [_x000D_
    '$scope',_x000D_
    'aService',_x000D_
    'aService2',_x000D_
    function FooCtrl($scope, aService, aService2) {_x000D_
      $scope.foo = aService.foo;_x000D_
      $scope.foo2 = aService2.foo;_x000D_
    }_x000D_
  ]);
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
_x000D_
<head>_x000D_
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>_x000D_
  <link rel="stylesheet" href="style.css" />_x000D_
  <script src="script.js"></script>_x000D_
</head>_x000D_
_x000D_
<body ng-app="myApp">_x000D_
  <div ng-controller="FooCtrl">_x000D_
    <h1>Array changes on each update</h1>_x000D_
    <div ng-repeat="item in foo">{{ item }}</div>_x000D_
    <h1>Array is the same on each udpate</h1>_x000D_
    <div ng-repeat="item in foo2">{{ item }}</div>_x000D_
  </div>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_

As you can see, the ng-repeat supposedly attached to aService.foo does not update when aService.foo changes, but the ng-repeat attached to aService2.foo does. This is because our reference to aService.foo is outdated, but our reference to aService2.foo is not. We created a reference to the initial array with $scope.foo = aService.foo;, which was then discarded by the service on it's next update, meaning $scope.foo no longer referenced the array we wanted anymore.

However, while there are several ways to make sure the initial reference is kept in tact, sometimes it may be necessary to change the object or array. Or what if the service property references a primitive like a String or Number? In those cases, we cannot simply rely on a reference. So what can we do?

Several of the answers given previously already give some solutions to that problem. However, I am personally in favor of using the simple method suggested by Jin and thetallweeks in the comments:

just reference aService.foo in the html markup

Solution 1-b: Attach the service to the scope, and reference {service}.{property} in the HTML.

Meaning, just do this:

HTML:

<div ng-controller="FooCtrl">
  <div ng-repeat="item in aService.foo">{{ item }}</div>
</div>

JS:

function FooCtrl($scope, aService) {
    $scope.aService = aService;
}

_x000D_
_x000D_
angular.module('myApp', [])_x000D_
  .factory('aService', [_x000D_
    '$interval',_x000D_
    function($interval) {_x000D_
      var service = {_x000D_
        foo: []_x000D_
      };_x000D_
_x000D_
      // Create a new array on each update, appending the previous items and _x000D_
      // adding one new item each time_x000D_
      $interval(function() {_x000D_
        if (service.foo.length < 10) {_x000D_
          var newArray = []_x000D_
          Array.prototype.push.apply(newArray, service.foo);_x000D_
          newArray.push(Math.random());_x000D_
          service.foo = newArray;_x000D_
        }_x000D_
      }, 1000);_x000D_
_x000D_
      return service;_x000D_
    }_x000D_
  ])_x000D_
  .controller('FooCtrl', [_x000D_
    '$scope',_x000D_
    'aService',_x000D_
    function FooCtrl($scope, aService) {_x000D_
      $scope.aService = aService;_x000D_
    }_x000D_
  ]);
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
_x000D_
<head>_x000D_
  <script data-require="[email protected]" data-semver="1.4.7" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular.js"></script>_x000D_
  <link rel="stylesheet" href="style.css" />_x000D_
  <script src="script.js"></script>_x000D_
</head>_x000D_
_x000D_
<body ng-app="myApp">_x000D_
  <div ng-controller="FooCtrl">_x000D_
    <h1>Array changes on each update</h1>_x000D_
    <div ng-repeat="item in aService.foo">{{ item }}</div>_x000D_
  </div>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_

That way, the $watch will resolve aService.foo on each $digest, which will get the correctly updated value.

This is kind of what you were trying to do with your workaround, but in a much less round about way. You added an unnecessary $watch in the controller which explicitly puts foo on the $scope whenever it changes. You don't need that extra $watch when you attach aService instead of aService.foo to the $scope, and bind explicitly to aService.foo in the markup.


Now that's all well and good assuming a $digest cycle is being applied. In my examples above, I used Angular's $interval service to update the arrays, which automatically kicks off a $digest loop after each update. But what if the service variables (for whatever reason) aren't getting updated inside the "Angular world". In other words, we dont have a $digest cycle being activated automatically whenever the service property changes?


Problem 2: Missing $digest

Many of the solutions here will solve this issue, but I agree with Code Whisperer:

The reason why we're using a framework like Angular is to not cook up our own observer patterns

Therefore, I would prefer to continue to use the aService.foo reference in the HTML markup as shown in the second example above, and not have to register an additional callback within the Controller.

Solution 2: Use a setter and getter with $rootScope.$apply()

I was surprised no one has yet suggested the use of a setter and getter. This capability was introduced in ECMAScript5, and has thus been around for years now. Of course, that means if, for whatever reason, you need to support really old browsers, then this method will not work, but I feel like getters and setters are vastly underused in JavaScript. In this particular case, they could be quite useful:

factory('aService', [
  '$rootScope',
  function($rootScope) {
    var realFoo = [];

    var service = {
      set foo(a) {
        realFoo = a;
        $rootScope.$apply();
      },
      get foo() {
        return realFoo;
      }
    };
  // ...
}

_x000D_
_x000D_
angular.module('myApp', [])_x000D_
  .factory('aService', [_x000D_
    '$rootScope',_x000D_
    function($rootScope) {_x000D_
      var realFoo = [];_x000D_
_x000D_
      var service = {_x000D_
        set foo(a) {_x000D_
          realFoo = a;_x000D_
          $rootScope.$apply();_x000D_
        },_x000D_
        get foo() {_x000D_
          return realFoo;_x000D_
        }_x000D_
      };_x000D_
_x000D_
      // Create a new array on each update, appending the previous items and _x000D_
      // adding one new item each time_x000D_
      setInterval(function() {_x000D_
        if (service.foo.length < 10) {_x000D_
          var newArray = [];_x000D_
          Array.prototype.push.apply(newArray, service.foo);_x000D_
          newArray.push(Math.random());_x000D_
          service.foo = newArray;_x000D_
        }_x000D_
      }, 1000);_x000D_
_x000D_
      return service;_x000D_
    }_x000D_
  ])_x000D_
  .controller('FooCtrl', [_x000D_
    '$scope',_x000D_
    'aService',_x000D_
    function FooCtrl($scope, aService) {_x000D_
      $scope.aService = aService;_x000D_
    }_x000D_
  ]);
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
_x000D_
<head>_x000D_
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>_x000D_
  <link rel="stylesheet" href="style.css" />_x000D_
  <script src="script.js"></script>_x000D_
</head>_x000D_
_x000D_
<body ng-app="myApp">_x000D_
  <div ng-controller="FooCtrl">_x000D_
    <h1>Using a Getter/Setter</h1>_x000D_
    <div ng-repeat="item in aService.foo">{{ item }}</div>_x000D_
  </div>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_

Here I added a 'private' variable in the service function: realFoo. This get's updated and retrieved using the get foo() and set foo() functions respectively on the service object.

Note the use of $rootScope.$apply() in the set function. This ensures that Angular will be aware of any changes to service.foo. If you get 'inprog' errors see this useful reference page, or if you use Angular >= 1.3 you can just use $rootScope.$applyAsync().

Also be wary of this if aService.foo is being updated very frequently, since that could significantly impact performance. If performance would be an issue, you could set up an observer pattern similar to the other answers here using the setter.

How to connect to Oracle 11g database remotely

First, make sure the listener on database server (computer A) that receives client connection requests is running. To do so, run lsnrctl status command.

In case, if you get TNS:no listener message (see below image), it means listener service is not running. To start it, run lsnrctl start command.

enter image description here

Second, for database operations and connectivity from remote clients, the following executables must be added to the Windows Firewall exception list: (see image)

Oracle_home\bin\oracle.exe - Oracle Database executable

Oracle_home\bin\tnslsnr.exe - Oracle Listener

enter image description here

Finally, install oracle instant client on client machine (computer B) and run:

sqlplus user/password@computerA:port/XE

Access blocked by CORS policy: Response to preflight request doesn't pass access control check

You can just create the required CORS configuration as a bean. As per the code below this will allow all requests coming from any origin. This is good for development but insecure. Spring Docs

@Bean
WebMvcConfigurer corsConfigurer() {
    return new WebMvcConfigurer() {
        @Override
        void addCorsMappings(CorsRegistry registry) {
            registry.addMapping("/**")
                    .allowedOrigins("*")
        }
    }
}

Return multiple values to a method caller

In C# 4, you will be able to use built-in support for tuples to handle this easily.

In the meantime, there are two options.

First, you can use ref or out parameters to assign values to your parameters, which get passed back to the calling routine.

This looks like:

void myFunction(ref int setMe, out int youMustSetMe);

Second, you can wrap up your return values into a structure or class, and pass them back as members of that structure. KeyValuePair works well for 2 - for more than 2 you would need a custom class or struct.

Storing and retrieving datatable from session

A simple solution for a very common problem

                 // DECLARATION
                HttpContext context = HttpContext.Current;
                DataTable dt_ShoppingBasket = context.Session["Shopping_Basket"] as DataTable;

                // TRY TO ADD rows with the info into the DataTable
                try
                {
                    // Add new Serial Code into DataTable dt_ShoppingBasket
                    dt_ShoppingBasket.Rows.Add(new_SerialCode.ToString());

                    // Assigns new DataTable to Session["Shopping_Basket"]
                    context.Session["Shopping_Basket"] = dt_ShoppingBasket;
                }
                catch (Exception)
                {
                    // IF FAIL (EMPTY OR DOESN'T EXIST) - 
                    // Create new Instance, 
                    DataTable dt_ShoppingBasket= new DataTable();

                    // Add column and Row with the info
                    dt_ShoppingBasket.Columns.Add("Serial");
                    dt_ShoppingBasket.Rows.Add(new_SerialCode.ToString());

                    // Assigns new DataTable to Session["Shopping_Basket"]
                    context.Session["Shopping_Basket"] = dt_PanierCommande;
                }



                // PRINT TESTS
                DataTable dt_To_Print = context.Session["Shopping_Basket"] as DataTable;

                foreach (DataRow row in dt_To_Print.Rows)
                {
                    foreach (var item in row.ItemArray)
                    {
                        Debug.WriteLine("DATATABLE IN SESSION: " + item);
                    }
                }

Difference between const reference and normal parameter

Firstly, there is no concept of cv-qualified references. So the terminology 'const reference' is not correct and is usually used to describle 'reference to const'. It is better to start talking about what is meant.

$8.3.2/1- "Cv-qualified references are ill-formed except when the cv-qualifiers are introduced through the use of a typedef (7.1.3) or of a template type argument (14.3), in which case the cv-qualifiers are ignored."

Here are the differences

$13.1 - "Only the const and volatile type-specifiers at the outermost level of the parameter type specification are ignored in this fashion; const and volatile type-specifiers buried within a parameter type specification are significant and can be used to distinguish overloaded function declarations.112). In particular, for any type T, “pointer to T,” “pointer to const T,” and “pointer to volatile T” are considered distinct parameter types, as are “reference to T,” “reference to const T,” and “reference to volatile T.”

void f(int &n){
   cout << 1; 
   n++;
}

void f(int const &n){
   cout << 2;
   //n++; // Error!, Non modifiable lvalue
}

int main(){
   int x = 2;

   f(x);        // Calls overload 1, after the call x is 3
   f(2);        // Calls overload 2
   f(2.2);      // Calls overload 2, a temporary of double is created $8.5/3
}

'NoneType' object is not subscriptable?

The indexing e.g. [0] should occour inside of the print...

Pro JavaScript programmer interview questions (with answers)

Basic JS programmming

  • Scope of variable
  • What is Associative Array? How do we use it?

OOPS JS

  • Difference between Classic Inheritance and Prototypical Inheritance
  • What is difference between private variable, public variable and static variable? How we achieve this in JS?
  • How to add/remove properties to object in run time?
  • How to achieve inheritance ?
  • How to extend built-in objects?
  • Why extending array is bad idea?

DOM and JS

  • Difference between browser detection and feature detection
  • DOM Event Propagation
  • Event Delegation
  • Event bubbling V/s Event Capturing

Misc

  • Graceful Degradation V/s Progressive Enhancement

Intersect Two Lists in C#

public static List<T> ListCompare<T>(List<T> List1 , List<T> List2 , string key )
{
    return List1.Select(t => t.GetType().GetProperty(key).GetValue(t))
                .Intersect(List2.Select(t => t.GetType().GetProperty(key).GetValue(t))).ToList();
}

What does this mean? "Parse error: syntax error, unexpected T_PAAMAYIM_NEKUDOTAYIM"

In your example

return $cnf::getConfig($key)

Probably should be:

return $cnf->getConfig($key)

And make getConfig not static

How to find all occurrences of a substring?

When looking for a large amount of key words in a document, use flashtext

from flashtext import KeywordProcessor
words = ['test', 'exam', 'quiz']
txt = 'this is a test'
kwp = KeywordProcessor()
kwp.add_keywords_from_list(words)
result = kwp.extract_keywords(txt, span_info=True)

Flashtext runs faster than regex on large list of search words.

Create a .csv file with values from a Python list

The best option I've found was using the savetxt from the numpy module:

import numpy as np
np.savetxt("file_name.csv", data1, delimiter=",", fmt='%s', header=header)

In case you have multiple lists that need to be stacked

np.savetxt("file_name.csv", np.column_stack((data1, data2)), delimiter=",", fmt='%s', header=header)

Can not deserialize instance of java.lang.String out of START_OBJECT token

Resolved the problem using Jackson library. Prints are called out of Main class and all POJO classes are created. Here is the code snippets.

MainClass.java

public class MainClass {
  public static void main(String[] args) throws JsonParseException, 
       JsonMappingException, IOException {

String jsonStr = "{\r\n" + "    \"id\": 2,\r\n" + " \"socket\": \"0c317829-69bf- 
             43d6-b598-7c0c550635bb\",\r\n"
            + " \"type\": \"getDashboard\",\r\n" + "    \"data\": {\r\n"
            + "     \"workstationUuid\": \"ddec1caa-a97f-4922-833f- 
            632da07ffc11\"\r\n" + " },\r\n"
            + " \"reply\": true\r\n" + "}";

    ObjectMapper mapper = new ObjectMapper();

    MyPojo details = mapper.readValue(jsonStr, MyPojo.class);

    System.out.println("Value for getFirstName is: " + details.getId());
    System.out.println("Value for getLastName  is: " + details.getSocket());
    System.out.println("Value for getChildren is: " + 
      details.getData().getWorkstationUuid());
    System.out.println("Value for getChildren is: " + details.getReply());

}

MyPojo.java

public class MyPojo {
    private String id;

    private Data data;

    private String reply;

    private String socket;

    private String type;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public Data getData() {
        return data;
    }

    public void setData(Data data) {
        this.data = data;
    }

    public String getReply() {
        return reply;
    }

    public void setReply(String reply) {
        this.reply = reply;
    }

    public String getSocket() {
        return socket;
    }

    public void setSocket(String socket) {
        this.socket = socket;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    } 
}

Data.java

public class Data {
    private String workstationUuid;

    public String getWorkstationUuid() {
        return workstationUuid;
    }

    public void setWorkstationUuid(String workstationUuid) {
        this.workstationUuid = workstationUuid;
    }   
}

RESULTS:

Value for getFirstName is: 2
Value for getLastName  is: 0c317829-69bf-43d6-b598-7c0c550635bb
Value for getChildren is: ddec1caa-a97f-4922-833f-632da07ffc11
Value for getChildren is: true

How to remove leading and trailing whitespace in a MySQL field?

A general answer that I composed from your answers and from other links and it worked for me and I wrote it in a comment is:

 UPDATE FOO set FIELD2 = TRIM(Replace(Replace(Replace(FIELD2,'\t',''),'\n',''),'\r',''));

etc.

Because trim() doesn't remove all the white spaces so it's better to replace all the white spaces u want and than trim it.

Hope I could help you with sharing my answer :)

When to choose mouseover() and hover() function?

From the official jQuery documentation

  • .mouseover()
    Bind an event handler to the "mouseover" JavaScript event, or trigger that event on an element.

  • .hover() Bind one or two handlers to the matched elements, to be executed when the mouse pointer enters and leaves the elements.

    Calling $(selector).hover(handlerIn, handlerOut) is shorthand for: $(selector).mouseenter(handlerIn).mouseleave(handlerOut);


  • .mouseenter()

    Bind an event handler to be fired when the mouse enters an element, or trigger that handler on an element.

    mouseover fires when the pointer moves into the child element as well, while mouseenter fires only when the pointer moves into the bound element.


What this means

Because of this, .mouseover() is not the same as .hover(), for the same reason .mouseover() is not the same as .mouseenter().

$('selector').mouseover(over_function) // may fire multiple times

// enter and exit functions only called once per element per entry and exit
$('selector').hover(enter_function, exit_function) 

Two-way SSL clarification

Both certificates should exist prior to the connection. They're usually created by Certification Authorities (not necessarily the same). (There are alternative cases where verification can be done differently, but some verification will need to be made.)

The server certificate should be created by a CA that the client trusts (and following the naming conventions defined in RFC 6125).

The client certificate should be created by a CA that the server trusts.

It's up to each party to choose what it trusts.

There are online CA tools that will allow you to apply for a certificate within your browser and get it installed there once the CA has issued it. They need not be on the server that requests client-certificate authentication.

The certificate distribution and trust management is the role of the Public Key Infrastructure (PKI), implemented via the CAs. The SSL/TLS client and servers and then merely users of that PKI.

When the client connects to a server that requests client-certificate authentication, the server sends a list of CAs it's willing to accept as part of the client-certificate request. The client is then able to send its client certificate, if it wishes to and a suitable one is available.

The main advantages of client-certificate authentication are:

  • The private information (the private key) is never sent to the server. The client doesn't let its secret out at all during the authentication.
  • A server that doesn't know a user with that certificate can still authenticate that user, provided it trusts the CA that issued the certificate (and that the certificate is valid). This is very similar to the way passports are used: you may have never met a person showing you a passport, but because you trust the issuing authority, you're able to link the identity to the person.

You may be interested in Advantages of client certificates for client authentication? (on Security.SE).

Best way to increase heap size in catalina.bat file

If you look in your installation's bin directory you will see catalina.sh or .bat scripts. If you look in these you will see that they run a setenv.sh or setenv.bat script respectively, if it exists, to set environment variables. The relevant environment variables are described in the comments at the top of catalina.sh/bat. To use them create, for example, a file $CATALINA_HOME/bin/setenv.sh with contents

export JAVA_OPTS="-server -Xmx512m"

For Windows you will need, in setenv.bat, something like

set JAVA_OPTS=-server -Xmx768m

Original answer here

After you run startup.bat, you can easily confirm the correct settings have been applied provided you have turned @echo on somewhere in your catatlina.bat file (a good place could be immediately after echo Using CLASSPATH: "%CLASSPATH%"):

enter image description here

Why do we use volatile keyword?

Consider this code,

int some_int = 100;

while(some_int == 100)
{
   //your code
}

When this program gets compiled, the compiler may optimize this code, if it finds that the program never ever makes any attempt to change the value of some_int, so it may be tempted to optimize the while loop by changing it from while(some_int == 100) to something which is equivalent to while(true) so that the execution could be fast (since the condition in while loop appears to be true always). (if the compiler doesn't optimize it, then it has to fetch the value of some_int and compare it with 100, in each iteration which obviously is a little bit slow.)

However, sometimes, optimization (of some parts of your program) may be undesirable, because it may be that someone else is changing the value of some_int from outside the program which compiler is not aware of, since it can't see it; but it's how you've designed it. In that case, compiler's optimization would not produce the desired result!

So, to ensure the desired result, you need to somehow stop the compiler from optimizing the while loop. That is where the volatile keyword plays its role. All you need to do is this,

volatile int some_int = 100; //note the 'volatile' qualifier now!

In other words, I would explain this as follows:

volatile tells the compiler that,

"Hey compiler, I'm volatile and, you know, I can be changed by some XYZ that you're not even aware of. That XYZ could be anything. Maybe some alien outside this planet called program. Maybe some lightning, some form of interrupt, volcanoes, etc can mutate me. Maybe. You never know who is going to change me! So O you ignorant, stop playing an all-knowing god, and don't dare touch the code where I'm present. Okay?"

Well, that is how volatile prevents the compiler from optimizing code. Now search the web to see some sample examples.


Quoting from the C++ Standard ($7.1.5.1/8)

[..] volatile is a hint to the implementation to avoid aggressive optimization involving the object because the value of the object might be changed by means undetectable by an implementation.[...]

Related topic:

Does making a struct volatile make all its members volatile?

How to get week numbers from dates?

if you try with lubridate:

library(lubridate)
lubridate::week(ymd("2014-03-16", "2014-03-17","2014-03-18", '2014-01-01'))

[1] 11 11 12  1

The pattern is the same. Try isoweek

lubridate::isoweek(ymd("2014-03-16", "2014-03-17","2014-03-18", '2014-01-01'))
[1] 11 12 12  1

Laravel PDOException SQLSTATE[HY000] [1049] Unknown database 'forge'

My APP_NAME variables in .env.example and .env and app.php were with space e.g. The App . Surounding that by ' and php artisan cache:clear and setting new generated app key to APP_KEY variable through env files and relaunching the server by php artisan serve solved this issue

how to run a winform from console application?

All the above answers are great help, but I thought to add some more tips for the absolute beginner.

So, you want to do something with Windows Forms, in a Console Application:

Add a reference to System.Windows.Forms.dll in your Console application project in Solution Explorer. (Right Click on Solution-name->add->Reference...)

Specify the name space in code: using System.Windows.Forms;

Declare the needed properties in your class for the controls you wish to add to the form.

e.g. int Left { get; set; } // need to specify the LEFT position of the button on the Form

And then add the following code snippet in Main():

static void Main(string[] args)
{
Application.EnableVisualStyles();
        Form frm = new Form();  // create aForm object

        Button btn = new Button()
        {
            Left = 120,
            Width = 130,
            Height = 30,
            Top = 150,
            Text = "Biju Joseph, Redmond, WA"
        };
       //… more code 
       frm.Controls.Add(btn);  // add button to the Form
       //  …. add more code here as needed

       frm.ShowDialog(); // a modal dialog 
}

Recommended add-ons/plugins for Microsoft Visual Studio

I'm always amazed that more people don't know about/use NDepend - it shows all dependencies at every level of your code, and will even draw pretty box and arrow pictures showing how confused your architecture really is :) Together with TestDriven.Net, I can't imagine working without it any more. Free/cheap.

How do I combine the first character of a cell with another cell in Excel?

QUESTION was: suppose T john is to be converted john T, how to change in excel?

If text "T john" is in cell A1

=CONCATENATE(RIGHT(A1,LEN(A1)-2)," ",LEFT(A1,1))

and with a nod to the & crowd

=RIGHT(A1,LEN(A1)-2)&" "&LEFT(A1,1)

takes the right part of the string excluding the first 2 characters, adds a space, adds the first character.

CSS :not(:last-child):after selector

An example using CSS

  ul li:not(:last-child){
        border-right: 1px solid rgba(153, 151, 151, 0.75);
    }

Excel VBA Macro: User Defined Type Not Defined

Sub DeleteEmptyRows()  

    Worksheets("YourSheetName").Activate
    On Error Resume Next
    Columns("A").SpecialCells(xlCellTypeBlanks).EntireRow.Delete

End Sub

The following code will delete all rows on a sheet(YourSheetName) where the content of Column A is blank.

EDIT: User Defined Type Not Defined is caused by "oTable As Table" and "oRow As Row". Replace Table and Row with Object to resolve the error and make it compile.

Interface type check with Typescript

Based on Fenton's answer, here's my implementation of a function to verify if a given object has the keys an interface has, both fully or partially.

Depending on your use case, you may also need to check the types of each of the interface's properties. The code below doesn't do that.

function implementsTKeys<T>(obj: any, keys: (keyof T)[]): obj is T {
    if (!obj || !Array.isArray(keys)) {
        return false;
    }

    const implementKeys = keys.reduce((impl, key) => impl && key in obj, true);

    return implementKeys;
}

Example of usage:

interface A {
    propOfA: string;
    methodOfA: Function;
}

let objectA: any = { propOfA: '' };

// Check if objectA partially implements A
let implementsA = implementsTKeys<A>(objectA, ['propOfA']);

console.log(implementsA); // true

objectA.methodOfA = () => true;

// Check if objectA fully implements A
implementsA = implementsTKeys<A>(objectA, ['propOfA', 'methodOfA']);

console.log(implementsA); // true

objectA = {};

// Check again if objectA fully implements A
implementsA = implementsTKeys<A>(objectA, ['propOfA', 'methodOfA']);

console.log(implementsA); // false, as objectA now is an empty object

How to get an element by its href in jquery?

Yes, you can use jQuery's attribute selector for that.

var linksToGoogle = $('a[href="http://google.com"]');

Alternatively, if your interest is rather links starting with a certain URL, use the attribute-starts-with selector:

var allLinksToGoogle = $('a[href^="http://google.com"]');

Change Orientation of Bluestack : portrait/landscape mode

Here are the step:

  1. Install the Nova theme in bluestack
  2. go into Nova setting -> look and feel -> screen orientation -> Force Portrait -> go to Home screen

You are done! :)

How to use ESLint with Jest

To complete Zachary's answer, here is a workaround for the "extend in overrides" limitation of eslint config :

overrides: [
  Object.assign(
    {
      files: [ '**/*.test.js' ],
      env: { jest: true },
      plugins: [ 'jest' ],
    },
    require('eslint-plugin-jest').configs.recommended
  )
]

From https://github.com/eslint/eslint/issues/8813#issuecomment-320448724

addClass - can add multiple classes on same div?

You can add multiple classes by separating classes names by spaces

$('.page-address-edit').addClass('test1 test2 test3');

Plugin org.apache.maven.plugins:maven-compiler-plugin or one of its dependencies could not be resolved

I accidentally turned on offline mode.

To disable it: in the Maven tool window, click The Toggle Offline Mode button.

enter image description here