Programs & Examples On #Event queue

Simple If/Else Razor Syntax

A little bit off topic maybe, but for modern browsers (IE9 and newer) you can use the css odd/even selectors to achieve want you want.

tr:nth-child(even) { /* your alt-row stuff */}
tr:nth-child(odd) { /* the other rows */ }

or

tr { /* all table rows */ }
tr:nth-child(even) { /* your alt-row stuff */}

How do I load an org.w3c.dom.Document from XML in a string?

Just had a similar problem, except i needed a NodeList and not a Document, here's what I came up with. It's mostly the same solution as before, augmented to get the root element down as a NodeList and using erickson's suggestion of using an InputSource instead for character encoding issues.

private String DOC_ROOT="root";
String xml=getXmlString();
Document xmlDoc=loadXMLFrom(xml);
Element template=xmlDoc.getDocumentElement();
NodeList nodes=xmlDoc.getElementsByTagName(DOC_ROOT);

public static Document loadXMLFrom(String xml) throws Exception {
        InputSource is= new InputSource(new StringReader(xml));
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setNamespaceAware(true);
        DocumentBuilder builder = null;
        builder = factory.newDocumentBuilder();
        Document doc = builder.parse(is);
        return doc;
    }

How to convert array into comma separated string in javascript

You can simply use JavaScripts join() function for that. This would simply look like a.value.join(','). The output would be a string though.

Docker-compose: node_modules not present in a volume after npm install succeeds

If you want the node_modules folder available to the host during development, you could install the dependencies when you start the container instead of during build-time. I do this to get syntax highlighting working in my editor.

Dockerfile

# We're using a multi-stage build so that we can install dependencies during build-time only for production.

# dev-stage
FROM node:14-alpine AS dev-stage
WORKDIR /usr/src/app
COPY package.json ./
COPY . .
# `yarn install` will run every time we start the container. We're using yarn because it's much faster than npm when there's nothing new to install
CMD ["sh", "-c", "yarn install && yarn run start"]

# production-stage
FROM node:14-alpine AS production-stage
WORKDIR /usr/src/app
COPY package.json ./
RUN yarn install
COPY . .

.dockerignore

Add node_modules to .dockerignore to prevent it from being copied when the Dockerfile runs COPY . .. We use volumes to bring in node_modules.

**/node_modules

docker-compose.yml

node_app:
    container_name: node_app
    build:
        context: ./node_app
        target: dev-stage # `production-stage` for production
    volumes:
        # For development:
        #   If node_modules already exists on the host, they will be copied
        #   into the container here. Since `yarn install` runs after the
        #   container starts, this volume won't override the node_modules.
        - ./node_app:/usr/src/app
        # For production:
        #   
        - ./node_app:/usr/src/app
        - /usr/src/app/node_modules

push_back vs emplace_back

One more example for lists:

// constructs the elements in place.                                                
emplace_back("element");

// creates a new object and then copies (or moves) that object.
push_back(ExplicitDataType{"element"});

Access-Control-Allow-Origin wildcard subdomains, ports and protocols

in my case using angular

in my HTTP interceptor , i set

with Credentials: true.

in the header of the request

JQuery style display value

Well, for one thing your epression can be simplified:

$("#pDetails").attr("style")

since there should only be one element for any given ID and the ID selector will be much faster than the attribute id selector you're using.

If you just want to return the display value or something, use css():

$("#pDetails").css("display")

If you want to search for elements that have display none, that's a lot harder to do reliably. This is a rough example that won't be 100%:

$("[style*='display: none']")

but if you just want to find things that are hidden, use this:

$(":hidden")

SQL Server insert if not exists best practice

You will need to join the tables together and get a list of unique competitors that don't already exist in Competitors.

This will insert unique records.

INSERT Competitors (cName) 
SELECT DISTINCT Name
FROM CompResults cr LEFT JOIN Competitors c ON cr.Name = c.cName
WHERE c.Name IS NULL

There may come a time when this insert needs to be done quickly without being able to wait for the selection of unique names. In that case, you could insert the unique names into a temporary table, and then use that temporary table to insert into your real table. This works well because all the processing happens at the time you are inserting into a temporary table, so it doesn't affect your real table. Then when you have all the processing finished, you do a quick insert into the real table. I might even wrap the last part, where you insert into the real table, inside a transaction.

Echo off but messages are displayed

@echo off
// quote the path or else it won't work if there are spaces in the path
SET INSTALL_PATH="c:\\etc etc\\test";
if exist %INSTALL_PATH% (
   //
   echo 222;
)

Python how to plot graph sine wave

import matplotlib.pyplot as plt # For ploting
import numpy as np # to work with numerical data efficiently

fs = 100 # sample rate 
f = 2 # the frequency of the signal

x = np.arange(fs) # the points on the x axis for plotting
# compute the value (amplitude) of the sin wave at the for each sample
y = np.sin(2*np.pi*f * (x/fs)) 

#this instruction can only be used with IPython Notbook. 
% matplotlib inline
# showing the exact location of the smaples
plt.stem(x,y, 'r', )
plt.plot(x,y)

enter image description here

Jquery checking success of ajax post

This style is also possible:

$.get("mypage.html")
    .done(function(result){
        alert("done. read "+result.length+" characters.");
    })
    .fail(function(jqXHR, textStatus, errorThrown){
        alert("fail. status: "+textStatus);
    })

Change Placeholder Text using jQuery

change placeholder text using jquery

try this

$('#selector').attr("placeholder", "Type placeholder");

SyntaxError: expected expression, got '<'

This problem occurs when your are including file with wrong path and server gives some 404 error in loading file.

Change an image with onclick()

You can try something like this:

CSS

div {
    width:200px;
    height:200px;
    background: url(img1.png) center center no-repeat;
}

.visited {
    background: url(img2.png) center center no-repeat;
}

HTML

<div href="#" onclick="this.className='visited'">
    <p>Content</p>
</div>

Fiddle

What is the best algorithm for overriding GetHashCode?

I usually go with something like the implementation given in Josh Bloch's fabulous Effective Java. It's fast and creates a pretty good hash which is unlikely to cause collisions. Pick two different prime numbers, e.g. 17 and 23, and do:

public override int GetHashCode()
{
    unchecked // Overflow is fine, just wrap
    {
        int hash = 17;
        // Suitable nullity checks etc, of course :)
        hash = hash * 23 + field1.GetHashCode();
        hash = hash * 23 + field2.GetHashCode();
        hash = hash * 23 + field3.GetHashCode();
        return hash;
    }
}

As noted in comments, you may find it's better to pick a large prime to multiply by instead. Apparently 486187739 is good... and although most examples I've seen with small numbers tend to use primes, there are at least similar algorithms where non-prime numbers are often used. In the not-quite-FNV example later, for example, I've used numbers which apparently work well - but the initial value isn't a prime. (The multiplication constant is prime though. I don't know quite how important that is.)

This is better than the common practice of XORing hashcodes for two main reasons. Suppose we have a type with two int fields:

XorHash(x, x) == XorHash(y, y) == 0 for all x, y
XorHash(x, y) == XorHash(y, x) for all x, y

By the way, the earlier algorithm is the one currently used by the C# compiler for anonymous types.

This page gives quite a few options. I think for most cases the above is "good enough" and it's incredibly easy to remember and get right. The FNV alternative is similarly simple, but uses different constants and XOR instead of ADD as a combining operation. It looks something like the code below, but the normal FNV algorithm operates on individual bytes, so this would require modifying to perform one iteration per byte, instead of per 32-bit hash value. FNV is also designed for variable lengths of data, whereas the way we're using it here is always for the same number of field values. Comments on this answer suggest that the code here doesn't actually work as well (in the sample case tested) as the addition approach above.

// Note: Not quite FNV!
public override int GetHashCode()
{
    unchecked // Overflow is fine, just wrap
    {
        int hash = (int) 2166136261;
        // Suitable nullity checks etc, of course :)
        hash = (hash * 16777619) ^ field1.GetHashCode();
        hash = (hash * 16777619) ^ field2.GetHashCode();
        hash = (hash * 16777619) ^ field3.GetHashCode();
        return hash;
    }
}

Note that one thing to be aware of is that ideally you should prevent your equality-sensitive (and thus hashcode-sensitive) state from changing after adding it to a collection that depends on the hash code.

As per the documentation:

You can override GetHashCode for immutable reference types. In general, for mutable reference types, you should override GetHashCode only if:

  • You can compute the hash code from fields that are not mutable; or
  • You can ensure that the hash code of a mutable object does not change while the object is contained in a collection that relies on its hash code.

The link to the FNV article is broken but here is a copy in the Internet Archive: Eternally Confuzzled - The Art of Hashing

Regular expression for a hexadecimal number?

This will match with or without 0x prefix

(?:0[xX])?[0-9a-fA-F]+

async for loop in node.js

I've reduced your code sample to the following lines to make it easier to understand the explanation of the concept.

var results = [];
var config = JSON.parse(queries);
for (var key in config) {
    var query = config[key].query;
    search(query, function(result) {
        results.push(result);
    });
}
res.writeHead( ... );
res.end(results);

The problem with the previous code is that the search function is asynchronous, so when the loop has ended, none of the callback functions have been called. Consequently, the list of results is empty.

To fix the problem, you have to put the code after the loop in the callback function.

    search(query, function(result) {
        results.push(result);
        // Put res.writeHead( ... ) and res.end(results) here
    });

However, since the callback function is called multiple times (once for every iteration), you need to somehow know that all callbacks have been called. To do that, you need to count the number of callbacks, and check whether the number is equal to the number of asynchronous function calls.

To get a list of all keys, use Object.keys. Then, to iterate through this list, I use .forEach (you can also use for (var i = 0, key = keys[i]; i < keys.length; ++i) { .. }, but that could give problems, see JavaScript closure inside loops – simple practical example).

Here's a complete example:

var results = [];
var config = JSON.parse(queries);
var onComplete = function() {
    res.writeHead( ... );
    res.end(results);
};
var keys = Object.keys(config);
var tasksToGo = keys.length;
if (tasksToGo === 0) {
   onComplete();
} else {
    // There is at least one element, so the callback will be called.
    keys.forEach(function(key) {
        var query = config[key].query;
        search(query, function(result) {
            results.push(result);
            if (--tasksToGo === 0) {
                // No tasks left, good to go
                onComplete();
            }
        });
    });
}

Note: The asynchronous code in the previous example are executed in parallel. If the functions need to be called in a specific order, then you can use recursion to get the desired effect:

var results = [];
var config = JSON.parse(queries);
var keys = Object.keys(config);
(function next(index) {
    if (index === keys.length) { // No items left
        res.writeHead( ... );
        res.end(results);
        return;
    }
    var key = keys[index];
    var query = config[key].query;
    search(query, function(result) {
        results.push(result);
        next(index + 1);
    });
})(0);

What I've shown are the concepts, you could use one of the many (third-party) NodeJS modules in your implementation, such as async.

How do I ignore ampersands in a SQL script running from SQL Plus?

You can set the special character, which is looked for upon execution of a script, to another value by means of using the SET DEFINE <1_CHARACTER>

By default, the DEFINE function itself is on, and it is set to &

It can be turned off - as mentioned already - but it can be avoided as well by means of setting it to a different value. Be very aware of what sign you set it to. In the below example, I've chose the # character, but that choice is just an example.

SQL> select '&var_ampersand #var_hash' from dual;
Enter value for var_ampersand: a value

'AVALUE#VAR_HASH'
-----------------
a value #var_hash

SQL> set define #
SQL> r
  1* select '&var_ampersand #var_hash' from dual
Enter value for var_hash: another value

'&VAR_AMPERSANDANOTHERVALUE'
----------------------------
&var_ampersand another value

SQL>

belongs_to through associations

The has_many :choices creates an association named choices, not choice. Try using current_user.choices instead.

See the ActiveRecord::Associations documentation for information about about the has_many magic.

How can I get a channel ID from YouTube?

I just found the simplest way to find the channel ID of any YouTube channel !!

Step 1: Play a video of that channel.

Step 2: Click the channel name under that video.

Step 3: Look at the browser address bar.

How do I configure PyCharm to run py.test tests?

With a special Conda python setup which included the pip install for py.test plus usage of the Specs addin (option --spec) (for Rspec like nice test summary language), I had to do ;

1.Edit the default py.test to include option= --spec , which means use the plugin: https://github.com/pchomik/pytest-spec

2.Create new test configuration, using py.test. Change its python interpreter to use ~/anaconda/envs/ your choice of interpreters, eg py27 for my namings.

3.Delete the 'unittests' test configuration.

4.Now the default test config is py.test with my lovely Rspec style outputs. I love it! Thank you everyone!

p.s. Jetbrains' doc on run/debug configs is here: https://www.jetbrains.com/help/pycharm/2016.1/run-debug-configuration-py-test.html?search=py.test

syntax error near unexpected token `('

Since you've got both the shell that you're typing into and the shell that sudo -s runs, you need to quote or escape twice. (EDITED fixed quoting)

sudo -su db2inst1 '/opt/ibm/db2/V9.7/bin/db2 force application \(1995\)'

or

sudo -su db2inst1 /opt/ibm/db2/V9.7/bin/db2 force application \\\(1995\\\)

Out of curiosity, why do you need -s? Can't you just do this:

sudo -u db2inst1 /opt/ibm/db2/V9.7/bin/db2 force application \(1995\)

Difference between Inheritance and Composition

Though both Inheritance and Composition provides code reusablility, main difference between Composition and Inheritance in Java is that Composition allows reuse of code without extending it but for Inheritance you must extend the class for any reuse of code or functionality. Another difference which comes from this fact is that by using Composition you can reuse code for even final class which is not extensible but Inheritance cannot reuse code in such cases. Also by using Composition you can reuse code from many classes as they are declared as just a member variable, but with Inheritance you can reuse code form just one class because in Java you can only extend one class, because multiple Inheritance is not supported in Java. You can do this in C++ though because there one class can extend more than one class. BTW, You should always prefer Composition over Inheritance in Java, its not just me but even Joshua Bloch has suggested in his book

Write in body request with HttpClient

If your xml is written by java.lang.String you can just using HttpClient in this way

    public void post() throws Exception{
        HttpClient client = new DefaultHttpClient();
        HttpPost post = new HttpPost("http://www.baidu.com");
        String xml = "<xml>xxxx</xml>";
        HttpEntity entity = new ByteArrayEntity(xml.getBytes("UTF-8"));
        post.setEntity(entity);
        HttpResponse response = client.execute(post);
        String result = EntityUtils.toString(response.getEntity());
    }

pay attention to the Exceptions.

BTW, the example is written by the httpclient version 4.x

Prevent PDF file from downloading and printing

Although we should agree that ultimately you cannot prevent some form of document capture (specially through screen capture technology either through phone or computer), the goal is to prevent direct download of original document. Some suggest you turn it into images, but this is not necessary. There is clearly a way, as several cloud services allow you to share pdf files, removing the download option, without converting the PDF to images (a superior method because it retains important properties like word search). Personally, as a user of Outlook email, I use the cloud service it provides, OneDrive. I just want to share the HTML code produced by OneDrive to share PDF files without download and right-click support. I am no expert on HTMl so cannot tell you exactly how it is done, but it might still provide you some insights. Here is the code for one particular PDF I shared (without private information and other bits that seemed unnecessary to me):

<!DOCTYPE html>
<html lang="en-us" dir="ltr">
<head><meta name="GENERATOR" content="Microsoft SharePoint" /><meta http-equiv="Content-type" content="text/html; charset=utf-8" /><meta http-equiv="X-UA-Compatible" content="IE=edge" /><meta http-equiv="Expires" content="0" /><meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=no" /><title>
    OneDrive for Business
</title><link rel="shortcut icon" href="/_layouts/15/images/odbfavicon.ico?rev=47" type="image/vnd.microsoft.icon" id="favicon" /></head>

  <body style="margin: 0; padding: 0;">
    <script  nonce= '55c3d852-fe79-49b0-927d-e793a0ba3192' >if(!spfxPerfMarks){var spfxPerfMarks = {};} var markPerfStage=function(key) {if(window.performance && typeof window.performance.now === 'function'){spfxPerfMarks[key]=window.performance.now();} else{spfxPerfMarks[key]=Date.now();} if (window.performance && typeof window.performance.mark === 'function') {window.performance.mark(key);}};</script><script type="text/javascript" id="SuiteNavShellCore" nonce="55c3d852-fe79-49b0-927d-e793a0ba3192" crossorigin="anonymous" src="https://shellprod.msocdn.com/api/shellbootstrapper/business/oneshell">

</script><script type="text/javascript" nonce="55c3d852-fe79-49b0-927d-e793a0ba3192">
    window.document.getElementById('SuiteNavShellCore').addEventListener('error', function() { 
var scriptElem = document.getElementById('SuiteNavShellCore');
scriptElem.parentNode.removeChild(scriptElem);
var newScript = document.createElement('script');
newScript.setAttribute('type', 'text/javascript');
newScript.setAttribute('id', 'SuiteNavShellCore');
newScript.setAttribute('src', 'https://shellprod.msocdn.com/api/shellbootstrapper/business/oneshell');
newScript.setAttribute('crossorigin', 'anonymous');
newScript.async = true;
newScript.addEventListener('load', function() { (typeof markPerfStage === 'function' && markPerfStage('suiteNavScriptAsyncEnd')); if (window.executeSuiteNavOnce) { window.executeSuiteNavOnce() } });
newScript.addEventListener('error', function() { window.o365ShellScriptLoadError = arguments[0]; (typeof markPerfStage === 'function' && markPerfStage('suiteNavScriptError')); if (window.executeSuiteNavOnce) { window.executeSuiteNavOnce() } });
document.head.appendChild(newScript); });
</script><script type="text/javascript" nonce="55c3d852-fe79-49b0-927d-e793a0ba3192">
    window.o365ShellLoadPromiseResolve = undefined; window.o365ShellLoadPromiseReject = undefined; window.o365ShellRenderPromiseResolve = undefined; window.o365ShellRenderPromiseReject = undefined; window.o365ShellPostRenderPromiseResolve = undefined; window.o365ShellPostRenderPromiseReject = undefined; window.o365ShellLoadPromise = new Promise(function (loadResolve, loadReject) { window.o365ShellLoadPromiseResolve = loadResolve, window.o365ShellLoadPromiseReject = loadReject }); window.o365ShellRenderPromise = new Promise(function (renderResolve, renderReject) { window.o365ShellRenderPromiseResolve = renderResolve, window.o365ShellRenderPromiseReject = renderReject }); window.o365ShellPostRenderPromise = new Promise(function (prResolve,prReject) { window.o365ShellPostRenderPromiseResolve = prResolve, window.o365ShellPostRenderPromiseReject = prReject });var executeSuiteNav = function () {var suiteNavPlaceholder = document.createElement('div');suiteNavPlaceholder.id = 'SuiteNavPlaceholder';suiteNavPlaceholder.style = "min-height: 50px";document.body.insertBefore(suiteNavPlaceholder, document.body.firstChild);if (window.o365ShellScriptLoadError) {o365ShellLoadPromiseReject(window.o365ShellScriptLoadError);o365ShellRenderPromiseReject(new Error('SuiteNavLoadError'));o365ShellPostRenderPromiseReject(new Error('SuiteNavLoadError'));return; }o365ShellLoadPromiseResolve();var themeData;try { themeData = JSON.parse(localStorage.getItem('odSuiteNavthemedata')).themeData; }catch(err) { themeData = {Primary:'#0078D4'}; }(typeof markPerfStage === 'function' && markPerfStage('suiteNavRenderAsyncStart'));O365Shell.RenderAsync({top: 'SuiteNavPlaceholder', layout: 'Mouse', enableSearchUX: true, initialSearchUXVisibility: true, initialSearchUXPlaceholderText: 'Search', initialSearchUXSearchText: "",enableDelayLoading: true, collapseO365Settings: true, disableDelayLoad: false, disableShellPlus: false, isThinHeader: false, enableLegacyResponsiveBehavior: false, expectSearchBoxSettings: true, shellDataOverrides: {}, supportShyHeaderMode: false, initialRenderData: { AppBrandTheme: themeData, Culture: 'en-US', CurrentMainLinkElementId: 'ShellDocuments', IsConsumer: false, UserDisplayName: 'JOHN DOE', UserID: '100320009e7b358d', WorkloadId: 'Sharepoint', ShellBootHost: 'https://shellprod.msocdn.com', EnableVanillaSearchBox: true }},function () {(typeof markPerfStage === 'function' && markPerfStage('suiteNavRenderAsyncEnd'));o365ShellRenderPromiseResolve();},function () {(typeof markPerfStage === 'function' && markPerfStage('suiteNavPostRender'));o365ShellPostRenderPromiseResolve();},function (error) {(typeof markPerfStage === 'function' && markPerfStage('suiteNavRenderAsyncErrorEnd'));o365ShellRenderPromiseReject(error); o365ShellPostRenderPromiseReject(error);});};
</script><script type="text/javascript" nonce="55c3d852-fe79-49b0-927d-e793a0ba3192">
    var params = window.location.search.substring(1).split('&') || [];
var shouldExecuteSuiteNav = true;
shouldExecuteSuiteNav &= params.indexOf('p=2') === -1;
shouldExecuteSuiteNav &= params.indexOf('cl=true') === -1;
shouldExecuteSuiteNav &= params.filter(function (x) { return x.indexOf('parent') === 0; }).length === 0;
try { shouldExecuteSuiteNav &= window.parent === window; } catch(err) { shouldExecuteSuiteNav = false; }
if (shouldExecuteSuiteNav) { executeSuiteNav(); }
</script>
  </body>



  
  
      <script type="text/javascript">
      try {
          (function() {
              var a = navigator.userAgent.toLowerCase();
              var i = a.indexOf("msie");
              if (-1 !== i) {
                  var v = parseInt(a.substring(i + 5));
                  if (v <= 8 && Boolean(document.documentMode) && document.documentMode <= 8) {
                      var d = new Date(); d.setTime(d.getTime() + 31536000000);
                      document.cookie = "odbnu=0;expires=" + d.toUTCString() + ";path=/";
                      window.location.href = window.location.href.replace(/\/onedrive\.aspx/i, '/start.aspx#/Documents/Forms/All.aspx');
                  }
              }
          })();
      } catch(e) {}
      </script>
      <script type="text/javascript" nonce="55c3d852-fe79-49b0-927d-e793a0ba3192">
       SOME PRIVATE STUFF HERE
</script><link rel="preconnect" href="https://spoprod-a.akamaihd.net" crossorigin /><script type="text/javascript">
    !function(){if('PerformanceLongTaskTiming' in window){var g=window.__tti={e:[]};g.o=new PerformanceObserver(function(l){g.e=g.e.concat(l.getEntries())});g.o.observe({entryTypes:['longtask']})}}();
</script><script type="text/javascript">
    var g_responseEnd = new Date().getTime();window['FabricConfig'] = { fontBaseUrl: ''};window['__odsp_culture'] = 'en-us';window['__odspSriHashes'] = {"listviewdataprefetch-mini-c82c051f.js":"sha256-GCNR9Rk+cuSJfvbszuhs5ZBaUs5tQ2RdzzJTteHOXGk=","reactandknockout-mini-584215d6.js":"sha256-ICjqvvD9qHiKbj5xYFNGC/JsgNcqNRRL1t3kW4RVioI=","aria-mini-2e5a74c4.js":"sha256-CbCwYga9yHE+t1OvB+NHHDdH2rxSfY6KJkCMiUpXQjw=","spectreviewer-mini-9c641fce.js":"sha256-tqmAhKxEONjZOpZuGrbo8VdnLx6kRH+Xfhjrcchv2+4=","babylonjs-mini-22e57381.js":"sha256-T6IgL4CdkolwNC0L4tG6d+G07Bhuc7bI1pSIShdrTUk=","sp-http_odb-mini-21a5eb98.js":"sha256-mTfdqB83ALG/d2z8krhrUugjXBzFQ/bzPfUIgcayACg=","onedriveappfontsplt-mini-ce0e18ec.js":"sha256-+ockQ4cjstrmVqBPVRH8C9Z9M0ZJbyQxHQ/cm/ukBOI=","onedriveappfontsdeferred-mini-3771cbb9.js":"sha256-qXZjhCWJDNPCbbXRIwDt1cqIyqzQKqROnwdASmSsoGw=","odbonedriveapp-mini-11081db7.js":"sha256-j/CkxuEVbtMOL5PRKZ05dZURZ/aNH9tk6vnMj6ei/lk=","en-us/
</script><script type="text/javascript">
    window['moduleNameMapping']={"odsp-next/providers/operation/OperationProvider":"Rq"};
</script><script type="text/javascript" data-import-link="https://spoprod-a.akamaihd.net/files/odsp-common-library-prod_2019-02-15_20190219.002/require.js" id="requireJsString">
    SOME VERY LONG FUNCTION CODE
</script><link href="https://spoprod-a.akamaihd.net/files/odsp-next-prod-amd_2020-06-12_20200612.001/listviewdataprefetch-mini-c82c051f.js" rel="preload" crossorigin="anonymous" as="script" /><link href="https://spoprod-a.akamaihd.net/files/odsp-next-prod-amd_2020-06-12_20200612.001/reactandknockout-mini-584215d6.js" rel="preload" crossorigin="anonymous" as="script" /><link href="https://spoprod-a.akamaihd.net/files/odsp-next-prod-amd_2020-06-12_20200612.001/odbonedriveapp-mini-11081db7.js" rel="preload" crossorigin="anonymous" as="script" /><link href="https://spoprod-a.akamaihd.net/files/odsp-next-prod-amd_2020-06-12_20200612.001/en-us/odbonedriveapp-mini.resx-7f957d5c.js" rel="preload" crossorigin="anonymous" as="script" /><link href="https://spoprod-a.akamaihd.net/files/odsp-next-prod-amd_2020-06-12_20200612.001/odbonedrive-mini-5e8b1855.js" rel="preload" crossorigin="anonymous" as="script" /><link href="https://spoprod-a.akamaihd.net/files/odsp-next-prod-amd_2020-06-12_20200612.001/en-us/odbonedrive-mini.resx-374bb468.js" rel="preload" crossorigin="anonymous" as="script" /><link href="https://spoprod-a.akamaihd.net/files/odsp-next-prod-amd_2020-06-12_20200612.001/odbfiles-mini-9aaee23c.js" rel="preload" crossorigin="anonymous" as="script" /><link href="https://spoprod-a.akamaihd.net/files/odsp-next-prod-amd_2020-06-12_20200612.001/en-us/odbfiles-mini.resx-250da06d.js" rel="preload" crossorigin="anonymous" as="script" /><link href="https://spoprod-a.akamaihd.net/files/odsp-next-prod-amd_2020-06-12_20200612.001/odbitemsscope-mini-5070e33c.js" rel="preload" crossorigin="anonymous" as="script" /><link href="https://spoprod-a.akamaihd.net/files/odsp-next-prod-amd_2020-06-12_20200612.001/en-us/odbitemsscope-mini.resx-ff223e24.js" rel="preload" crossorigin="anonymous" as="script" /><script type="text/javascript" id="requireConfig">
    
!function(){
    var backupBaseUrl = 'https://az741266.vo.msecnd.net/files/odsp-next-prod-amd_2020-06-12_20200612.001/';
    window.__backupBaseUrl = backupBaseUrl;
    var failOverState = window.__cdnFailOverState = {
        baseUrlFailedOver: false,
        modulesFalledBack: []
    };
    function processConfigToSupportFailOver(config) {
        var paths = {};
        for (var bundleId in config.bundles) {
            var bundlePath = config.paths[bundleId];
            var fallbackPaths = [bundlePath, backupBaseUrl + bundlePath];
            for (var _i = 0, _a = config.bundles[bundleId]; _i < _a.length; _i++) {
                var moduleName = _a[_i];
                paths[moduleName] = fallbackPaths;
            }
        }
        return {
            paths: paths,
            shim: config.shim,
            deps: config.deps,
            baseUrl: config.baseUrl,
            waitSeconds: config.waitSeconds,
            onNodeCreated: config.onNodeCreated,
            enforceDefine: config.enforceDefine,
            onPathFallback: function (options) {
                var moduleId = options.moduleId;
                var config = options.config;
                if (moduleId && config && config.deps && config.deps.indexOf(moduleId) >= 0) {
                    var failedModules = failOverState.modulesFalledBack;
                    failedModules.push(moduleId);
                    if (!failOverState.baseUrlFailedOver && failedModules.length >= 2) {
                        require.config({
                            baseUrl: backupBaseUrl
                        });
                        failOverState.baseUrlFailedOver = true;
                    }
                }
            }
        };
    }
    var config = {paths:{"listviewdataprefetch-mini":"listviewdataprefetch-mini-c82c051f","reactandknockout-mini":"reactandknockout-mini-584215d6","aria-mini":"aria-mini-2e5a74c4","spectreviewer-mini":"spectreviewer-mini-9c641fce","babylonjs-mini":"babylonjs-mini-22e57381","sp-http_odb-mini":"sp-http_odb-mini-21a5eb98","onedriveappfontsplt-mini":"onedriveappfontsplt-mini-ce0e18ec","onedriveappfontsdeferred-mini":"onedriveappfontsdeferred-mini-3771cbb9","odbonedriveapp-mini":"odbonedriveapp-mini-11081db7","odbonedriveapp-mini.resx":"en-us/odbonedriveapp-mini.resx-7f957d5c","odbonedrive-mini":"odbonedrive-mini-5e8b1855","odbonedrive-mini.resx":"en-us/odbonedrive-mini.resx-374bb468","odbbasepage-mini":"odbbasepage-mini-8d7dea71","odbfiles-mini":"odbfiles-mini-9aaee23c","odbfiles-mini.resx":"en-us/odbfiles-mini.resx-250da06d","odbuploadmanager-mini":"odbuploadmanager-mini-168f0ee8","odbuploadmanager-mini.resx":"en-us/odbuploadmanager-mini.resx-660b735c","odbreactcontrols-mini":"odbreactcontrols-mini-6f323ced","odbreactcontrols-mini.resx":"en-us/odbreactcontrols-mini.resx-c7ec26e2","odbdeferred-mini":"odbdeferred-mini-b9def3da","odbdeferred-mini.resx":"en-us/odbdeferred-mini.resx-d1f98f82","odblivepersonapicker-mini":"odblivepersonapicker-mini-414c6f81","odbdebugwindow-mini":"odbdebugwindow-mini-2f4ef22c","odbfilepicker-mini":"odbfilepicker-mini-2f5a2203","odbfilepicker-mini.resx":"en-us/odbfilepicker-mini.resx-3562db06","odbembed-mini":"odbembed-mini-8638d6c3","odboneup-mini":"odboneup-mini-3086899d","odboneup-mini.resx":"en-us/odboneup-mini.resx-a7d40d5e","odbpdf-mini":"odbpdf-mini-7d046eb1","odbpdf-mini.resx":"en-us/odbpdf-mini.resx-e5e07b77","odbwrs-mini":"odbwrs-mini-2c0b0a8b","odbsharepage-mini":"odbsharepage-mini-e62fc2f8","odbtextfileeditor-mini":"odbtextfileeditor-mini-000ede78","odbtextfileeditor-mini.resx":"en-us/odbtextfileeditor-mini.resx-259dbac3","odbfilerequestpage-mini":"odbfilerequestpage-mini-db0e14b3","odbfilerequestpage-mini.resx":"en-us/odbfilerequestpage-mini.resx-8e83db21","odbtiles-mini":"odbtiles-mini-a111ffa2","odbtiles-mini.resx":"en-us/odbtiles-mini.resx-4fae993b","odbsites-mini":"odbsites-mini-c5563389","odbsites-mini.resx":"en-us/odbsites-mini.resx-1b3b4aeb","odbitemvideoplayer-mini":"odbitemvideoplayer-mini-b7a61bf1","odbitemvideoplayer-mini.resx":"en-us/odbitemvideoplayer-mini.resx-983d47a8","odbexecutors-mini":"odbexecutors-mini-f93c0ada","odbexecutors-mini.resx":"en-us/odbexecutors-mini.resx-853081e6","odbdeferredcontrols-mini":"odbdeferredcontrols-mini-29643ad1","odbdeferredcontrols-mini.resx":"en-us/odbdeferredcontrols-mini.resx-d50ca5ed","odbnotifications-mini":"odbnotifications-mini-04da08b9","odbpushchannel-mini":"odbpushchannel-mini-38d90d10","odberror-mini":"odberror-mini-12596c1d","odberror-mini.resx":"en-us/odberror-mini.resx-cf31139d","odbrestore-mini":"odbrestore-mini-950ba62f","odbrestore-mini.resx":"en-us/odbrestore-mini.resx-3a5cbe8e","odbsettingsbasepage-mini":"odbsettingsbasepage-mini-d6c5acdd","odbsettingsbasepage-mini.resx":"en-us/odbsettingsbasepage-mini.resx-b5949852","odbsettings-mini":"odbsettings-mini-ddeab1d1","odbitemsscope-mini":"odbitemsscope-mini-5070e33c","odbitemsscope-mini.resx":"en-us/odbitemsscope-mini.resx-ff223e24","odbitemsscopedeferred-mini":"odbitemsscopedeferred-mini-f918897a","odbitemsscopedeferred-mini.resx":"en-us/odbitemsscopedeferred-mini.resx-af61a995","odbmobileappupsellbasepage-mini":"odbmobileappupsellbasepage-mini-723e546a","odbemptyfolderroot-mini":"odbemptyfolderroot-mini-f9f096eb","odbwinappcommunicator-mini":"odbwinappcommunicator-mini-60ab2c1a","odbcreatesite-mini":"odbcreatesite-mini-5400c9ec","odbcreatesite-mini.resx":"en-us/odbcreatesite-mini.resx-d9c236d6","odb-functional-tests-mini":"odb-functional-tests-mini-41e66bd6","odbhighcharts-mini":"odbhighcharts-mini-ce7056aa","odbclientform-mini":"odbclientform-mini-106b2b9f","odbclientform-mini.resx":"en-us/odbclientform-mini.resx-356af9e8","odbfloodgate-mini":"odbfloodgate-mini-061846b3","odbfloodgate-mini.resx":"en-us/odbfloodgate-mini.resx-610e7422","odbpowerapps-mini":"odbpowerapps-mini-c5977eac","msflowsdk":"msflowsdk-8689f64f","power-app":"power-app-86d2bb4d"},"directional-navigation":{}},deps:["bL3","f","bvB","a6o","buW","buZ","bfi"],baseUrl:"https:\u002f\u002fspoprod-a.akamaihd.net\u002ffiles\u002fodsp-next-prod-amd_2020-06-12_20200612.001\u002f",waitSeconds:0,onNodeCreated:function(n,c,m,u) {
n.setAttribute("crossorigin","anonymous");
var urlParts = u.split('/');
var fileName = urlParts[urlParts.length - 1];
var odspSriHashes = window.__odspSriHashes;
var integrity = odspSriHashes && (odspSriHashes[window.__odsp_culture + '/' + fileName] || odspSriHashes[fileName]);
if (integrity) {
    n.setAttribute("integrity",integrity);
}
},enforceDefine:true};
    var newConfig = processConfigToSupportFailOver(config);
    require.config(newConfig);
}();

</script><script type="text/javascript">
    window["_spModuleLink"]={"buildNumber":"odsp-next-prod-amd_2020-06-12_20200612.001","manifestName":"ODBOneDrive","scenarioName":"ODBOneDrive","usingRedirectCookie":false,"bugLinkFormat":null,"ulsLinkFormat":null};
</script>
      
  

</html>
<script type="text/javascript" nonce="55c3d852-fe79-49b0-927d-e793a0ba3192">
    var g_duration = 92;
var g_iisLatency = 2;
var g_cpuDuration = 72;
var g_queryCount = 6;
var g_queryDuration = 18;
var g_requireJSDone = new Date().getTime();
</script><script type="text/javascript">
var _spOneDrivePageDataCache = {"SPHomeWeb:sites/feed":{"cacheContext":{"ListItemId":3,"Hash":null,"MySiteUrl":null,"Time":"2020-05-28T15:24:51.0000000Z","Version":null},"cacheValue":null},"ODBWeb.sites/feed":{"cacheContext":{"ListItemId":4,"Hash":"7iItaPeKRTNyNthQTkF2/CvVyjcOTjNOkCsKnNsKarY=","MySiteUrl":null,"Time":"2020-05-28T15:25:03.0000000Z","Version":"1.0"},"cacheValue":"{\"Items\":[],\"Type\":\"ItemsList\"}"},"ODBWeb.substrate.recommended":{"cacheContext":{"ListItemId":5,"Hash":null,"MySiteUrl":null,"Time":"2020-05-28T15:24:51.0000000Z","Version":null},"cacheValue":null}};

</script>
<script type="text/javascript" nonce="55c3d852-fe79-49b0-927d-e793a0ba3192">
    var g_deferDataLoadTime = new Date().getTime();var g_payload = {"parameters":{"__metadata":{"type":"SP.RenderListDataParameters"},"RenderOptions":1513223,"AllowMultipleValueFilterForTaxonomyFields":true, "AddRequiredFields":true}}; var g_listData = {"wpq":"","Templates":{},"ListData":{ "Row" : 
[] OTHER SETTINGS WITH PRIVATE STUFF...
}};if (typeof DeferredListDataComplete != "undefined" && DeferredListDataComplete) { DeferredListDataComplete(); }
</script>

How can I trigger the click event of another element in ng-click using angularjs?

Simply have them in the same controller, and do something like this:

HTML:

<input id="upload"
    type="file"
    ng-file-select="onFileSelect($files)"
    style="display: none;">

<button type="button"
    ng-click="startUpload()">Upload</button>

JS:

var MyCtrl = [ '$scope', '$upload', function($scope, $upload) {
  $scope.files = [];
  $scope.startUpload = function(){
    for (var i = 0; i < $scope.files.length; i++) {
      $upload($scope.files[i]);
    } 
  }
  $scope.onFileSelect = function($files) {
     $scope.files = $files;
  };
}];

This is, in my opinion, the best way to do it in angular. Using jQuery to find the element and trigger an event isn't the best practice.

Difference between __getattr__ vs __getattribute__

A key difference between __getattr__ and __getattribute__ is that __getattr__ is only invoked if the attribute wasn't found the usual ways. It's good for implementing a fallback for missing attributes, and is probably the one of two you want.

__getattribute__ is invoked before looking at the actual attributes on the object, and so can be tricky to implement correctly. You can end up in infinite recursions very easily.

New-style classes derive from object, old-style classes are those in Python 2.x with no explicit base class. But the distinction between old-style and new-style classes is not the important one when choosing between __getattr__ and __getattribute__.

You almost certainly want __getattr__.

Open an image using URI in Android's default gallery image viewer

The problem with showing a file using Intent.ACTION_VIEW, is that if you pass the Uri parsing the path. Doesn't work in all cases. To fix that problem, you need to use:

Uri.fromFile(new File(filePath));

Instead of:

Uri.parse(filePath);

Edit

Here is my complete code:

Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(new File(mediaFile.filePath)), mediaFile.getExtension());
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);

Info

MediaFile is my domain class to wrap files from database in objects. MediaFile.getExtension() returns a String with Mimetype for the file extension. Example: "image/png"


Aditional code: needed for showing any file (extension)

import android.webkit.MimeTypeMap;

public String getExtension () {
    MimeTypeMap myMime = MimeTypeMap.getSingleton();
    return myMime.getMimeTypeFromExtension(MediaFile.fileExtension(filePath));
}

public static String fileExtension(String path) {
    if (path.indexOf("?") > -1) {
        path = path.substring(0, path.indexOf("?"));
    }
    if (path.lastIndexOf(".") == -1) {
        return null;
    } else {
        String ext = path.substring(path.lastIndexOf(".") + 1);
        if (ext.indexOf("%") > -1) {
            ext = ext.substring(0, ext.indexOf("%"));
        }
        if (ext.indexOf("/") > -1) {
            ext = ext.substring(0, ext.indexOf("/"));
        }
        return ext.toLowerCase();
    }
}

Let me know if you need more code.

Does Hibernate create tables in the database automatically

your hibernate.hbm2ddl.auto setting should be defining that the database is created (options are validate, create, update or create-drop)

Vendor code 17002 to connect to SQLDeveloper

I encountered same problem with ORACLE 11G express on Windows. After a long time waiting I got the same error message.

My solution is to make sure the hostname in tnsnames.ora (usually it's not "localhost") and the default hostname in sql developer(usually it's "localhost") same. You can either do this by changing it in the tnsnames.ora, or filling up the same in the sql developer.

Oh, of course you need to reboot all the oracle services (just to be safe).

Hope it helps.


I came across the similar problem again on another machine, but this time above solution doesn't work. After some trying, I found restarting all the oracle related services can fix the problem. Originally when the installation is done, connection can be made. Somehow after several reboot of computer, there is problem. I change all the oracle services with start time as auto. And once I could not connect, I restart them all over again (the core service should be restarted at last order), and works fine.

Some article says it might be due to the MTS problem. Microsoft's problem. Maybe!

Get width height of remote image from url

ES6: Using async/await you can do below getMeta function in sequence-like way and you can use it as follows (which is almost identical to code in your question (I add await keyword and change variable end to img, and change var to let keyword). You need to run getMeta by await only from async function (run).

_x000D_
_x000D_
function getMeta(url) {
    return new Promise((resolve, reject) => {
        let img = new Image();
        img.onload = () => resolve(img);
        img.onerror = () => reject();
        img.src = url;
    });
}

async function run() {

  let img = await getMeta("http://shijitht.files.wordpress.com/2010/08/github.png");

  let w = img.width;
  let h = img.height; 

  size.innerText = `width=${w}px, height=${h}px`;
  size.appendChild(img);
}

run();
_x000D_
<div id="size" />
_x000D_
_x000D_
_x000D_

Setting format and value in input type="date"

Please check this https://stackoverflow.com/a/9519493/1074944 and try this way also $('input[type="date"]').datepicker().prop('type','text'); check the demo

Hibernate Group by Criteria Object

You can use the approach @Ken Chan mentions, and add a single line of code after that if you want a specific list of Objects, example:

    session.createCriteria(SomeTable.class)       
                    .add(Restrictions.ge("someColumn", xxxxx))      
                    .setProjection(Projections.projectionList()
                            .add(Projections.groupProperty("someColumn"))
                            .add(Projections.max("someColumn"))
                            .add(Projections.min("someColumn"))
                            .add(Projections.count("someColumn"))           
                    ).setResultTransformer(Transformers.aliasToBean(SomeClazz.class));

List<SomeClazz> objectList = (List<SomeClazz>) criteria.list();

How to shutdown a Spring Boot Application in a correct way?

All of the answers seem to be missing the fact that you may need to complete some portion of work in coordinated fashion during graceful shutdown (for example, in an enterprise application).

@PreDestroy allows you to execute shutdown code in the individual beans. Something more sophisticated would look like this:

@Component
public class ApplicationShutdown implements ApplicationListener<ContextClosedEvent> {
     @Autowired ... //various components and services

     @Override
     public void onApplicationEvent(ContextClosedEvent event) {
         service1.changeHeartBeatMessage(); // allows loadbalancers & clusters to prepare for the impending shutdown
         service2.deregisterQueueListeners();
         service3.finishProcessingTasksAtHand();
         service2.reportFailedTasks();
         service4.gracefullyShutdownNativeSystemProcessesThatMayHaveBeenLaunched(); 
         service1.eventLogGracefulShutdownComplete();
     }
}

"static const" vs "#define" vs "enum"

We looked at the produced assembler code on the MBF16X... Both variants result in the same code for arithmetic operations (ADD Immediate, for example).

So const int is preferred for the type check while #define is old style. Maybe it is compiler-specific. So check your produced assembler code.

Remove large .pack file created by git

this is more of a handy solution than a coding one. zip the file. Open the zip in file view format (different from unzipping). Delete the .pack file. Unzip and replace the folder. Works like a charm!

Using a dispatch_once singleton model in Swift

Swift 5.2

You can point to the type with Self. So:

static let shared = Self()

And should be inside a type, like:

class SomeTypeWithASingletonInstance {
   static let shared = Self()
}

How to determine if OpenSSL and mod_ssl are installed on Apache2

In my case this is how I got the information:

  • find where apache logs are located, and go there, in my case:

    cd /var/log/apache2

  • find in which log openssl information can be found:

    grep -i apache.*openssl *_log

    e.g. error_log ...

  • to get fresh information, restart apache, e.g.

    rcapache2 restart # or service apache2 restart

  • check for last entries in the log, e.g.

    /var/log/apache2 # tail error_log

    [Thu Jun 09 07:42:24 2016] [notice] Apache/... (Linux/...) mod_ssl/2.2.22 OpenSSL/1.0.1t ...

difference between System.out.println() and System.err.println()

System.out.println("wassup"); refers to when you have to output a certain result pertaining to the proper input given by the user whereas System.err.println("duh, that's wrong); is a reference to show that the input provided is wrong or there is some other error.

Most of the IDEs show this in red color (System.err.print).

How can a Jenkins user authentication details be "passed" to a script which uses Jenkins API to create jobs?

Try this way: (for example delete the job)

curl --silent --show-error http://<username>:<api-token>@<jenkins-server>/job/<job-name>/doDelete

The api-token can be obtained from http://<jenkins-server>/user/<username>/configure.

HTML 5: Is it <br>, <br/>, or <br />?

XML doesn't allow leaving tags open, so it makes <br> a bit worse than the other two. The other two are roughly equivalent with the second (<br/>) preferred for compatibility with older browsers. Actually, space before / is preferred for compatibility sake, but I think it only makes sense for tags that have attributes. So I'd say either <br/> or <br />, whichever pleases your aesthetics.

To sum it up: all three are valid with the first one (<br>) being a bit less "portable".

Edit: Now that we're all crazy about specs, I think it worth pointing out that according to dev.w3.org:

Start tags consist of the following parts, in exactly the following order:

  1. A "<" character.
  2. The element’s tag name.
  3. Optionally, one or more attributes, each of which must be preceded by one or more space characters.
  4. Optionally, one or more space characters.
  5. Optionally, a "/" character, which may be present only if the element is a void element.
  6. A ">" character.

How to edit the size of the submit button on a form?

Use the css height and width properties.

For this to work on Mac, you also need to set the button's border to none.

How get data from material-ui TextField, DropDownMenu components?

Add an onChange handler to each of your TextField and DropDownMenu elements. When it is called, save the new value of these inputs in the state of your Content component. In render, retrieve these values from state and pass them as the value prop. See Controlled Components.

var Content = React.createClass({

    getInitialState: function() {
        return {
            textFieldValue: ''
        };
    },

    _handleTextFieldChange: function(e) {
        this.setState({
            textFieldValue: e.target.value
        });
    },

    render: function() {
        return (
            <div>
                <TextField value={this.state.textFieldValue} onChange={this._handleTextFieldChange} />
            </div>
        )
    }

});

Now all you have to do in your _handleClick method is retrieve the values of all your inputs from this.state and send them to the server.

You can also use the React.addons.LinkedStateMixin to make this process easier. See Two-Way Binding Helpers. The previous code becomes:

var Content = React.createClass({

    mixins: [React.addons.LinkedStateMixin],

    getInitialState: function() {
        return {
            textFieldValue: ''
        };
    },

    render: function() {
        return (
            <div>
                <TextField valueLink={this.linkState('textFieldValue')} />
            </div>
        )
    }

});

read complete file without using loop in java

If you are using Java 5/6, you can use Apache Commons IO for read file to string. The class org.apache.commons.io.FileUtils contais several method for read files.

e.g. using the method FileUtils#readFileToString:

File file = new File("abc.txt");
String content = FileUtils.readFileToString(file);

How does the stack work in assembly language?

Calling functions, which requires saving and restoring local state in LIFO fashion (as opposed to say, a generalized co-routine approach), turns out to be such an incredibly common need that assembly languages and CPU architectures basically build this functionality in. The same could probably be said for notions of threading, memory protection, security levels, etc. In theory you could implement your own stack, calling conventions, etc., but I assume some opcodes and most existing runtimes rely on this native concept of "stack".

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

You can now pip install numpy on Windows!

"Note: this page has only historical relevance, you can now pip-install for windows" Source: https://github.com/numpy/numpy/wiki/Whats-with-Windows-builds

sudo echo "something" >> /etc/privilegedFile doesn't work

In bash you can use tee in combination with > /dev/null to keep stdout clean.

 echo "# comment" |  sudo tee -a /etc/hosts > /dev/null

Node.js ES6 classes with require

Yes, your example would work fine.

As for exposing your classes, you can export a class just like anything else:

class Animal {...}
module.exports = Animal;

Or the shorter:

module.exports = class Animal {

};

Once imported into another module, then you can treat it as if it were defined in that file:

var Animal = require('./Animal');

class Cat extends Animal {
    ...
}

Force Internet Explorer to use a specific Java Runtime Environment install?

For the server-side solution (which your question was originally ambiguous about), this page at sun lists one way to specify a JRE. Specifically,

<OBJECT 
  classid="clsid:8AD9C840-044E-11D1-B3E9-00805F499D93"
  width="200" height="200">
  <PARAM name="code" value="Applet1.class">
</OBJECT>

The classid attribute identifies which version of Java Plug-in to use.

Following is an alternative form of the classid attribute:

classid="clsid:CAFEEFAC-xxxx-yyyy-zzzz-ABCDEFFEDCBA"

In this form, "xxxx", "yyyy", and "zzzz" are four-digit numbers that identify the specific version of Java Plug-in to be used.

For example, to use Java Plug-in version 1.5.0, you specify:

classid="clsid:CAFEEFAC-0015-0000-0000-ABCDEFFEDCBA"

How to convert InputStream to FileInputStream

Long story short: Don't use FileInputStream as a parameter or variable type. Use the abstract base class, in this case InputStream instead.

Vue.js dynamic images not working

I got this working by following code

  getImgUrl(pet) {
    var images = require.context('../assets/', false, /\.png$/)
    return images('./' + pet + ".png")
  }

and in HTML:

<div class="col-lg-2" v-for="pic in pics">
   <img :src="getImgUrl(pic)" v-bind:alt="pic">
</div>

But not sure why my earlier approach did not work.

ImportError: No Module named simplejson

Sometimes there is permission errors. Try:

sudo pip install simplejson

Hope it helps.

Forwarding port 80 to 8080 using NGINX

As simple as like this,

make sure to change example.com to your domain (or IP), and 8080 to your Node.js application port:

server {
    listen 80;
    server_name example.com;

    location / {
        proxy_set_header   X-Forwarded-For $remote_addr;
        proxy_set_header   Host $http_host;
        proxy_pass         "http://127.0.0.1:8080";
    }
}

Source: https://eladnava.com/binding-nodejs-port-80-using-nginx/

Use URI builder in Android or create URL with variables

You can do that with lambda expressions;

    private static final String BASE_URL = "http://api.example.org/data/2.5/forecast/daily";

    private String getBaseUrl(Map<String, String> params) {
        final Uri.Builder builder = Uri.parse(BASE_URL).buildUpon();
        params.entrySet().forEach(entry -> builder.appendQueryParameter(entry.getKey(), entry.getValue()));
        return builder.build().toString();
    }

and you can create params like that;

    Map<String, String> params = new HashMap<String, String>();
    params.put("zip", "94043,us");
    params.put("units", "metric");

Btw. If you will face any issue like “lambda expressions not supported at this language level”, please check this URL;

https://stackoverflow.com/a/22704620/2057154

What is the common header format of Python files?

The answers above are really complete, but if you want a quick and dirty header to copy'n paste, use this:

#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""Module documentation goes here
   and here
   and ...
"""

Why this is a good one:

  • The first line is for *nix users. It will choose the Python interpreter in the user path, so will automatically choose the user preferred interpreter.
  • The second one is the file encoding. Nowadays every file must have a encoding associated. UTF-8 will work everywhere. Just legacy projects would use other encoding.
  • And a very simple documentation. It can fill multiple lines.

See also: https://www.python.org/dev/peps/pep-0263/

If you just write a class in each file, you don't even need the documentation (it would go inside the class doc).

Java: how to add image to Jlabel?

the shortest code is :

JLabel jLabelObject = new JLabel();
jLabelObject.setIcon(new ImageIcon(stringPictureURL));

stringPictureURL is PATH of image .

How to compare only date components from DateTime in EF?

NOTE: at the time of writing this answer, the EF-relation was unclear (that was edited into the question after this was written). For correct approach with EF, check Mandeeps answer.


You can use the DateTime.Date property to perform a date-only comparison.

DateTime a = GetFirstDate();
DateTime b = GetSecondDate();

if (a.Date.Equals(b.Date))
{
    // the dates are equal
}

CSS word-wrapping in div

I'm a little surprised it doesn't just do that. Could there another element inside the div that has a width set to something greater than 250?

MySQL Job failed to start

In most cases, just purging the mysql-server package and re-installing it will do the job.

Run,

sudo apt-get purge mysql-server-5.1 mysql-common

followed by

sudo apt-get install mysql-server

Generating random number between 1 and 10 in Bash Shell Script

To generate in the range: {0,..,9}

r=$(( $RANDOM % 10 )); echo $r

To generate in the range: {40,..,49}

r=$(( $RANDOM % 10 + 40 )); echo $r

Angular 2 Show and Hide an element

There are two options depending what you want to achieve :

  1. You can use the hidden directive to show or hide an element

    <div [hidden]="!edited" class="alert alert-success box-msg" role="alert">
      <strong>List Saved!</strong> Your changes has been saved.
    </div>
    
  2. You can use the ngIf control directive to add or remove the element. This is different of the hidden directive because it does not show / hide the element, but it add / remove from the DOM. You can loose unsaved data of the element. It can be the better choice for an edit component that is cancelled.

    <div *ngIf="edited" class="alert alert-success box-msg" role="alert"> 
      <strong>List Saved!</strong> Your changes has been saved.
    </div>
    

For you problem of change after 3 seconds, it can be due to incompatibility with setTimeout. Did you include angular2-polyfills.js library in your page ?

Pandas DataFrame to List of Dictionaries

If you are interested in only selecting one column this will work.

df[["item1"]].to_dict("records")

The below will NOT work and produces a TypeError: unsupported type: . I believe this is because it is trying to convert a series to a dict and not a Data Frame to a dict.

df["item1"].to_dict("records")

I had a requirement to only select one column and convert it to a list of dicts with the column name as the key and was stuck on this for a bit so figured I'd share.

Transposing a 2D-array in JavaScript

You can achieve this without loops by using the following.

It looks very elegant and it does not require any dependencies such as jQuery of Underscore.js.

function transpose(matrix) {  
    return zeroFill(getMatrixWidth(matrix)).map(function(r, i) {
        return zeroFill(matrix.length).map(function(c, j) {
            return matrix[j][i];
        });
    });
}

function getMatrixWidth(matrix) {
    return matrix.reduce(function (result, row) {
        return Math.max(result, row.length);
    }, 0);
}

function zeroFill(n) {
    return new Array(n+1).join('0').split('').map(Number);
}

Minified

function transpose(m){return zeroFill(m.reduce(function(m,r){return Math.max(m,r.length)},0)).map(function(r,i){return zeroFill(m.length).map(function(c,j){return m[j][i]})})}function zeroFill(n){return new Array(n+1).join("0").split("").map(Number)}

Here is a demo I threw together. Notice the lack of loops :-)

_x000D_
_x000D_
// Create a 5 row, by 9 column matrix._x000D_
var m = CoordinateMatrix(5, 9);_x000D_
_x000D_
// Make the matrix an irregular shape._x000D_
m[2] = m[2].slice(0, 5);_x000D_
m[4].pop();_x000D_
_x000D_
// Transpose and print the matrix._x000D_
println(formatMatrix(transpose(m)));_x000D_
_x000D_
function Matrix(rows, cols, defaultVal) {_x000D_
    return AbstractMatrix(rows, cols, function(r, i) {_x000D_
        return arrayFill(cols, defaultVal);_x000D_
    });_x000D_
}_x000D_
function ZeroMatrix(rows, cols) {_x000D_
    return AbstractMatrix(rows, cols, function(r, i) {_x000D_
        return zeroFill(cols);_x000D_
    });_x000D_
}_x000D_
function CoordinateMatrix(rows, cols) {_x000D_
    return AbstractMatrix(rows, cols, function(r, i) {_x000D_
        return zeroFill(cols).map(function(c, j) {_x000D_
            return [i, j];_x000D_
        });_x000D_
    });_x000D_
}_x000D_
function AbstractMatrix(rows, cols, rowFn) {_x000D_
    return zeroFill(rows).map(function(r, i) {_x000D_
        return rowFn(r, i);_x000D_
    });_x000D_
}_x000D_
/** Matrix functions. */_x000D_
function formatMatrix(matrix) {_x000D_
    return matrix.reduce(function (result, row) {_x000D_
        return result + row.join('\t') + '\n';_x000D_
    }, '');_x000D_
}_x000D_
function copy(matrix) {  _x000D_
    return zeroFill(matrix.length).map(function(r, i) {_x000D_
        return zeroFill(getMatrixWidth(matrix)).map(function(c, j) {_x000D_
            return matrix[i][j];_x000D_
        });_x000D_
    });_x000D_
}_x000D_
function transpose(matrix) {  _x000D_
    return zeroFill(getMatrixWidth(matrix)).map(function(r, i) {_x000D_
        return zeroFill(matrix.length).map(function(c, j) {_x000D_
            return matrix[j][i];_x000D_
        });_x000D_
    });_x000D_
}_x000D_
function getMatrixWidth(matrix) {_x000D_
    return matrix.reduce(function (result, row) {_x000D_
        return Math.max(result, row.length);_x000D_
    }, 0);_x000D_
}_x000D_
/** Array fill functions. */_x000D_
function zeroFill(n) {_x000D_
  return new Array(n+1).join('0').split('').map(Number);_x000D_
}_x000D_
function arrayFill(n, defaultValue) {_x000D_
    return zeroFill(n).map(function(value) {_x000D_
        return defaultValue || value;_x000D_
    });_x000D_
}_x000D_
/** Print functions. */_x000D_
function print(str) {_x000D_
    str = Array.isArray(str) ? str.join(' ') : str;_x000D_
    return document.getElementById('out').innerHTML += str || '';_x000D_
}_x000D_
function println(str) {_x000D_
    print.call(null, [].slice.call(arguments, 0).concat(['<br />']));_x000D_
}
_x000D_
#out {_x000D_
    white-space: pre;_x000D_
}
_x000D_
<div id="out"></div>
_x000D_
_x000D_
_x000D_

Build fails with "Command failed with a nonzero exit code"

What was causing these errors for me (I was getting 8+ for some of my cocoapods) was fixing any runtime build issues in all the pods.

Maven with Eclipse Juno

All the info you need, is provided in the release announcement for m2e 1.1:

m2e 1.1 has been released as part of Eclipse Juno simultaneous release today.

[...]

m2e 1.1 is already included in "Eclipse IDE for Java Developers" package available from http://eclipse.org/downloads/ or it can be installed from Eclipse Juno release repository [2]. Eclipse 3.7/Indigo users can install the new version from m2e release repository [3]

[...]

[2] http://download.eclipse.org/releases/juno

[3] http://download.eclipse.org/technology/m2e/releases

What is copy-on-write?

Copy-on-write is a technique to reduce the memory usage of resource copies using deferred copy. The resource copies are initially virtual (i.e. they share memory) and only become real (i.e. they have their own memory) on the first write operation, hence the name ‘copy-on-write’.

Here after is a Python implementation of the copy-on-write technique using the proxy design pattern. A ValueProxy object (the proxy) implements the copy-on-write technique by:

  • having an attribute bound to an immutable Value object (the subject);
  • translating copy requests to the creation of a new ValueProxy object sharing the same subject attribute as the original ValueProxy object;
  • forwarding read requests to the subject attribute;
  • translating write requests to the creation of a new immutable Value object with the new state and the rebinding of the subject attribute to this new immutable Value object.
import abc

class BaseValue(abc.ABC):
    @abc.abstractmethod
    def read(self):
        raise NotImplementedError
    @abc.abstractmethod
    def write(self, data):
        raise NotImplementedError

class Value(BaseValue):
    def __init__(self, data):
        self.data = data
    def read(self):
        return self.data
    def write(self, data):
        pass

class ValueProxy(BaseValue):
    def __init__(self, subject):
        self.subject = subject
    def read(self):
        return self.subject.read()
    def write(self, data):
        self.subject = Value(data)
    def clone(self):
        return ValueProxy(self.subject)

v1 = ValueProxy(Value('foo'))
v2 = v1.clone()  # shares the immutable Value object between the copies
assert v1.subject is v2.subject
v2.write('bar')  # creates a new immutable Value object with the new state
assert v1.subject is not v2.subject

Using Server.MapPath in external C# Classes in ASP.NET

System.Reflection.Assembly.GetAssembly(type).Location

IF the file you are trying to get is the assembly location for a type. But if the files are relative to the assembly location then you can use this with System.IO namespace to get the exact path of the file.

_DEBUG vs NDEBUG

The macro NDEBUG controls whether assert() statements are active or not.

In my view, that is separate from any other debugging - so I use something other than NDEBUG to control debugging information in the program. What I use varies, depending on the framework I'm working with; different systems have different enabling macros, and I use whatever is appropriate.

If there is no framework, I'd use a name without a leading underscore; those tend to be reserved to 'the implementation' and I try to avoid problems with name collisions - doubly so when the name is a macro.

How do I measure execution time of a command on the Windows command line?

The following script emulates *nix epoch time, but it is local and regional. It should handle calender edge cases including leap years. If Cygwin is available, epoch values can be compared by specifying the Cygwin option.

I'm in EST and the difference reported is 4 hours which is relatively correct. There are some interesting solutions to remove the TZ and regional dependencies, but nothing trivial that I noticed.

@ECHO off
SETLOCAL EnableDelayedExpansion

::
::  Emulates local epoch seconds
::

:: Call passing local date and time
CALL :SECONDS "%DATE%" "%TIME%"
IF !SECONDS! LEQ 0 GOTO END

:: Not testing - print and exit
IF NOT "%~1"=="cygwin" (
    ECHO !SECONDS!
    GOTO END
)

:: Call on Cygwin to get epoch time
FOR /F %%c IN ('C:\cygwin\bin\date +%%s') DO SET EPOCH=%%c

:: Show the results
ECHO Local Seconds: !SECONDS!
ECHO Epoch Seconds: !EPOCH!

:: Calculate difference between script and Cygwin
SET /A HOURS=(!EPOCH!-!SECONDS!)/3600
SET /A FRAC=(!EPOCH!-!SECONDS!)%%3600

:: Delta hours shown reflect TZ
ECHO Delta Hours: !HOURS! Remainder: !FRAC!

GOTO END

:SECONDS
SETLOCAL  EnableDelayedExpansion

    :: Expecting values from caller
    SET DATE=%~1
    SET TIME=%~2

    :: Emulate Unix epoch time without considering TZ
    SET "SINCE_YEAR=1970"

    :: Regional constraint! Expecting date and time in the following formats:
    ::   Sun 03/08/2015   Day MM/DD/YYYY
    ::   20:04:53.64         HH:MM:SS
    SET VALID_DATE=0
    ECHO !DATE! | FINDSTR /R /C:"^... [0-9 ][0-9]/[0-9 ][0-9]/[0-9][0-9][0-9][0-9]" > nul && SET VALID_DATE=1
    SET VALID_TIME=0
    ECHO !TIME! | FINDSTR /R /C:"^[0-9 ][0-9]:[0-9 ][0-9]:[0-9 ][0-9]" > nul && SET VALID_TIME=1
    IF NOT "!VALID_DATE!!VALID_TIME!"=="11" (
        IF !VALID_DATE! EQU 0  ECHO Unsupported Date value: !DATE! 1>&2
        IF !VALID_TIME! EQU 0  ECHO Unsupported Time value: !TIME! 1>&2
        SET SECONDS=0
        GOTO SECONDS_END
    )

    :: Parse values
    SET "YYYY=!DATE:~10,4!"
    SET "MM=!DATE:~4,2!"
    SET "DD=!DATE:~7,2!"
    SET "HH=!TIME:~0,2!"
    SET "NN=!TIME:~3,2!"
    SET "SS=!TIME:~6,2!"
    SET /A YEARS=!YYYY!-!SINCE_YEAR!
    SET /A DAYS=!YEARS!*365

    :: Bump year if after February  - want leading zeroes for this test
    IF "!MM!!DD!" GEQ "0301" SET /A YEARS+=1

    :: Remove leading zeros that can cause octet probs for SET /A
    FOR %%r IN (MM,DD,HH,NN,SS) DO (
        SET "v=%%r"
        SET "t=!%%r!"
        SET /A N=!t:~0,1!0
        IF 0 EQU !N! SET "!v!=!t:~1!"
    )

    :: Increase days according to number of leap years
    SET /A DAYS+=(!YEARS!+3)/4-(!SINCE_YEAR!%%4+3)/4

    :: Increase days by preceding months of current year
    FOR %%n IN (31:1,28:2,31:3,30:4,31:5,30:6,31:7,31:8,30:9,31:10,30:11) DO (
        SET "n=%%n"
        IF !MM! GTR !n:~3! SET /A DAYS+=!n:~0,2!
    )

    :: Multiply and add it all together
    SET /A SECONDS=(!DAYS!+!DD!-1)*86400+!HH!*3600+!NN!*60+!SS!

:SECONDS_END
ENDLOCAL & SET "SECONDS=%SECONDS%"
GOTO :EOF

:END
ENDLOCAL

Rendering HTML elements to <canvas>

RasterizeHTML is a very good project, but if you need to access the canvas it wont work on chrome. due to the use of <foreignObject>.

If you need to access the canvas then you can use html2canvas

I am trying to find another project as html2canvas is very slow in performance

Plot two histograms on single chart with matplotlib

You should use bins from the values returned by hist:

import numpy as np
import matplotlib.pyplot as plt

foo = np.random.normal(loc=1, size=100) # a normal distribution
bar = np.random.normal(loc=-1, size=10000) # a normal distribution

_, bins, _ = plt.hist(foo, bins=50, range=[-6, 6], normed=True)
_ = plt.hist(bar, bins=bins, alpha=0.5, normed=True)

Two matplotlib histograms with same binning

Could not resolve Spring property placeholder

You may have more than one org.springframework.beans.factory.config.PropertyPlaceholderConfigurer in your application. Try setting a breakpoint on the setLocations method of the superclass and see if it's called more than once at application startup. If there is more than one org.springframework.beans.factory.config.PropertyPlaceholderConfigurer, you might need to look at configuring the ignoreUnresolvablePlaceholders property so that your application will start up cleanly.

What is the maximum value for an int32?

Well, it has 32 bits and hence can store 2^32 different values. Half of those are negative.

The solution is 2,147,483,647

And the lowest is -2,147,483,648.

(Notice that there is one more negative value.)

Pandas read_csv from url

The problem you're having is that the output you get into the variable 's' is not a csv, but a html file. In order to get the raw csv, you have to modify the url to:

'https://raw.githubusercontent.com/cs109/2014_data/master/countries.csv'

Your second problem is that read_csv expects a file name, we can solve this by using StringIO from io module. Third problem is that request.get(url).content delivers a byte stream, we can solve this using the request.get(url).text instead.

End result is this code:

from io import StringIO

import pandas as pd
import requests
url='https://raw.githubusercontent.com/cs109/2014_data/master/countries.csv'
s=requests.get(url).text

c=pd.read_csv(StringIO(s))

output:

>>> c.head()
    Country  Region
0   Algeria  AFRICA
1    Angola  AFRICA
2     Benin  AFRICA
3  Botswana  AFRICA
4   Burkina  AFRICA

How to call window.alert("message"); from C#?

It's a bit hard to give a definitive answer without a bit more information, but one usual way is to register a startup script:

try
{
  ...
}
catch(ApplicationException ex){
  Page.ClientScript.RegisterStartupScript(this.GetType(),"ErrorAlert","alert('Some text here - maybe ex.Message');",true);
}

Convert character to ASCII code in JavaScript

JavaScript stores strings as UTF-16 (double byte) so if you want to ignore the second byte just strip it out with a bitwise & operator on 0000000011111111 (ie 255):

'a'.charCodeAt(0) & 255 === 97; // because 'a' = 97 0 
'b'.charCodeAt(0) & 255 === 98; // because 'b' = 98 0 
'?'.charCodeAt(0) & 255 === 19; // because '?' = 19 39

How to add header data in XMLHttpRequest when using formdata?

Check to see if the key-value pair is actually showing up in the request:

In Chrome, found somewhere like: F12: Developer Tools > Network Tab > Whatever request you have sent > "view source" under Response Headers

Depending on your testing workflow, if whatever pair you added isn't there, you may just need to clear your browser cache. To verify that your browser is using your most up-to-date code, you can check the page's sources, in Chrome this is found somewhere like: F12: Developer Tools > Sources Tab > YourJavascriptSrc.js and check your code.

But as other answers have said:

xhttp.setRequestHeader(key, value);

should add a key-value pair to your request header, just make sure to place it after your open() and before your send()

Using Environment Variables with Vue.js

  1. Create two files in root folder (near by package.json) .env and .env.production
  2. Add variables to theese files with prefix VUE_APP_ eg: VUE_APP_WHATEVERYOUWANT
  3. serve uses .env and build uses .env.production
  4. In your components (vue or js), use process.env.VUE_APP_WHATEVERYOUWANT to call value
  5. Don't forget to restart serve if it is currently running
  6. Clear browser cache

Be sure you are using vue-cli version 3 or above

For more information: https://cli.vuejs.org/guide/mode-and-env.html

ASP.NET Identity DbContext confusion

If you drill down through the abstractions of the IdentityDbContext you'll find that it looks just like your derived DbContext. The easiest route is Olav's answer, but if you want more control over what's getting created and a little less dependency on the Identity packages have a look at my question and answer here. There's a code example if you follow the link, but in summary you just add the required DbSets to your own DbContext subclass.

How to run an EXE file in PowerShell with parameters with spaces and quotes

I tried all of the suggestions but was still unable to run msiexec.exe with parameters that contained spaces. So my solution ended up using System.Diagnostics.ProcessStartInfo:

# can have spaces here, no problems
$settings = @{
  CONNECTION_STRING = "... ..."
  ENTITY_CONTEXT = "... ..."
  URL = "..."
}

$settingsJoined = ($settings.Keys | % { "$_=""$($settings[$_])""" }) -join " "
$pinfo = New-Object System.Diagnostics.ProcessStartInfo
$pinfo.WorkingDirectory = $ScriptDirectory
$pinfo.FileName = "msiexec.exe"
$pinfo.RedirectStandardError = $true
$pinfo.RedirectStandardOutput = $true
$pinfo.UseShellExecute = $false
$pinfo.Arguments = "/l* install.log /i installer.msi $settingsJoined"
$p = New-Object System.Diagnostics.Process
$p.StartInfo = $pinfo
$p.Start() | Out-Null
$p.WaitForExit()
$stdout = $p.StandardOutput.ReadToEnd()

Decrementing for loops

for i in range(10,0,-1):
    print i,

The range() function will include the first value and exclude the second.

How to get the first word of a sentence in PHP?

You could do

echo current(explode(' ',$myvalue));

Closing a Userform with Unload Me doesn't work

Without seeing your full code, this is impossible to answer with any certainty. The error usually occurs when you are trying to unload a control rather than the form.

Make sure that you don't have the "me" in brackets.

Also if you can post the full code for the userform it would help massively.

Foreach loop, determine which is the last iteration of the loop

Just store the previous value and work with it inside the loop. Then at the end the 'previous' value will be the last item, letting you handle it differently. No counting or special libraries required.

bool empty = true;
Item previousItem;

foreach (Item result in Model.Results)
{
    if (!empty)
    {
        // We know this isn't the last item because it came from the previous iteration
        handleRegularItem(previousItem);
    }

    previousItem = result;
    empty = false;
}

if (!empty)
{
    // We know this is the last item because the loop is finished
    handleLastItem(previousItem);
}

Skip the headers when editing a csv file using Python

Another way of solving this is to use the DictReader class, which "skips" the header row and uses it to allowed named indexing.

Given "foo.csv" as follows:

FirstColumn,SecondColumn
asdf,1234
qwer,5678

Use DictReader like this:

import csv
with open('foo.csv') as f:
    reader = csv.DictReader(f, delimiter=',')
    for row in reader:
        print(row['FirstColumn'])  # Access by column header instead of column number
        print(row['SecondColumn'])

MySQL - Replace Character in Columns

Replace below characters

~ ! @ # $ % ^ & * ( ) _ +
` - = 
{ } |
[ ] \
: " 
; '

< > ?
, . 

with this SQL

SELECT note as note_original, 

    REPLACE(
        REPLACE(
            REPLACE(
                REPLACE(
                    REPLACE(
                        REPLACE(
                            REPLACE(
                                REPLACE(
                                    REPLACE(
                                        REPLACE(
                                            REPLACE(
                                                REPLACE(
                                                    REPLACE(
                                                        REPLACE(
                                                            REPLACE(
                                                                REPLACE(
                                                                    REPLACE(
                                                                        REPLACE(
                                                                            REPLACE(
                                                                                REPLACE(
                                                                                    REPLACE(
                                                                                        REPLACE(
                                                                                            REPLACE(
                                                                                                REPLACE(
                                                                                                    REPLACE(
                                                                                                        REPLACE(
                                                                    REPLACE(
                                                                        REPLACE(
                                                                            REPLACE(
                                                                                REPLACE(
                                                                                    REPLACE(
                                                                                        REPLACE(
                                                                                            REPLACE(note, '\"', ''),
                                                                                        '.', ''),
                                                                                    '?', ''),
                                                                                '`', ''),
                                                                            '<', ''),
                                                                        '=', ''),
                                                                    '{', ''),
                                                                                                        '}', ''),
                                                                                                    '[', ''),
                                                                                                ']', ''),
                                                                                            '|', ''),
                                                                                        '\'', ''),
                                                                                    ':', ''),
                                                                                ';', ''),
                                                                            '~', ''),
                                                                        '!', ''),
                                                                    '@', ''),
                                                                '#', ''),
                                                            '$', ''),
                                                        '%', ''),
                                                    '^', ''),
                                                '&', ''),
                                            '*', ''),
                                        '_', ''),
                                    '+', ''),
                                ',', ''),
                            '/', ''),
                        '(', ''),
                    ')', ''),
                '-', ''),
            '>', ''),
        ' ', '-'),
    '--', '-') as note_changed FROM invheader

Checking Value of Radio Button Group via JavaScript?

If you are using a javascript library like jQuery, it's very easy:

alert($('input[name=gender]:checked').val());

This code will select the checked input with gender name, and gets it's value. Simple isn't it?

Live demo

CSS pseudo elements in React

Inline styles cannot be used to target pseudo-classes or pseudo-elements. You need to use a stylesheet.

If you want to generate CSS dynamically, then the easiest way is to create a DOM element <style>.

<style dangerouslySetInnerHTML={{
  __html: [
     '.my-special-div:after {',
     '  content: "Hello";',
     '  position: absolute',
     '}'
    ].join('\n')
  }}>
</style>
<div className='my-special-div'></div>

Can't install any packages in Node.js using "npm install"

This error might also occur due to proxy settings, once check that your proxy allow the access to npm commands.

It worked for me quite well.

C# Telnet Library

I am currently evaluating two .NET (v2.0) C# Telnet libraries that may be of interest:

Hope this helps.

Regards, Andy.

HTML5 Audio Looping

Your code works for me on Chrome (5.0.375), and Safari (5.0). Doesn't loop on Firefox (3.6).

See example.

var song = new Audio("file");
song.loop = true;
document.body.appendChild(song);?

Filter object properties by key in ES6

You can now make it shorter and simpler by using the Object.fromEntries method (check browser support):

const raw = { item1: { prop:'1' }, item2: { prop:'2' }, item3: { prop:'3' } };

const allowed = ['item1', 'item3'];

const filtered = Object.fromEntries(
   Object.entries(raw).filter(
      ([key, val])=>allowed.includes(key)
   )
);

read more about: Object.fromEntries

Android Material: Status bar color won't change

While colouring the status bar is not supported <5.0, on 4.4 you can use a work around to achieve a darker colour:

Make the status bar translucent

<item name="android:windowTranslucentStatus">true</item>

Then use AppCompat's Toolbar for your appbar, making sure that it fits system windows:

<android.support.v7.widget.Toolbar
    android:id="@+id/toolbar"
    ...
    android:fitsSystemWindows="true"/>

Make sure to set your toolbar as your activity's toolbar:

protected void onCreate(final Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    ...
    toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

The toolbar stretches underneath the status bar, and the semi translucency of the status bar makes it appear to be a darker secondary colour. If that's not the colour you want, this combination allows you to fit a view underneath your status bar sporting the background colour of your choice (though it's still tinted darker by the status bar).

Kind of an edge case workaround due to 4.4 only, but there ya go.

C# Lambda expressions: Why should I use them?

The innovation is in the type safety and transparency. Although you don't declare types of lambda expressions, they are inferred, and can be used by code search, static analysis, refactoring tools, and runtime reflection.

For example, before you might have used SQL and could get an SQL injection attack, because a hacker passed a string where a number was normally expected. Now you would use a LINQ lambda expression, which is protected from that.

Building a LINQ API on pure delegates is not possible, because it requires combining expression trees together before evaluating them.

In 2016 most of the popular languages have lambda expression support, and C# was one of the pioneers in this evolution among the mainstream imperative languages.

Is there a unique Android device ID?

It's a simple question, with no simple answer.

More over, all of the existing answers here are whether out of date or unreliable.

So if you're searching for a solution in 2020.

Here are a few things to take in mind:

All the hardware based identifiers (SSAID, IMEI, MAC, etc) are unreliable for non-google's devices (Everything except Pixels and Nexuses), which are more than 50% of active devices worldwide. Therefore official Android identifiers best practices clearly states:

Avoid using hardware identifiers, such as SSAID (Android ID), IMEI, MAC address, etc...

That makes most of the answers above invalid. Also due to different android security updates, some of them require newer and stricter runtime permissions, which can be simply denied by user.

As example CVE-2018-9489 which affects all the WIFI based techniques mentioned above.

That makes those identifiers not only unreliable, but also unaccessible in many cases.

So in simpler words: don't use those techniques.

Many other answers here are suggesting to use the AdvertisingIdClient, which is also incompatible, as its by design should be used only for ads profiling. It's also stated in the official reference

Only use an Advertising ID for user profiling or ads use cases

It's not only unreliable for device identification, but you also must follow the user privacy regarding ad tracking policy, which states clearly that user can reset or block it at any moment.

So don't use it either.

Since you cannot have the desired static globally unique and reliable device identifier. Android's official reference suggest:

Use a FirebaseInstanceId or a privately stored GUID whenever possible for all other use cases, except for payment fraud prevention and telephony.

It's unique for the application installation on the device, so when the user uninstall the app - it's wiped out, so it's not 100% reliable, but it's the next best thing.

To use FirebaseInstanceId add the latest firebase-messaging dependency into your gradle

implementation 'com.google.firebase:firebase-messaging:20.2.4'

And use the code below in a background thread:

String reliableIdentifier = FirebaseInstanceId.getInstance().getId();

If you need to store the device identification on your remote server, then don't store it as is (plain text), but a hash with salt.

Today it's not only a best practice, you actually must to do it by law according to GDPR - identifiers and similar regulations.

AngularJS access parent scope from child controller

From a child component you can access the properties and methods of the parent component with 'require'. Here is an example:

Parent:

.component('myParent', mymodule.MyParentComponent)
...
controllerAs: 'vm',
...
var vm = this;
vm.parentProperty = 'hello from parent';

Child:

require: {
    myParentCtrl: '^myParent'
},
controllerAs: 'vm',
...
var vm = this;
vm.myParentCtrl.parentProperty = 'hello from child';

In Python How can I declare a Dynamic Array

In python, A dynamic array is an 'array' from the array module. E.g.

from array import array
x = array('d')          #'d' denotes an array of type double
x.append(1.1)
x.append(2.2)
x.pop()                 # returns 2.2

This datatype is essentially a cross between the built-in 'list' type and the numpy 'ndarray' type. Like an ndarray, elements in arrays are C types, specified at initialization. They are not pointers to python objects; this may help avoid some misuse and semantic errors, and modestly improves performance.

However, this datatype has essentially the same methods as a python list, barring a few string & file conversion methods. It lacks all the extra numerical functionality of an ndarray.

See https://docs.python.org/2/library/array.html for details.

Finding the 'type' of an input element

Check the type property. Would that suffice?

htons() function in socket programing

the htons() function converts values between host and network byte orders. There is a difference between big-endian and little-endian and network byte order depending on your machine and network protocol in use.

Generate Java classes from .XSD files...?

Isn't JAXB's XJC is a possible answer to this? I'm trying to achieve the same thing. Still in the "trying" phase though. Came across XJC, so thought of sharing.

What does [object Object] mean? (JavaScript)

Alerts aren't the best for displaying objects. Try console.log? If you still see Object Object in the console, use JSON.parse like this > var obj = JSON.parse(yourObject); console.log(obj)

C - gettimeofday for computing time?

No. gettimeofday should NEVER be used to measure time.

This is causing bugs all over the place. Please don't add more bugs.

How do I sort a vector of pairs based on the second element of the pair?

EDIT: using c++14, the best solution is very easy to write thanks to lambdas that can now have parameters of type auto. This is my current favorite solution

std::sort(v.begin(), v.end(), [](auto &left, auto &right) {
    return left.second < right.second;
});

Just use a custom comparator (it's an optional 3rd argument to std::sort)

struct sort_pred {
    bool operator()(const std::pair<int,int> &left, const std::pair<int,int> &right) {
        return left.second < right.second;
    }
};

std::sort(v.begin(), v.end(), sort_pred());

If you're using a C++11 compiler, you can write the same using lambdas:

std::sort(v.begin(), v.end(), [](const std::pair<int,int> &left, const std::pair<int,int> &right) {
    return left.second < right.second;
});

EDIT: in response to your edits to your question, here's some thoughts ... if you really wanna be creative and be able to reuse this concept a lot, just make a template:

template <class T1, class T2, class Pred = std::less<T2> >
struct sort_pair_second {
    bool operator()(const std::pair<T1,T2>&left, const std::pair<T1,T2>&right) {
        Pred p;
        return p(left.second, right.second);
    }
};

then you can do this too:

std::sort(v.begin(), v.end(), sort_pair_second<int, int>());

or even

std::sort(v.begin(), v.end(), sort_pair_second<int, int, std::greater<int> >());

Though to be honest, this is all a bit overkill, just write the 3 line function and be done with it :-P

Java: object to byte[] and byte[] to object converter (for Tokyo Cabinet)

You can look at how Hector does this for Cassandra, where the goal is the same - convert everything to and from byte[] in order to store/retrieve from a NoSQL database - see here. For the primitive types (+String), there are special Serializers, otherwise there is the generic ObjectSerializer (expecting Serializable, and using ObjectOutputStream). You can, of course, use only it for everything, but there might be redundant meta-data in the serialized form.

I guess you can copy the entire package and make use of it.

How to increase timeout for a single test case in mocha

From command line:

mocha -t 100000 test.js

How to pass in a react component into another react component to transclude the first component's content?

You can pass in a component via. the props and render it with interpolation.

var DivWrapper = React.createClass({
    render: function() {
        return <div>{ this.props.child }</div>;
    }
});

You would then pass in a prop called child, which would be a React component.

How to prevent errno 32 broken pipe?

It depends on how you tested it, and possibly on differences in the TCP stack implementation of the personal computer and the server.

For example, if your sendall always completes immediately (or very quickly) on the personal computer, the connection may simply never have broken during sending. This is very likely if your browser is running on the same machine (since there is no real network latency).


In general, you just need to handle the case where a client disconnects before you're finished, by handling the exception.

Remember that TCP communications are asynchronous, but this is much more obvious on physically remote connections than on local ones, so conditions like this can be hard to reproduce on a local workstation. Specifically, loopback connections on a single machine are often almost synchronous.

new Date() is working in Chrome but not Firefox

If you still want to create date using dashes, you can use this format:

var date = new Date('2013-08-31T17:00:00Z')

But bear in mind, that it creates time according to UTC. Meaning, if you live in GMT+3 (3 hours ahead of GMT) timezone, it will add this timezone offset to the time. So the above example will have this value, if GMT+3 (note that it is hour 20:00 and not 17:00):

Sat Aug 31 2013 20:00:00 GMT+0300 (FLE Standard Time)

Be sure to add 'Z' letter at the end, because otherwise Chrome and Firefox will parse the string differently (one will add time offset and the other won't).

How to watch for a route change in AngularJS?

Note: This is a proper answer for a legacy version of AngularJS. See this question for updated versions.

$scope.$on('$routeChangeStart', function($event, next, current) { 
   // ... you could trigger something here ...
 });

The following events are also available (their callback functions take different arguments):

  • $routeChangeSuccess
  • $routeChangeError
  • $routeUpdate - if reloadOnSearch property has been set to false

See the $route docs.

There are two other undocumented events:

  • $locationChangeStart
  • $locationChangeSuccess

See What's the difference between $locationChangeSuccess and $locationChangeStart?

Select rows with same id but different value in another column

Select A.ARIDNR,A.LIEFNR
from Table A
join Table B
on A.ARIDNR = B.ARIDNR
and A.LIEFNR<> B.LIEFNR
group by A.ARIDNR,A.LIEFNR

How to fix symbol lookup error: undefined symbol errors in a cluster environment

After two dozens of comments to understand the situation, it was found that the libhdf5.so.7 was actually a symlink (with several levels of indirection) to a file that was not shared between the queued processes and the interactive processes. This means even though the symlink itself lies on a shared filesystem, the contents of the file do not and as a result the process was seeing different versions of the library.

For future reference: other than checking LD_LIBRARY_PATH, it's always a good idea to check a library with nm -D to see if the symbols actually exist. In this case it was found that they do exist in interactive mode but not when run in the queue. A quick md5sum revealed that the files were actually different.

Simple linked list in C++

The addNode function needs to be able to change head. As it's written now simply changes the local variable head (a parameter).

Changing the code to

void addNode(struct Node *& head, int n){
    ...
}

would solve this problem because now the head parameter is passed by reference and the called function can mutate it.

How to launch a Google Chrome Tab with specific URL using C#

If the user doesn't have Chrome, it will throw an exception like this:

    //chrome.exe http://xxx.xxx.xxx --incognito
    //chrome.exe http://xxx.xxx.xxx -incognito
    //chrome.exe --incognito http://xxx.xxx.xxx
    //chrome.exe -incognito http://xxx.xxx.xxx
    private static void Chrome(string link)
    {
        string url = "";

        if (!string.IsNullOrEmpty(link)) //if empty just run the browser
        {
            if (link.Contains('.')) //check if it's an url or a google search
            {
                url = link;
            }
            else
            {
                url = "https://www.google.com/search?q=" + link.Replace(" ", "+");
            }
        }

        try
        {
            Process.Start("chrome.exe", url + " --incognito");
        }
        catch (System.ComponentModel.Win32Exception e)
        {
            MessageBox.Show("Unable to find Google Chrome...",
                "chrome.exe not found!", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
    }

How can I list all foreign keys referencing a given table in SQL Server?

I have been using this on 2008 and up. It's similar to some other solutions listed but, the field names are proper cased to handle case specific (LatBin) collations. Additionally, you can feed it a single table name and retrieve just the info for that table.

-->>SPECIFY THE DESIRED DB
USE ???
GO

/*********************************************************************************************

    LIST OUT ALL PRIMARY AND FOREIGN KEY CONSTRAINTS IN A DB OR FOR A SPECIFIED TABLE

*********************************************************************************************/
DECLARE @tblName VARCHAR(255) 

/*******************/

    SET @tblName = NULL-->NULL will return all PK/FK constraints for every table in the database

/*******************/

SELECT PKTABLE_QUALIFIER = CONVERT(SYSNAME,DB_NAME()), 
       PKTABLE_OWNER = CONVERT(SYSNAME,SCHEMA_NAME(O1.schema_id)), 
       PKTABLE_NAME = CONVERT(SYSNAME,O1.name), 
       PKCOLUMN_NAME = CONVERT(SYSNAME,C1.name), 
       FKTABLE_QUALIFIER = CONVERT(SYSNAME,DB_NAME()), 
       FKTABLE_OWNER = CONVERT(SYSNAME,SCHEMA_NAME(O2.schema_id)), 
       FKTABLE_NAME = CONVERT(SYSNAME,O2.name), 
       FKCOLUMN_NAME = CONVERT(SYSNAME,C2.name), 
       -- Force the column to be non-nullable (see SQL BU 325751) 
       KEY_SEQ             = isnull(convert(smallint,K.constraint_column_id),0), 
       UPDATE_RULE = CONVERT(SMALLINT,CASE OBJECTPROPERTY(F.object_id,'CnstIsUpdateCascade')  
                                        WHEN 1 THEN 0 
                                        ELSE 1 
                                      END), 
       DELETE_RULE = CONVERT(SMALLINT,CASE OBJECTPROPERTY(F.object_id,'CnstIsDeleteCascade')  
                                        WHEN 1 THEN 0 
                                        ELSE 1 
                                      END), 
       FK_NAME = CONVERT(SYSNAME,OBJECT_NAME(F.object_id)), 
       PK_NAME = CONVERT(SYSNAME,I.name), 
       DEFERRABILITY = CONVERT(SMALLINT,7)   -- SQL_NOT_DEFERRABLE 
FROM   sys.all_objects O1, 
       sys.all_objects O2, 
       sys.all_columns C1, 
       sys.all_columns C2, 
       sys.foreign_keys F 
       INNER JOIN sys.foreign_key_columns K 
         ON (K.constraint_object_id = F.object_id) 
       INNER JOIN sys.indexes I 
         ON (F.referenced_object_id = I.object_id 
             AND F.key_index_id = I.index_id) 
WHERE  O1.object_id = F.referenced_object_id 
       AND O2.object_id = F.parent_object_id 
       AND C1.object_id = F.referenced_object_id 
       AND C2.object_id = F.parent_object_id 
       AND C1.column_id = K.referenced_column_id
       AND C2.column_id = K.parent_column_id
       AND (   O1.name = @tblName 
            OR O2.name = @tblName
            OR @tblName IS null)
ORDER BY PKTABLE_NAME,FKTABLE_NAME

Create a temporary table in MySQL with an index from a select

Did find the answer on my own. My problem was, that i use two temporary tables for a join and create the second one out of the first one. But the Index was not copied during creation...

CREATE TEMPORARY TABLE tmpLivecheck (tmpid INTEGER NOT NULL AUTO_INCREMENT, PRIMARY    
KEY(tmpid), INDEX(tmpid))
SELECT * FROM tblLivecheck_copy WHERE tblLivecheck_copy.devId = did;

CREATE TEMPORARY TABLE tmpLiveCheck2 (tmpid INTEGER NOT NULL, PRIMARY KEY(tmpid), 
INDEX(tmpid))  
SELECT * FROM tmpLivecheck;

... solved my problem.

Greetings...

Onclick javascript to make browser go back to previous page?

window.history.back();

<button onclick="goBack()">Go Back</button>

<script>
function goBack() {
    window.history.back();
}
</script>

Oracle - how to remove white spaces?

Use the following to insure there is no whitespace in your output:

select first_name || ',' || last_name from table x;

Output

John,Smith

Jane,Doe

Why does AngularJS include an empty option in select?

i had the same problem, i (removed "ng-model") changed this :

<select ng-model="mapayear" id="mapayear" name="mapayear" style="  display:inline-block !important;  max-width: 20%;" class="form-control">
  <option id="removable" hidden> Selecione u </option>
    <option selected ng-repeat="x in anos" value="{{ x.ano }}">{{ x.ano }}
</option>
</select>

to this:

<select id="mapayear" name="mapayear" style="  display:inline-block !important;  max-width: 20%;" class="form-control">
  <option id="removable" hidden> Selecione u </option>
    <option selected ng-repeat="x in anos" value="{{ x.ano }}">{{ x.ano }}
</option>
</select>

now its working, but in my case it was cause ive deleted that scope from ng.controller, check if u didn't do the same.

Numpy `ValueError: operands could not be broadcast together with shape ...`

If X and beta do not have the same shape as the second term in the rhs of your last line (i.e. nsample), then you will get this type of error. To add an array to a tuple of arrays, they all must be the same shape.

I would recommend looking at the numpy broadcasting rules.

Classpath resource not found when running as jar

I was facing same error

InputStream inputStream = new ClassPathResource("filename.ext").inputStream();

this should solve FileNotFoundException while running

How can I get the current contents of an element in webdriver

My answer is based on this answer: How can I get the current contents of an element in webdriver just more like copy-paste.

from selenium import webdriver

driver = webdriver.Firefox()
driver.get('http://www.w3c.org')
element = driver.find_element_by_name('q')
element.send_keys('hi mom')

element_text = element.text
element_attribute_value = element.get_attribute('value')

print (element)
print ('element.text: {0}'.format(element_text))
print ('element.get_attribute(\'value\'): {0}'.format(element_attribute_value))


element = driver.find_element_by_css_selector('.description.expand_description > p')
element_text = element.text
element_attribute_value = element.get_attribute('value')

print (element)
print ('element.text: {0}'.format(element_text))
print ('element.get_attribute(\'value\'): {0}'.format(element_attribute_value))
driver.quit()

Unexpected 'else' in "else" error

I would suggest to read up a bit on the syntax. See here.

if (dsnt<0.05) {
  wilcox.test(distance[result=='nt'],distance[result=='t'],alternative=c("two.sided"),paired=TRUE) 
} else if (dst<0.05) {
    wilcox.test(distance[result=='nt'],distance[result=='t'],alternative=c("two.sided"),paired=TRUE)
} else 
  t.test(distance[result=='nt'],distance[result=='t'],alternative=c("two.sided"),paired=TRUE)

How can I find the number of days between two Date objects in Ruby?

Well, take care of what you mean by "between" too...

days_apart = (to - from).to_i     # from + days_apart = to
total_days = (to - from).to_i + 1 # number of "selected" days
in_between_days = (to - from).to_i - 1 # how many days are in between from and to, i.e. excluding those two days

How to preview selected image in input type="file" in popup using jQuery?

Just check my scripts it's working well:

  function handleFileSelect(evt) {
    var files = evt.target.files; // FileList object

    // Loop through the FileList and render image files as thumbnails.
    for (var i = 0, f; f = files[i]; i++) {

      // Only process image files.
      if (!f.type.match('image.*')) {
        continue;
      }

      var reader = new FileReader();

      // Closure to capture the file information.
      reader.onload = (function(theFile) {
        return function(e) {
          // Render thumbnail.
          var span = document.createElement('span');
          span.innerHTML = ['<img class="thumb" src="', e.target.result,
                            '" title="', escape(theFile.name), '"/>'].join('');
          document.getElementById('list').insertBefore(span, null);
        };
      })(f);

      // Read in the image file as a data URL.
      reader.readAsDataURL(f);
    }
  }

  document.getElementById('files').addEventListener('change', handleFileSelect, false);
#list img{
  width: auto;
  height: 100px;
  margin: 10px ;
}

Get the key corresponding to the minimum value within a dictionary

For the case where you have multiple minimal keys and want to keep it simple

def minimums(some_dict):
    positions = [] # output variable
    min_value = float("inf")
    for k, v in some_dict.items():
        if v == min_value:
            positions.append(k)
        if v < min_value:
            min_value = v
            positions = [] # output variable
            positions.append(k)

    return positions

minimums({'a':1, 'b':2, 'c':-1, 'd':0, 'e':-1})

['e', 'c']

How to Merge Two Eloquent Collections?

$users = User::all();
$associates = Associate::all();

$userAndAssociate = $users->merge($associates);

see if two files have the same content in python

Yes, I think hashing the file would be the best way if you have to compare several files and store hashes for later comparison. As hash can clash, a byte-by-byte comparison may be done depending on the use case.

Generally byte-by-byte comparison would be sufficient and efficient, which filecmp module already does + other things too.

See http://docs.python.org/library/filecmp.html e.g.

>>> import filecmp
>>> filecmp.cmp('file1.txt', 'file1.txt')
True
>>> filecmp.cmp('file1.txt', 'file2.txt')
False

Speed consideration: Usually if only two files have to be compared, hashing them and comparing them would be slower instead of simple byte-by-byte comparison if done efficiently. e.g. code below tries to time hash vs byte-by-byte

Disclaimer: this is not the best way of timing or comparing two algo. and there is need for improvements but it does give rough idea. If you think it should be improved do tell me I will change it.

import random
import string
import hashlib
import time

def getRandText(N):
    return  "".join([random.choice(string.printable) for i in xrange(N)])

N=1000000
randText1 = getRandText(N)
randText2 = getRandText(N)

def cmpHash(text1, text2):
    hash1 = hashlib.md5()
    hash1.update(text1)
    hash1 = hash1.hexdigest()

    hash2 = hashlib.md5()
    hash2.update(text2)
    hash2 = hash2.hexdigest()

    return  hash1 == hash2

def cmpByteByByte(text1, text2):
    return text1 == text2

for cmpFunc in (cmpHash, cmpByteByByte):
    st = time.time()
    for i in range(10):
        cmpFunc(randText1, randText2)
    print cmpFunc.func_name,time.time()-st

and the output is

cmpHash 0.234999895096
cmpByteByByte 0.0

Getting binary (base64) data from HTML5 Canvas (readAsBinaryString)

Seeing how you draw your canvas with

$("canvas").drawImage();

it seems that you use jQuery Canvas (jCanvas) by Caleb Evans. I actually use that plugin and it has a simple way to retrieve canvas base64 image string with $('canvas').getCanvasImage();

Here's a working Fiddle for you: http://jsfiddle.net/e6nqzxpn/

How do I get IntelliJ to recognize common Python modules?

My problem was similar to @Toddarooski 's, except that the module I had, under the "Dependencies" tab, had no SDK listed. I right clicked on 'SDK', picked edit from the drop down menu, and selected my Python SDK. That did the trick.

How to concatenate two strings in SQL Server 2005

I got a easy solution which will select from database table and let you do easily.

SELECT b.FirstName + b.LastName FROM tbl_Users b WHERE b.Id='11'

You can easily add a space there if you try

SELECT b.FirstName +' '+ b.LastName FROM Users b WHERE b.Id='23'

Here you can combine as much as your table have.

Random float number generation

For C++, it can generate real float numbers within the range specified by dist variable

#include <random>  //If it doesnt work then use   #include <tr1/random>
#include <iostream>

using namespace std;

typedef std::tr1::ranlux64_base_01 Myeng; 
typedef std::tr1::normal_distribution<double> Mydist;

int main() { 
       Myeng eng; 
       eng.seed((unsigned int) time(NULL)); //initializing generator to January 1, 1970);
       Mydist dist(1,10); 

       dist.reset(); // discard any cached values 
       for (int i = 0; i < 10; i++)
       {
           std::cout << "a random value == " << (int)dist(eng) << std::endl; 
       }

       return (0);
}

Fatal error: Call to undefined function mysqli_connect()

Late to the conversation...

If you have the module installed and set your PHP.INI file properly, check your apache error log for something like the following:

PHP Warning: PHP Startup: Unable to load dynamic library 'C:\php\ext\php_mysqli.dll' - The specified module could not be found.

In this case, your extension directory is not what you think it is. You may neeed to set it explicitly, like so:

extension_dir="C:\xampp\php\ext"

How to markdown nested list items in Bitbucket?

4 spaces do the trick even inside definition list:

Endpoint
: `/listAgencies`

Method
: `GET`

Arguments
:   * `level` - bla-bla.
    * `withDisabled` - should we include disabled `AGENT`s.
    * `userId` - bla-bla.

I am documenting API using BitBucket Wiki and Markdown proprietary extension for definition list is most pleasing (MD's table syntax is awful, imaging multiline and embedding requirements...).

Error: stray '\240' in program

As mentioned in a previous reply, this generally comes when compiling copy pasted code. If you have a bash shell, the following command generally works:

iconv -f utf-8 -t ascii//translit input.c > output.c

Determine installed PowerShell version

I would use either Get-Host or $PSVersionTable. As Andy Schneider points out, $PSVersionTable doesn't work in version 1; it was introduced in version 2.

get-host

Name             : ConsoleHost
Version          : 2.0
InstanceId       : d730016e-2875-4b57-9cd6-d32c8b71e18a
UI               : System.Management.Automation.Internal.Host.InternalHostUserInterface
CurrentCulture   : en-GB
CurrentUICulture : en-US
PrivateData      : Microsoft.PowerShell.ConsoleHost+ConsoleColorProxy
IsRunspacePushed : False
Runspace         : System.Management.Automation.Runspaces.LocalRunspace

$PSVersionTable

Name                           Value
----                           -----
CLRVersion                     2.0.50727.4200
BuildVersion                   6.0.6002.18111
PSVersion                      2.0
WSManStackVersion              2.0
PSCompatibleVersions           {1.0, 2.0}
SerializationVersion           1.1.0.1
PSRemotingProtocolVersion      2.1

img tag displays wrong orientation

If you have access to Linux, then open a terminal, cd to the directory containing your images and then run

mogrify -auto-orient *

This should permanently fix the orientation issues on all the images.

How to export the Html Tables data into PDF using Jspdf

Just follow these steps i can assure pdf file will be generated

    <html>
    <head>

    <title>Exporting table data to pdf Example</title>


    <script type="text/javascript" src="https://code.jquery.com/jquery-2.1.3.js"></script>
    <script type="text/javascript" src="js/jspdf.js"></script>
    <script type="text/javascript" src="js/from_html.js"></script>
    <script type="text/javascript" src="js/split_text_to_size.js"></script>
    <script type="text/javascript" src="js/standard_fonts_metrics.js"></script>
    <script type="text/javascript" src="js/cell.js"></script>
    <script type="text/javascript" src="js/FileSaver.js"></script>


    <script type="text/javascript">
        $(document).ready(function() {

            $("#exportpdf").click(function() {
                var pdf = new jsPDF('p', 'pt', 'ledger');
                // source can be HTML-formatted string, or a reference
                // to an actual DOM element from which the text will be scraped.
                source = $('#yourTableIdName')[0];

                // we support special element handlers. Register them with jQuery-style 
                // ID selector for either ID or node name. ("#iAmID", "div", "span" etc.)
                // There is no support for any other type of selectors 
                // (class, of compound) at this time.
                specialElementHandlers = {
                    // element with id of "bypass" - jQuery style selector
                    '#bypassme' : function(element, renderer) {
                        // true = "handled elsewhere, bypass text extraction"
                        return true
                    }
                };
                margins = {
                    top : 80,
                    bottom : 60,
                    left : 60,
                    width : 522
                };
                // all coords and widths are in jsPDF instance's declared units
                // 'inches' in this case
                pdf.fromHTML(source, // HTML string or DOM elem ref.
                margins.left, // x coord
                margins.top, { // y coord
                    'width' : margins.width, // max width of content on PDF
                    'elementHandlers' : specialElementHandlers
                },

                function(dispose) {
                    // dispose: object with X, Y of the last line add to the PDF 
                    //          this allow the insertion of new lines after html
                    pdf.save('fileNameOfGeneretedPdf.pdf');
                }, margins);
            });

        });
    </script>
    </head>
    <body>
    <div id="yourTableIdName">
        <table style="width: 1020px;font-size: 12px;" border="1">
            <thead>
                <tr align="left">
                    <th>Country</th>
                    <th>State</th>
                    <th>City</th>
                </tr>
            </thead>


            <tbody>

                <tr align="left">
                    <td>India</td>
                    <td>Telangana</td>
                    <td>Nirmal</td>
                </tr>
<tr align="left">
                    <td>India</td>
                    <td>Telangana</td>
                    <td>Nirmal</td>
                </tr><tr align="left">
                    <td>India</td>
                    <td>Telangana</td>
                    <td>Nirmal</td>
                </tr><tr align="left">
                    <td>India</td>
                    <td>Telangana</td>
                    <td>Nirmal</td>
                </tr><tr align="left">
                    <td>India</td>
                    <td>Telangana</td>
                    <td>Nirmal</td>
                </tr><tr align="left">
                    <td>India</td>
                    <td>Telangana</td>
                    <td>Nirmal</td>
                </tr><tr align="left">
                    <td>India</td>
                    <td>Telangana</td>
                    <td>Nirmal</td>
                </tr>
            </tbody>
        </table></div>

        <input type="button" id="exportpdf" value="Download PDF">


    </body>

    </html>

Output:

Html file output: html output

Pdf file output: pdf output

Excel formula is only showing the formula rather than the value within the cell in Office 2010

Check the formatting (right click on cell, Format Cells). Under tab "Number" the category should be "General". If, for instance, it's "Text" anything typed in would be treated as a string rather than a formula to be interpreted.

What is "with (nolock)" in SQL Server?

I've used to retrieve a "next batch" for things to do. It doesn't matter in this case which exact item, and I have a lot of users running this same query.

LINQ Inner-Join vs Left-Join

Here's a good blog post that's just been posted by Fabrice (author of LINQ in Action) which covers the material in the question that I asked. I'm putting it here for reference as readers of the question will find this useful.

Converting LINQ queries from query syntax to method/operator syntax

What is the difference between tinyint, smallint, mediumint, bigint and int in MySQL?

When it gets to real world usage of these datatypes, it is very important that you understand that using certain integer types could just be an overkill or under used. For example, using integer datatype for employeeCount in a table say employee could be an overkill since it supports a range of integer values from ~ negative 2 billion to positive 2 billion or zero to approximately 4 billion (unsigned). So, even if you consider one of the US biggest employer such as Walmart with roughly about 2.2 million employees using an integer datatype for the employeeCount column would be unnecessary. In such a case you use mediumint (that supports from 0 to 16 million (unsigned)) for example. Having said that if your range is expected to be unusually large you might consider bigint which as you can see from Daniel's notes supports a range larger than I care to decipher.

Get the name of a pandas DataFrame

From here what I understand DataFrames are:

DataFrame is a 2-dimensional labeled data structure with columns of potentially different types. You can think of it like a spreadsheet or SQL table, or a dict of Series objects.

And Series are:

Series is a one-dimensional labeled array capable of holding any data type (integers, strings, floating point numbers, Python objects, etc.).

Series have a name attribute which can be accessed like so:

 In [27]: s = pd.Series(np.random.randn(5), name='something')

 In [28]: s
 Out[28]: 
 0    0.541
 1   -1.175
 2    0.129
 3    0.043
 4   -0.429
 Name: something, dtype: float64

 In [29]: s.name
 Out[29]: 'something'

EDIT: Based on OP's comments, I think OP was looking for something like:

 >>> df = pd.DataFrame(...)
 >>> df.name = 'df' # making a custom attribute that DataFrame doesn't intrinsically have
 >>> print(df.name)
 'df'

How can I check the syntax of Python script without executing it?

Here's another solution, using the ast module:

python -c "import ast; ast.parse(open('programfile').read())"

To do it cleanly from within a Python script:

import ast, traceback

filename = 'programfile'
with open(filename) as f:
    source = f.read()
valid = True
try:
    ast.parse(source)
except SyntaxError:
    valid = False
    traceback.print_exc()  # Remove to silence any errros
print(valid)

How to calculate the sum of all columns of a 2D numpy array (efficiently)

Check out the documentation for numpy.sum, paying particular attention to the axis parameter. To sum over columns:

>>> import numpy as np
>>> a = np.arange(12).reshape(4,3)
>>> a.sum(axis=0)
array([18, 22, 26])

Or, to sum over rows:

>>> a.sum(axis=1)
array([ 3, 12, 21, 30])

Other aggregate functions, like numpy.mean, numpy.cumsum and numpy.std, e.g., also take the axis parameter.

From the Tentative Numpy Tutorial:

Many unary operations, such as computing the sum of all the elements in the array, are implemented as methods of the ndarray class. By default, these operations apply to the array as though it were a list of numbers, regardless of its shape. However, by specifying the axis parameter you can apply an operation along the specified axis of an array:

How can I delete all Git branches which have been merged?

If you are using branching model like HubFlow or GitFlow you can use this command to remove the merged feature branches:

git branch --merged | grep feature.* | grep -v "\*" | xargs -n 1 git branch -d

SQL ROWNUM how to return rows between a specific range

SELECT  *
FROM    (
        SELECT  q.*, rownum rn
        FROM    (
                SELECT  *
                FROM    maps006
                ORDER BY
                        id
                ) q
        )
WHERE   rn BETWEEN 50 AND 100

Note the double nested view. ROWNUM is evaluated before ORDER BY, so it is required for correct numbering.

If you omit ORDER BY clause, you won't get consistent order.

How can I detect if a selector returns null?

I like to use presence, inspired from Ruby on Rails:

$.fn.presence = function () {
    return this.length !== 0 && this;
}

Your example becomes:

alert($('#notAnElement').presence() || "No object found");

I find it superior to the proposed $.fn.exists because you can still use boolean operators or if, but the truthy result is more useful. Another example:

$ul = $elem.find('ul').presence() || $('<ul class="foo">').appendTo($elem)
$ul.append('...')

Do I need to compile the header files in a C program?

You don't need to compile header files. It doesn't actually do anything, so there's no point in trying to run it. However, it is a great way to check for typos and mistakes and bugs, so it'll be easier later.

Setting Inheritance and Propagation flags with set-acl and powershell

Here's a table to help find the required flags for different permission combinations.

    +-----------------------------------------------------------------------------------------------------------------------------------------------------------+
    ¦             ¦ folder only ¦ folder, sub-folders and files ¦ folder and sub-folders ¦ folder and files ¦ sub-folders and files ¦ sub-folders ¦    files    ¦
    ¦-------------+-------------+-------------------------------+------------------------+------------------+-----------------------+-------------+-------------¦
    ¦ Propagation ¦ none        ¦ none                          ¦ none                   ¦ none             ¦ InheritOnly           ¦ InheritOnly ¦ InheritOnly ¦
    ¦ Inheritance ¦ none        ¦ Container|Object              ¦ Container              ¦ Object           ¦ Container|Object      ¦ Container   ¦ Object      ¦
    +-----------------------------------------------------------------------------------------------------------------------------------------------------------+

So, as David said, you'll want

InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit
PropagationFlags.None

How can I set the default value for an HTML <select> element?

To set the default using PHP and JavaScript:

State: <select id="State">
<option value="" selected disabled hidden></option>
<option value="Andhra Pradesh">Andhra Pradesh</option>
<option value="Andaman and Nicobar Islands">Andaman and Nicobar Islands</option>
.
.
<option value="West Bengal">West Bengal</option>
</select>
<?php
if(isset($_GET['State'])){
    echo <<<heredoc
<script>
document.getElementById("State").querySelector('option[value="{$_GET['State']}"]').selected = true;
</script>
heredoc;
}
?>

Android Log.v(), Log.d(), Log.i(), Log.w(), Log.e() - When to use each one?

The source code provides some basic guidance:

The order in terms of verbosity, from least to most is ERROR, WARN, INFO, DEBUG, VERBOSE. Verbose should never be compiled into an application except during development. Debug logs are compiled in but stripped at runtime. Error, warning and info logs are always kept.

For more detail, Kurtis' answer is dead on. I would just add: Don't log any personally identifiable or private information at INFO or above (WARN/ERROR). Otherwise, bug reports or anything else that includes logging may be polluted.

Full Screen Theme for AppCompat

To remove title bar in AppCompat:

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        supportRequestWindowFeature(Window.FEATURE_NO_TITLE);
        super.onCreate(savedInstanceState);
    }

Redraw datatables after using ajax to refresh the table content?

check fnAddData: https://legacy.datatables.net/ref

$(document).ready(function () {
  var table = $('#example').dataTable();
  var url = '/RESTApplicationTest/webresources/entity.person';
  $.get(url, function (data) {
    for (var i = 0; i < data.length; i++) {
      table.fnAddData([data[i].idPerson, data[i].firstname, data[i].lastname, data[i].email, data[i].phone])
    }
  });
});

How to update and order by using ms sql

I have to offer this as a better approach - you don't always have the luxury of an identity field:

UPDATE m
SET [status]=10
FROM (
  Select TOP (10) *
  FROM messages
  WHERE [status]=0
  ORDER BY [priority] DESC
) m

You can also make the sub-query as complicated as you want - joining multiple tables, etc...

Why is this better? It does not rely on the presence of an identity field (or any other unique column) in the messages table. It can be used to update the top N rows from any table, even if that table has no unique key at all.

Facebook share button and custom text

We use something like this [use in one line]:

<a title="send to Facebook" 
  href="http://www.facebook.com/sharer.php?s=100&p[title]=YOUR_TITLE&p[summary]=YOUR_SUMMARY&p[url]=YOUR_URL&p[images][0]=YOUR_IMAGE_TO_SHARE_OBJECT"
  target="_blank">
  <span>
    <img width="14" height="14" src="'icons/fb.gif" alt="Facebook" /> Facebook 
  </span>
</a>

Where do I put image files, css, js, etc. in Codeigniter?

No, inside the views folder is not good.

Look: You must have 3 basic folders on your project:

system // This is CI framework there are not much reasons to touch this files

application //this is where your logic goes, the files that makes the application,

public // this must be your documentroot

For security reasons its better to keep your framework and the application outside your documentroot,(public_html, htdocs, public, www... etc)

Inside your public folder, you should put your public info, what the browsers can see, its common to find the folders: images, js, css; so your structure will be:

|- system/
|- application/
|---- models/
|---- views/
|---- controllers/
|- public/
|---- images/
|---- js/
|---- css/
|---- index.php
|---- .htaccess

Reliable method to get machine's MAC address in C#

This method will determine the MAC address of the Network Interface used to connect to the specified url and port.

All the answers here are not capable of achieving this goal.

I wrote this answer years ago (in 2014). So I decided to give it a little "face lift". Please look at the updates section

    /// <summary>
    /// Get the MAC of the Netowrk Interface used to connect to the specified url.
    /// </summary>
    /// <param name="allowedURL">URL to connect to.</param>
    /// <param name="port">The port to use. Default is 80.</param>
    /// <returns></returns>
    private static PhysicalAddress GetCurrentMAC(string allowedURL, int port = 80)
    {
        //create tcp client
        var client = new TcpClient();

        //start connection
        client.Client.Connect(new IPEndPoint(Dns.GetHostAddresses(allowedURL)[0], port));

        //wai while connection is established
        while(!client.Connected)
        {
            Thread.Sleep(500);
        }

        //get the ip address from the connected endpoint
        var ipAddress = ((IPEndPoint)client.Client.LocalEndPoint).Address;

        //if the ip is ipv4 mapped to ipv6 then convert to ipv4
        if(ipAddress.IsIPv4MappedToIPv6)
            ipAddress = ipAddress.MapToIPv4();        

        Debug.WriteLine(ipAddress);

        //disconnect the client and free the socket
        client.Client.Disconnect(false);
        
        //this will dispose the client and close the connection if needed
        client.Close();

        var allNetworkInterfaces = NetworkInterface.GetAllNetworkInterfaces();

        //return early if no network interfaces found
        if(!(allNetworkInterfaces?.Length > 0))
            return null;

        foreach(var networkInterface in allNetworkInterfaces)
        {
            //get the unicast address of the network interface
            var unicastAddresses = networkInterface.GetIPProperties().UnicastAddresses;
           
            //skip if no unicast address found
            if(!(unicastAddresses?.Count > 0))
                continue;

            //compare the unicast addresses to see 
            //if any match the ip address used to connect over the network
            for(var i = 0; i < unicastAddresses.Count; i++)
            {
                var unicastAddress = unicastAddresses[i];

                //this is unlikely but if it is null just skip
                if(unicastAddress.Address == null)
                    continue;
                
                var ipAddressToCompare = unicastAddress.Address;

                Debug.WriteLine(ipAddressToCompare);

                //if the ip is ipv4 mapped to ipv6 then convert to ipv4
                if(ipAddressToCompare.IsIPv4MappedToIPv6)
                    ipAddressToCompare = ipAddressToCompare.MapToIPv4();

                Debug.WriteLine(ipAddressToCompare);

                //skip if the ip does not match
                if(!ipAddressToCompare.Equals(ipAddress))
                    continue;

                //return the mac address if the ip matches
                return networkInterface.GetPhysicalAddress();
            }
              
        }

        //not found so return null
        return null;
    }

To call it you need to pass a URL to connect to like this:

var mac = GetCurrentMAC("www.google.com");

You can also specify a port number. If not specified default is 80.

UPDATES:

2020

  • Added comments to explain the code.
  • Corrected to be used with newer operating systems that use IPV4 mapped to IPV6 ( like windows 10 ).
  • Reduced nesting.
  • Upgraded the code use "var".

How to trap the backspace key using jQuery?

The default behaviour for backspace on most browsers is to go back the the previous page. If you do not want this behaviour you need to make sure the call preventDefault(). However as the OP alluded to, if you always call it preventDefault() you will also make it impossible to delete things in text fields. The code below has a solution adapted from this answer.

Also, rather than using hard coded keyCode values (some values change depending on your browser, although I haven't found that to be true for Backspace or Delete), jQuery has keyCode constants already defined. This makes your code more readable and takes care of any keyCode inconsistencies for you.

// Bind keydown event to this function.  Replace document with jQuery selector
// to only bind to that element.
$(document).keydown(function(e){

    // Use jquery's constants rather than an unintuitive magic number.
    // $.ui.keyCode.DELETE is also available. <- See how constants are better than '46'?
    if (e.keyCode == $.ui.keyCode.BACKSPACE) {

        // Filters out events coming from any of the following tags so Backspace
        // will work when typing text, but not take the page back otherwise.
        var rx = /INPUT|SELECT|TEXTAREA/i;
        if(!rx.test(e.target.tagName) || e.target.disabled || e.target.readOnly ){
            e.preventDefault();
        }

       // Add your code here.
     }
});

Windows service on Local Computer started and then stopped error

If the service starts and stops like that, it means your code is throwing an unhandled exception. This is pretty difficult to debug, but there are a few options.

  1. Consult the Windows Event Viewer. Normally you can get to this by going to the computer/server manager, then clicking Event Viewer -> Windows Logs -> Application. You can see what threw the exception here, which may help, but you don't get the stack trace.
  2. Extract your program logic into a library class project. Now create two different versions of the program: a console app (for debugging), and the windows service. (This is a bit of initial effort, but saves a lot of angst in the long run.)
  3. Add more try/catch blocks and logging to the app to get a better picture of what's going on.

Using subprocess to run Python script on Windows

Just found sys.executable - the full path to the current Python executable, which can be used to run the script (instead of relying on the shbang, which obviously doesn't work on Windows)

import sys
import subprocess

theproc = subprocess.Popen([sys.executable, "myscript.py"])
theproc.communicate()

Formula to determine brightness of RGB color

To determine the brightness of a color with R, I convert the RGB system color in HSV system color.

In my script, I use the HEX system code before for other reason, but you can start also with RGB system code with rgb2hsv {grDevices}. The documentation is here.

Here is this part of my code:

 sample <- c("#010101", "#303030", "#A6A4A4", "#020202", "#010100")
 hsvc <-rgb2hsv(col2rgb(sample)) # convert HEX to HSV
 value <- as.data.frame(hsvc) # create data.frame
 value <- value[3,] # extract the information of brightness
 order(value) # ordrer the color by brightness

CSS How to set div height 100% minus nPx

In this example you can identify different areas:

<html>
<style>
#divContainer {
    width: 100%;
    height: 100%;
}
#divHeader {
    position: absolute;
    left: 0px;
    top: 0px;
    right: 0px;
    height: 28px;
    background-color:blue;
}
#divContentArea {
    position: absolute;
    left: 0px;
    top: 30px;
    right: 0px;
    bottom: 30px;
}
#divContentLeft {
    position: absolute;
    top: 0px;
    left: 0px;
    width: 200px;
    bottom: 0px;
    background-color:red;
}
#divContentCenter {
    position: absolute;
    top: 0px;
    left: 200px;
    bottom: 0px;
    right:200px;
    background-color:yellow;
}
#divContentRight {
    position: absolute;
    top: 0px;
    right: 0px;
    bottom: 0px;
    width:200px;
    background-color:red;
}
#divFooter {
    position: absolute;
    height: 28px;
    left: 0px;
    bottom: 0px;
    right: 0px;
    background-color:blue;
}
</style>
<body >

<div id="divContainer">
    <div id="divHeader"> top
    </div>
    <div id="divContentArea">
        <div id="divContentLeft">left
        </div>
        <div id="divContentCenter">center
        </div>
        <div id="divContentRight">right
        </div>
    </div>
    <div id="divFooter">bottom
    </div>
</div>

</body>
</html>

How to echo with different colors in the Windows command line

call :color_echo "blue" "blue txt"
call :color_echo "red" "red txt"
echo "white txt"


REM : https://www.robvanderwoude.com/ansi.php
:color_echo
    @echo off

    set "color=%~1"
    set "txt=%~2"

    set ESC=
    set black=%ESC%[30m
    set red=%ESC%[31m
    set green=%ESC%[32m
    set yellow=%ESC%[33m
    set blue=%ESC%[34m
    set magenta=%ESC%[35m
    set cyan=%ESC%[36m
    set white=%ESC%[37m

    if "%~1" == "black"   set "color=!black!"
    if "%~1" == "red"     set "color=!red!"
    if "%~1" == "green"   set "color=!green!"
    if "%~1" == "yellow"  set "color=!yellow!"
    if "%~1" == "blue"    set "color=!blue!"
    if "%~1" == "magenta" set "color=!magenta!"
    if "%~1" == "cyan"    set "color=!cyan!"
    if "%~1" == "white"   set "color=!white!"

    echo | set /p="!color!!txt!"
    echo.

    REM : return to standard white color
    echo | set /p="!white!"

    REM : exiting the function only
    EXIT /B 0

How do you right-justify text in an HTML textbox?

Did you try setting the style:

input {
    text-align:right;
}

Just tested, this works fine (in FF3 at least):

<html>
    <head>
        <title>Blah</title>
        <style type="text/css">
        input { text-align:right; }
        </style>
    </head>
    <body>
        <input type="text" value="2">
    </body>
</html>

You'll probably want to throw a class on these inputs, and use that class as the selector. I would shy away from "rightAligned" or something like that. In a class name, you want to describe what the element's function is, not how it should be rendered. "numeric" might be good, or perhaps the business function of the text boxes.

Convert String XML fragment to Document Node in Java

Try jcabi-xml, with a one liner:

Node node = new XMLDocument("<node>value</node>").node();

set background color: Android

This question is a old one but it can help for others too.

Try this :

    li.setBackgroundColor(getResources().getColor(R.color.blue));

    or

    li.setBackgroundColor(getResources().getColor(android.R.color.red));

    or

    li.setBackgroundColor(Color.rgb(226, 11, 11));


    or
    li.setBackgroundColor(Color.RED)

Calculate date from week number

This one worked for me, it also have the advantage of expecting a cultureinfo as parameter to test the formula with different cultures. If empty, it gets the current culture info... valid values are like: "it", "en-us", "fr", ... ando so on. The trick is to subtract the week number of the first day of the year, that may be 1 to indicate that the first day is within the first week. Hope this helps.

Public Shared Function FirstDayOfWeek(ByVal year As Integer, ByVal weekNumber As Integer, ByVal culture As String) As Date
    Dim cInfo As System.Globalization.CultureInfo
    If culture = "" Then
        cInfo = System.Globalization.CultureInfo.CurrentCulture
    Else
        cInfo = System.Globalization.CultureInfo.CreateSpecificCulture(culture)
    End If
    Dim calendar As System.Globalization.Calendar = cInfo.Calendar
    Dim firstOfYear As DateTime = New DateTime(year, 1, 1, calendar)
    Dim firstDayWeek As Integer = calendar.GetWeekOfYear(firstOfYear, cInfo.DateTimeFormat.CalendarWeekRule, cInfo.DateTimeFormat.FirstDayOfWeek)
    weekNumber -= firstDayWeek
    Dim targetDay As DateTime = calendar.AddWeeks(firstOfYear, weekNumber)
    Dim fDayOfWeek As DayOfWeek = cInfo.DateTimeFormat.FirstDayOfWeek

    While (targetDay.DayOfWeek <> fDayOfWeek)
        targetDay = targetDay.AddDays(-1)
    End While
    Return targetDay
End Function

how do you increase the height of an html textbox

Note that if you want a multi line text box you have to use a <textarea> instead of an <input type="text">.

How to produce a range with step n in bash? (generate a sequence of numbers with increments)

Pure Bash, without an extra process:

for (( COUNTER=0; COUNTER<=10; COUNTER+=2 )); do
    echo $COUNTER
done

SQL Server Group By Month

Another approach, that doesn't involve adding columns to the result, is to simply zero-out the day component of the date, so 2016-07-13 and 2016-07-16 would both be 2016-07-01 - thus making them equal by month.

If you have a date (not a datetime) value, then you can zero it directly:

SELECT
    DATEADD( day, 1 - DATEPART( day, [Date] ), [Date] ),
    COUNT(*)
FROM
    [Table]
GROUP BY
    DATEADD( day, 1 - DATEPART( day, [Date] ), [Date] )

If you have datetime values, you'll need to use CONVERT to remove the time-of-day portion:

SELECT
    DATEADD( day, 1 - DATEPART( day, [Date] ),  CONVERT( date, [Date] ) ),
    COUNT(*)
FROM
    [Table]
GROUP BY
    DATEADD( day, 1 - DATEPART( day, [Date] ),  CONVERT( date, [Date] ) )

MySQL: How to reset or change the MySQL root password?

If you would like to change the MySQL root password, in a terminal enter:

sudo dpkg-reconfigure mysql-server-5.5

The MySQL daemon will be stopped, and you will be prompted to enter a new password.

Calculate summary statistics of columns in dataframe

describe may give you everything you want otherwise you can perform aggregations using groupby and pass a list of agg functions: http://pandas.pydata.org/pandas-docs/stable/groupby.html#applying-multiple-functions-at-once

In [43]:

df.describe()

Out[43]:

       shopper_num is_martian  number_of_items  count_pineapples
count      14.0000         14        14.000000                14
mean        7.5000          0         3.357143                 0
std         4.1833          0         6.452276                 0
min         1.0000      False         0.000000                 0
25%         4.2500          0         0.000000                 0
50%         7.5000          0         0.000000                 0
75%        10.7500          0         3.500000                 0
max        14.0000      False        22.000000                 0

[8 rows x 4 columns]

Note that some columns cannot be summarised as there is no logical way to summarise them, for instance columns containing string data

As you prefer you can transpose the result if you prefer:

In [47]:

df.describe().transpose()

Out[47]:

                 count      mean       std    min   25%  50%    75%    max
shopper_num         14       7.5    4.1833      1  4.25  7.5  10.75     14
is_martian          14         0         0  False     0    0      0  False
number_of_items     14  3.357143  6.452276      0     0    0    3.5     22
count_pineapples    14         0         0      0     0    0      0      0

[4 rows x 8 columns]

The model backing the <Database> context has changed since the database was created

For me, with the upgrade to 4.3.1, I just truncate the EdmMetaData table or just delete it outright.

How Should I Declare Foreign Key Relationships Using Code First Entity Framework (4.1) in MVC3?

If you have an Order class, adding a property that references another class in your model, for instance Customer should be enough to let EF know there's a relationship in there:

public class Order
{
    public int ID { get; set; }

    // Some other properties

    // Foreign key to customer
    public virtual Customer Customer { get; set; }
}

You can always set the FK relation explicitly:

public class Order
{
    public int ID { get; set; }

    // Some other properties

    // Foreign key to customer
    [ForeignKey("Customer")]
    public string CustomerID { get; set; }
    public virtual Customer Customer { get; set; }
}

The ForeignKeyAttribute constructor takes a string as a parameter: if you place it on a foreign key property it represents the name of the associated navigation property. If you place it on the navigation property it represents the name of the associated foreign key.

What this means is, if you where to place the ForeignKeyAttribute on the Customer property, the attribute would take CustomerID in the constructor:

public string CustomerID { get; set; }
[ForeignKey("CustomerID")]
public virtual Customer Customer { get; set; }

EDIT based on Latest Code You get that error because of this line:

[ForeignKey("Parent")]
public Patient Patient { get; set; }

EF will look for a property called Parent to use it as the Foreign Key enforcer. You can do 2 things:

1) Remove the ForeignKeyAttribute and replace it with the RequiredAttribute to mark the relation as required:

[Required]
public virtual Patient Patient { get; set; }

Decorating a property with the RequiredAttribute also has a nice side effect: The relation in the database is created with ON DELETE CASCADE.

I would also recommend making the property virtual to enable Lazy Loading.

2) Create a property called Parent that will serve as a Foreign Key. In that case it probably makes more sense to call it for instance ParentID (you'll need to change the name in the ForeignKeyAttribute as well):

public int ParentID { get; set; }

In my experience in this case though it works better to have it the other way around:

[ForeignKey("Patient")]
public int ParentID { get; set; }

public virtual Patient Patient { get; set; }

How do I terminate a thread in C++11?

I guess the thread that needs to be killed is either in any kind of waiting mode, or doing some heavy job. I would suggest using a "naive" way.

Define some global boolean:

std::atomic_bool stop_thread_1 = false;

Put the following code (or similar) in several key points, in a way that it will cause all functions in the call stack to return until the thread naturally ends:

if (stop_thread_1)
    return;

Then to stop the thread from another (main) thread:

stop_thread_1 = true;
thread1.join ();
stop_thread_1 = false; //(for next time. this can be when starting the thread instead)

How To Save Canvas As An Image With canvas.toDataURL()?

I created a small library that does this (along with some other handy conversions). It's called reimg, and it's really simple to use.

ReImg.fromCanvas(yourCanvasElement).toPng()

How do I sort a table in Excel if it has cell references in it?

I had this same problem; I had a master sheet which was a summary of information on other worksheets in my workbook.

If you just want to filter/sort in a worksheet where you have your data stored, and then return it to its original state (no matter what you are filtering/sorting by) just make your first column a Line Item Number.

After your initial filter/sort you can then just resort by the “Line Item Number” to return everything back to normal. NOTE: This only works if you always add new rows to the end of the list in sequence.

DateTime format to SQL format using C#

Using the standard datetime format "s" will also ensure internationalization compatibility (MM/dd versus dd/MM):

myDateTime.ToString("s");

=> 2013-12-31T00:00:00

Complete Options: (code: sample result)

d: 6/15/2008 
D: Sunday, June 15, 2008 
f: Sunday, June 15, 2008 9:15 PM 
F: Sunday, June 15, 2008 9:15:07 PM 
g: 6/15/2008 9:15 PM 
G: 6/15/2008 9:15:07 PM 
m: June 15 
o: 2008-06-15T21:15:07.0000000 
R: Sun, 15 Jun 2008 21:15:07 GMT 
s: 2008-06-15T21:15:07 
t: 9:15 PM 
T: 9:15:07 PM 
u: 2008-06-15 21:15:07Z 
U: Monday, June 16, 2008 4:15:07 AM 
y: June, 2008 

'h:mm:ss.ff t': 9:15:07.00 P 
'd MMM yyyy': 15 Jun 2008 
'HH:mm:ss.f': 21:15:07.0 
'dd MMM HH:mm:ss': 15 Jun 21:15:07 
'\Mon\t\h\: M': Month: 6 
'HH:mm:ss.ffffzzz': 21:15:07.0000-07:00

Supported in .NET Framework: 4.6, 4.5, 4, 3.5, 3.0, 2.0, 1.1, 1.0
Reference: DateTime.ToString Method

Is HTML considered a programming language?

Well, L is for language, but it doesn't imply programming language. After all, English or French are (natural) languages too! ;-)

As said above, put them under a subsidiary section, Technology seems to be a good term.

(Looking at my own resume, not updated in a while) I have made a section just called "Languages", so I can't get wrong... :-D
I have put "(X)HTML and CSS, XML/DTD/Schema and SVG" at the end of the section, clearly separated.

In French, I have a section "Langages" (programming and markup) and another "Langues" (French/English). In the English version, I titled both at "Languages", which is clumsy now that I think of it, although context clarify this. I should find a better formulation.

How to upload a file in Django?

Extending on Henry's example:

import tempfile
import shutil

FILE_UPLOAD_DIR = '/home/imran/uploads'

def handle_uploaded_file(source):
    fd, filepath = tempfile.mkstemp(prefix=source.name, dir=FILE_UPLOAD_DIR)
    with open(filepath, 'wb') as dest:
        shutil.copyfileobj(source, dest)
    return filepath

You can call this handle_uploaded_file function from your view with the uploaded file object. This will save the file with a unique name (prefixed with filename of the original uploaded file) in filesystem and return the full path of saved file. You can save the path in database, and do something with the file later.

Date ticks and rotation in matplotlib

An easy solution which avoids looping over the ticklabes is to just use

fig.autofmt_xdate()

This command automatically rotates the xaxis labels and adjusts their position. The default values are a rotation angle 30° and horizontal alignment "right". But they can be changed in the function call

fig.autofmt_xdate(bottom=0.2, rotation=30, ha='right')

The additional bottom argument is equivalent to setting plt.subplots_adjust(bottom=bottom), which allows to set the bottom axes padding to a larger value to host the rotated ticklabels.

So basically here you have all the settings you need to have a nice date axis in a single command.

A good example can be found on the matplotlib page.

Comparing two integer arrays in Java

From what I see you just try to see if they are equal, if this is true, just go with something like this:

boolean areEqual = Arrays.equals(arr1, arr2);

This is the standard way of doing it.

Please note that the arrays must be also sorted to be considered equal, from the JavaDoc:

Two arrays are considered equal if both arrays contain the same number of elements, and all corresponding pairs of elements in the two arrays are equal. In other words, two arrays are equal if they contain the same elements in the same order.

Sorry for missing that.

Heap vs Binary Search Tree (BST)

Insert all n elements from an array to BST takes O(n logn). n elemnts in an array can be inserted to a heap in O(n) time. Which gives heap a definite advantage

Setting a minimum/maximum character count for any character using a regular expression

Like this: .

The . means any character except newline (which sometimes is but often isn't included, check your regex flavour).

You can rewrite your expression as ^.{1,35}$, which should match any line of length 1-35.

How might I force a floating DIV to match the height of another floating DIV?

Flex does this by default.

<div id="flex">
 <div id="response">
 </div> 
 <div id="note">
 </div>
</div>   

CSS:

#flex{display:flex}
#response{width:65%}
#note{width:35%}

https://jsfiddle.net/784pnojq/1/

BONUS: multiple rows

https://jsfiddle.net/784pnojq/2/

How to check if String value is Boolean type in Java?

The methods you're calling on the Boolean class don't check whether the string contains a valid boolean value, but they return the boolean value that represents the contents of the string: put "true" in string, they return true, put "false" in string, they return false.

You can surely use these methods, however, to check for valid boolean values, as I'd expect them to throw an exception if the string contains "hello" or something not boolean.

Wrap that in a Method ContainsBoolString and you're go.

EDIT
By the way, in C# there are methods like bool Int32.TryParse(string x, out int i) that perform the check whether the content can be parsed and then return the parsed result.

int i;
if (Int32.TryParse("Hello", out i))
  // Hello is an int and its value is in i
else
  // Hello is not an int

Benchmarks indicate they are way faster than the following:

int i;
try
{
   i = Int32.Parse("Hello");
   // Hello is an int and its value is in i
}
catch
{
   // Hello is not an int
}

Maybe there are similar methods in Java? It's been a while since I've used Java...

Sleep function in C++

You'll need at least C++11.

#include <thread>
#include <chrono>

...

std::this_thread::sleep_for(std::chrono::milliseconds(200));

How to detect IE11?

Detect most browsers with this:

var getBrowser = function(){
  var navigatorObj = navigator.appName,
      userAgentObj = navigator.userAgent,
      matchVersion;
  var match = userAgentObj.match(/(opera|chrome|safari|firefox|msie|trident)\/?\s*(\.?\d+(\.\d+)*)/i);
  if( match && (matchVersion = userAgentObj.match(/version\/([\.\d]+)/i)) !== null) match[2] = matchVersion[1];
  //mobile
  if (navigator.userAgent.match(/iPhone|Android|webOS|iPad/i)) {
    return match ? [match[1], match[2], mobile] : [navigatorObj, navigator.appVersion, mobile];
  }
  // web browser
  return match ? [match[1], match[2]] : [navigatorObj, navigator.appVersion, '-?'];
};

https://gist.github.com/earlonrails/5266945

JavaFX Location is not set error message

I mean something like this:

FXMLLoader myLoader = null; Scene myScene = null; Stage prevStage = null;

public void start(Stage primaryStage) throws Exception {
  primaryStage.setTitle("Shop Management");
  myLoader = new FXMLLoader(getClass().getResource("cartHomePage.fxml"));
  Pane myPane = (Pane) myLoader.load();
  CartHomePageUI controller = (CartHomePageUI) myLoader.getController();
  controller.setPrevStage(primaryStage);
  myScene = new Scene(myPane);
  primaryStage.setScene(myScene);
  primaryStage.show();
}

After that

public void setPrevStage(Stage stage){
    this.prevStage = stage;
}

public void gotoCreateCategory(ActionEvent event) throws IOException {
    Stage stage = new Stage();
    stage.setTitle("Shop Management");
    myLoader = new FXMLLoader(getClass().getResource("createCategory.fxml"));
    Pane myPane = (Pane) myLoader.load();            
    Scene scene = new Scene(myPane);
    stage.setScene(scene);
// prevStage.close(); I don't think you need this, closing it will set preStage to null   put a breakpoint after this to confirm it
    setPrevStage(stage);
    stage.show();       
}

//Method to change scene when menu item create product is on click
@FXML
public void gotoCreateProduct(ActionEvent event) throws IOException {
    Stage stage = new Stage();
    stage.setTitle("Shop Management");
    myLoader = new FXMLLoader(getClass().getResource("creatProduct.fxml"));
    Pane myPane = (Pane) myLoader.load();            
    Scene scene = new Scene(myPane);
    stage.setScene(scene);
// prevStage.close(); I don't think you need this, closing it will set preStage to null put a breakpoint after this to confirm it
    setPrevStage(stage);
    stage.show();      
}

Try it and let me know please.

Shorter syntax for casting from a List<X> to a List<Y>?

To add to Sweko's point:

The reason why the cast

var listOfX = new List<X>();
ListOf<Y> ys = (List<Y>)listOfX; // Compile error: Cannot implicitly cast X to Y

is not possible is because the List<T> is invariant in the Type T and thus it doesn't matter whether X derives from Y) - this is because List<T> is defined as:

public class List<T> : IList<T>, ICollection<T>, IEnumerable<T> ... // Other interfaces

(Note that in this declaration, type T here has no additional variance modifiers)

However, if mutable collections are not required in your design, an upcast on many of the immutable collections, is possible, e.g. provided that Giraffe derives from Animal:

IEnumerable<Animal> animals = giraffes;

This is because IEnumerable<T> supports covariance in T - this makes sense given that IEnumerable implies that the collection cannot be changed, since it has no support for methods to Add or Remove elements from the collection. Note the out keyword in the declaration of IEnumerable<T>:

public interface IEnumerable<out T> : IEnumerable

(Here's further explanation for the reason why mutable collections like List cannot support covariance, whereas immutable iterators and collections can.)

Casting with .Cast<T>()

As others have mentioned, .Cast<T>() can be applied to a collection to project a new collection of elements casted to T, however doing so will throw an InvalidCastException if the cast on one or more elements is not possible (which would be the same behaviour as doing the explicit cast in the OP's foreach loop).

Filtering and Casting with OfType<T>()

If the input list contains elements of different, incompatable types, the potential InvalidCastException can be avoided by using .OfType<T>() instead of .Cast<T>(). (.OfType<>() checks to see whether an element can be converted to the target type, before attempting the conversion, and filters out incompatable types.)

foreach

Also note that if the OP had written this instead: (note the explicit Y y in the foreach)

List<Y> ListOfY = new List<Y>();

foreach(Y y in ListOfX)
{
    ListOfY.Add(y);
}

that the casting will also be attempted. However, if no cast is possible, an InvalidCastException will result.

Examples

For example, given the simple (C#6) class hierarchy:

public abstract class Animal
{
    public string Name { get;  }
    protected Animal(string name) { Name = name; }
}

public class Elephant :  Animal
{
    public Elephant(string name) : base(name){}
}

public class Zebra : Animal
{
    public Zebra(string name)  : base(name) { }
}

When working with a collection of mixed types:

var mixedAnimals = new Animal[]
{
    new Zebra("Zed"),
    new Elephant("Ellie")
};

foreach(Animal animal in mixedAnimals)
{
     // Fails for Zed - `InvalidCastException - cannot cast from Zebra to Elephant`
     castedAnimals.Add((Elephant)animal);
}

var castedAnimals = mixedAnimals.Cast<Elephant>()
    // Also fails for Zed with `InvalidCastException
    .ToList();

Whereas:

var castedAnimals = mixedAnimals.OfType<Elephant>()
    .ToList();
// Ellie

filters out only the Elephants - i.e. Zebras are eliminated.

Re: Implicit cast operators

Without dynamic, user defined conversion operators are only used at compile-time*, so even if a conversion operator between say Zebra and Elephant was made available, the above run time behaviour of the approaches to conversion wouldn't change.

If we add a conversion operator to convert a Zebra to an Elephant:

public class Zebra : Animal
{
    public Zebra(string name) : base(name) { }
    public static implicit operator Elephant(Zebra z)
    {
        return new Elephant(z.Name);
    }
}

Instead, given the above conversion operator, the compiler will be able to change the type of the below array from Animal[] to Elephant[], given that the Zebras can be now converted to a homogeneous collection of Elephants:

var compilerInferredAnimals = new []
{
    new Zebra("Zed"),
    new Elephant("Ellie")
};

Using Implicit Conversion Operators at run time

*As mentioned by Eric, the conversion operator can however be accessed at run time by resorting to dynamic:

var mixedAnimals = new Animal[] // i.e. Polymorphic collection
{
    new Zebra("Zed"),
    new Elephant("Ellie")
};

foreach (dynamic animal in mixedAnimals)
{
    castedAnimals.Add(animal);
}
// Returns Zed, Ellie

How to create strings containing double quotes in Excel formulas?

Returning an empty or zero-length string (e.g. "") to make a cell appear blank is a common practise in a worksheet formula but recreating that option when inserting the formula through the Range.Formula or Range.FormulaR1C1 property in VBA is unwieldy due to the necessity of having to double-up the double-quote characters within a quoted string.

The worksheet's native TEXT function can produce the same result without using quotes.

'formula to insert into C1 - =IF(A1<>"", B1, "")
range("C1").formula = "=IF(A1<>"""", B1, """")"         '<~quote chars doubled up
range("C1").formula = "=IF(A1<>TEXT(,), B1, TEXT(,))"   '<~with TEXT(,) instead

To my eye, using TEXT(,) in place of "" cleans up even a simple formula like the one above. The benefits become increasingly significant when used in more complicated formulas like the practise of appending an empty string to a VLOOKUP to avoid returning a zero to the cell when a lookup results in a blank or returning an empty string on no-match with IFERROR.

'formula to insert into D1 - =IFERROR(VLOOKUP(A1, B:C, 2, FALSE)&"", "")
range("D1").formula = "=IFERROR(VLOOKUP(A1, B:C, 2, FALSE)&"""", """")"
range("D1").formula = "=IFERROR(VLOOKUP(A1, B:C, 2, FALSE)&TEXT(,), TEXT(,))"

With TEXT(,) replacing the old "" method of delivering an empty string, you might get to stop using an abacus to determine whether you have the right number of quote characters in a formula string.

Angular 4 HttpClient Query Parameters

If you have an object that can be converted to {key: 'stringValue'} pairs, you can use this shortcut to convert it:

this._Http.get(myUrlString, {params: {...myParamsObject}});

I just love the spread syntax!

Is it wrong to place the <script> tag after the </body> tag?

IE doesn't allow this anymore (since Version 10, I believe) and will ignore such scripts. FF and Chrome still tolerate them, but there are chances that some day they will drop this as non-standard.

How to represent the double quotes character (") in regex?

you need to use backslash before ". like \"

From the doc here you can see that

A character preceded by a backslash ( \ ) is an escape sequence and has special meaning to the compiler.

and " (double quote) is a escacpe sequence

When an escape sequence is encountered in a print statement, the compiler interprets it accordingly. For example, if you want to put quotes within quotes you must use the escape sequence, \", on the interior quotes. To print the sentence

She said "Hello!" to me.

you would write

System.out.println("She said \"Hello!\" to me.");

How to implement LIMIT with SQL Server?

Starting SQL SERVER 2005, you can do this...

USE AdventureWorks;
GO
WITH OrderedOrders AS
(
    SELECT SalesOrderID, OrderDate,
    ROW_NUMBER() OVER (ORDER BY OrderDate) AS 'RowNumber'
    FROM Sales.SalesOrderHeader 
) 
SELECT * 
FROM OrderedOrders 
WHERE RowNumber BETWEEN 10 AND 20;

or something like this for 2000 and below versions...

SELECT TOP 10 * FROM (SELECT TOP 20 FROM Table ORDER BY Id) ORDER BY Id DESC