text:
Q: How can I find the node of the last layer of each tree in GBDT, using Spark MLLib? I want to generate feature using GBDT (Facebook's paper Practical Lessons from Predicting Clicks on Ads at Facebook). And it seems easy to do this job, using Sklearn Feature transformations with ensembles of trees. But using Spark to do this job seems hard since there is no method in Saprk's GBDT named apply (this method in sklearn can help me find the node) or some method that we can find the index of the leaf x ends up in each estimator, in another word, the node that data will be end up with in each estimator.
If I use the method trees in MLLib's GBDT Classifier model, then I get the following, which does not tell me the exactly node that I want to know
[DecisionTreeRegressionModel (uid=dtr_e1fb06f46c7c) of depth 2 with 5 nodes,
 DecisionTreeRegressionModel (uid=dtr_23641ea362dc) of depth 4 with 17 nodes,
 DecisionTreeRegressionModel (uid=dtr_3dedd910cbe2) of depth 3 with 7 nodes,
 DecisionTreeRegressionModel (uid=dtr_2cfe4fa44b89) of depth 3 with 9 nodes,
 DecisionTreeRegressionModel (uid=dtr_24c37bd33424) of depth 5 with 19 nodes,
 DecisionTreeRegressionModel (uid=dtr_4d7530bfc4e2) of depth 4 with 11 nodes,
 DecisionTreeRegressionModel (uid=dtr_e288599f5944) of depth 4 with 15 nodes,
 DecisionTreeRegressionModel (uid=dtr_d355940d4246) of depth 4 with 15 nodes,
 DecisionTreeRegressionModel (uid=dtr_6abbfbcfdd4e) of depth 3 with 9 nodes,
 DecisionTreeRegressionModel (uid=dtr_58ca63396c4a) of depth 3 with 13 nodes]

If I use toDebugString, then I get something like
u'GBTClassificationModel (uid=GBTClassifier_4f36b986f967194b34b6) with 10 trees\n  Tree 0 (weight 1.0):\n    If (feature 406 <= 72.0)\n     If (feature 99 in {2.0})\n      Predict: -1.0\n     Else (feature 99 not in {2.0})\n      Predict: 1.0\n    Else (feature 406 > 72.0)\n     Predict: -1.0\n  Tree 1 (weight 0.1):\n    If (feature 406 <= 72.0)\n     If (feature 209 <= 4.0)\n      Predict: -0.4768116880884702\n     Else (feature 209 > 4.0)\n      If (feature 236 <= 253.0)\n       If (feature 244 <= 175.0)\n        Predict: 0.4768116880884702\n       Else (feature 244 > 175.0)\n        Predict: 0.47681168808847024\n      Else (feature 236 > 253.0)\n       Predict: 0.4768116880884703\n    Else (feature 406 > 72.0)\n     If (feature 459 <= 144.0)\n      If (feature 323 <= 78.0)\n       If (feature 119 in {0.0})\n        Predict: -0.4768116880884702\n       Else (feature 119 not in {0.0})\n        Predict: -0.4768116880884701\n      Else (feature 323 > 78.0)\n       If (feature 323 <= 116.0)\n        Predict: -0.4768116880884702\n       Else (feature 323 > 116.0)\n        Predict: -0.47681168808847035\n     Else (feature 459 > 144.0)\n      Predict: -0.4768116880884712\n  Tree 2 (weight 0.1):\n    If (feature 406 <= 72.0)\n     If (feature 209 <= 4.0)\n      Predict: -0.4381935810427206\n     Else (feature 209 > 4.0)\n      If (feature 578 <= 13.0)\n       Predict: 0.4381935810427206\n      Else (feature 578 > 13.0)\n       Predict: 0.4381935810427206\n    Else (feature 406 > 72.0)\n     Predict: -0.43819358104272055\n  Tree 3 (weight 0.1):\n    If (feature 433 <= 0.0)\n     If (feature 239 <= 253.0)\n      Predict: 0.40514968028459825\n     Else (feature 239 > 253.0)\n      Predict: -0.4051496802845982\n    Else (feature 433 > 0.0)\n     If (feature 124 <= 26.0)\n      If (feature 265 <= 3.0)\n       Predict: -0.40514968028459825\n      Else (feature 265 > 3.0)\n       Predict: -0.4051496802845982\n     Else (feature 124 > 26.0)\n      Predict: -0.4051496802845984\n

It is hard for my code to find the place of node in the last layer of each tree.
How can I generate feature using Spark's GBDT, just like what sklearn can do ?


text:
Q: Remove the preview, view button and permalink to custom post admin using functions.php I have a custom theme with custom post. I like to remove the preview/view button and permalink on the default post admin using functions.php.
here is my code in default custom post
////////////////////Change the default post to "新規求人登録"////////////////////
function Change_menulabel() {
global $menu;
global $submenu;
  $name = '新規求人登録';
  $menu[5][0] = $name;
  $submenu['edit.php'][5][0] = $name.'';
  $submenu['edit.php'][10][0] = '新しいお知らせを追加';
}
function Change_objectlabel() {
  global $wp_post_types;
  $name = '新規求人登録';
  $labels = &$wp_post_types['post']->labels;
  $labels->name = $name;
  $labels->singular_name = $name;
  $labels->add_new = _x('追加', $name);
  $labels->add_new_item = $name.'の新規追加';
  $labels->edit_item = $name.'の編集';
  $labels->new_item = '新規'.$name;
  $labels->view_item = $name.'を表示';
  $labels->search_items = $name.'を検索';
  $labels->not_found = $name.'が見つかりませんでした';
  $labels->not_found_in_trash = 'ゴミ箱に'.$name.'は見つかりませんでした';
}

add_action( 'init', 'Change_objectlabel' );
add_action( 'admin_menu', 'Change_menulabel' );

A: hi @shouu you can hide the preview button and its permalink through this code
function hide_publishing_actions(){
    $my_post_type = 'post';
    global $post;
       if($post->post_type == $my_post_type){
          echo '
             <style type="text/css">
                #edit-slug-box,
                #minor-publishing-actions{
                     display:none;
                }
             </style>
           ';
        }
      }
   add_action('admin_head-post.php', 'hide_publishing_actions');
   add_action('admin_head-post-new.php', 'hide_publishing_actions');

redpajama_set_name: RedPajamaStackExchange


text:
Q: SyntaxError in Chrome but ReferenceError in node So I run the same code 5=6 on both chrome and node this of course produces an error. But look at the error type!

On chrome it's a SyntaxError on node ReferenceError.
Well that's odd. For one thing cause both use v8, for another because well...you'd think this would be defined in the spec, so someone has to be wrong.
The same thing happens with strings. Same thing when running js outside of the chrome console as a script. Same thing when running outside of the node console as a script.
Someone suggested that it might be due to differences in boxing since Number(5) = 6 is a ReferenceError on both but that's just the case for any fn() = _. And if that is the case, then it still doesn't explain why the behavior is different in the two engines.
So what's the correct (as per the spec) thing to do here? Who is wrong and why are the two engines giving me different errors?

A: The ECMAScript language specification changed in June 2019 so that many things that were previously a ReferenceError (including attempting to assign to a number literal) are now a SyntaxError.
v8 implemented this change (also in June 2019) in version 7.7.196, which was included in Chrome 77 and Node 12.11. Prior to those versions, attempting to assign to a number literal resulted in a ReferenceError in both Node and Chrome. Starting with those versions, the same code now results in a SyntaxError.
$ ./node-v12.10.0 -e 5=6 2>&1 | grep Error
ReferenceError: Invalid left-hand side in assignment
$ ./node-v12.11.0 -e 5=6 2>&1 | grep Error
SyntaxError: Invalid left-hand side in assignment

A: From searching
Assigning to literal is type of syntax error.
A ReferenceError occurs when there was an unexpected assignment somewhere
A SyntaxError occurs when object represents an error when trying to interpret syntactically invalid code

try {
  Number(5) = 6
} catch (e) {
  console.log(e instanceof ReferenceError)  // true
  console.log(e.message)                    // ""
  console.log(e.name)                       // "ReferenceError"
  console.log(e.fileName)
  console.log(e.lineNumber)
  console.log(e.columnNumber)
  console.log(e.stack)
}

but typeof Number(5) is number but assigning to function is valid in js.
when i write below it give SyntaxError rather than ReferenceError

try {
  5 = 6
} catch (e) {
  console.log(e instanceof ReferenceError)
  console.log(e.message)
  console.log(e.name)
  console.log(e.fileName)
  console.log(e.lineNumber)
  console.log(e.columnNumber)
  console.log(e.stack)
}

Their error details are same but Number(5) in js syntactically valid code , but its error in both of situation are same(Invalid left-hand side in assignment). Only differance is Number(5) is syntactically valid code in js but not in node.
But in node 12.14.0 that I used errors are same with js then, node changed its error type.

 This means js is correct for this error type


text:
Q: Requests for Poloniex API I trying work with Poloniex API. And I try get balances via Trading API methods. And I try do it with requests library like this:
import requests
import hmac
import hashlib
import time
import urllib

def setPrivateCommand(self):
    poloniex_data = {'command': 'returnBalances', 'nonce': int(time.time() * 1000)}
    post_data = urllib.parse.urlencode(poloniex_data).encode()
    sig = hmac.new(str.encode(app.config['HMAC_KEYS']['Poloniex_Secret']), post_data, hashlib.sha512).hexdigest()
    headers = {'Sign': sig, 'Key': app.config['HMAC_KEYS']['Poloniex_APIKey']}
    polo_request = requests.post('https://poloniex.com/tradingApi', data=post_data, headers=headers, timeout=20)
    polo_request = polo_request.json()
    print('Request: {0}'.format(polo_request))
    return polo_request

With this code I always get error with message: "Request: {'error': 'Invalid command.'}". What I do wrong?
From other side code below returns data without any problem! Look at this, please:
import requests
import hmac
import hashlib
import json
import time
import urllib

def setPrivateCommand(self):
    poloniex_data = {'command': 'returnBalances', 'nonce': int(time.time() * 1000)}
    post_data = urllib.parse.urlencode(poloniex_data).encode()
    sig = hmac.new(str.encode(app.config['HMAC_KEYS']['Poloniex_Secret']), post_data, hashlib.sha512).hexdigest()
    headers = {'Sign': sig, 'Key': app.config['HMAC_KEYS']['Poloniex_APIKey']}
    req = urllib.request.Request('https://poloniex.com/tradingApi', data=post_data, headers=headers)
    res = urllib.request.urlopen(req, timeout=20)
    Ret_data = json.loads(res.read().decode('utf-8'))
    print('Request: {0}'.format(Ret_data))
    return Ret_data

I using Python 3.6

A: It's best to let requests handle post data because it creates the appropriate headers.  Other than that i don't see anything wrong with your code.
def setPrivateCommand(self):
    poloniex_data = {'command': 'returnBalances', 'nonce': int(time.time() * 1000)}
    post_data = urllib.parse.urlencode(poloniex_data).encode()
    sig = hmac.new(
        str.encode(app.config['HMAC_KEYS']['Poloniex_Secret']), post_data, hashlib.sha512
    ).hexdigest()
    headers = {'Sign': sig, 'Key': app.config['HMAC_KEYS']['Poloniex_APIKey']}
    polo_request = requests.post(
        'https://poloniex.com/tradingApi', data=poloniex_data, headers=headers, timeout=20
    )
    polo_request = polo_request.json()
    print('Request: {0}'.format(polo_request))
    return polo_request

Or you could specify the 'Content-Type' in headers if you want to have a string  in data, example,
headers = {
    'Sign': sig, 'Key': app.config['HMAC_KEYS']['Poloniex_APIKey'],
    'Content-Type': 'application/x-www-form-urlencoded'
}
polo_request = requests.post(
    'http://httpbin.org/anything', data=post_data, headers=headers, timeout=20
)


text:
Q: RFC 2822, 3.6.2 error in production for emails following "abc@xyz.co.uk" format using Laravel I get RFC 2822, 3.6.2 error thrown (only in production) for email addresses which follow this format:  abc@xyz.co.uk
Source code is as follows:
Mail::to($emailAddress, $name)->send($email);

Other email formats that pass the Laravel validation work just fine.
I can not reproduce this issue locally
I'm using laravel 5.3
Local:
Windows 10 + homestead + mailtrap
Production:
AWS + forge + mailgun
Swiftmailer version is 5.4.8 (retrieved from composer.lock)
I could reproduce it locally, with Firefox V: 54.0 (32-bit). This seems pretty strange I can't reproduce it in production neither locally with Chrome.
Here is the full exception:
Swift_RfcComplianceException in MailboxHeader.php line 345: Address in mailbox given [abc@xyz.co.uk] does not comply with RFC 2822, 3.6.2.

in MailboxHeader.php line 345
at Swift_Mime_Headers_MailboxHeader->_assertValidAddress('abc@xyz.co.uk') in MailboxHeader.php line 261
at Swift_Mime_Headers_MailboxHeader->normalizeMailboxes(array('abc@xyz.co.uk' => null)) in MailboxHeader.php line 106
at Swift_Mime_Headers_MailboxHeader->setNameAddresses(array('abc@xyz.co.uk' => null)) in MailboxHeader.php line 63
at Swift_Mime_Headers_MailboxHeader->setFieldBodyModel(array('abc@xyz.co.uk' => null)) in SimpleHeaderFactory.php line 58
at Swift_Mime_SimpleHeaderFactory->createMailboxHeader('To', array('abc@xyz.co.uk' => null)) in SimpleHeaderSet.php line 68
at Swift_Mime_SimpleHeaderSet->addMailboxHeader('To', array('abc@xyz.co.uk' => null)) in SimpleMessage.php line 329
at Swift_Mime_SimpleMessage->setTo(array('abc@xyz.co.uk' => null)) in SimpleMessage.php line 305
at Swift_Mime_SimpleMessage->addTo('abc@xyz.co.uk', null) in Message.php line 151
at Message->addAddresses('abc@xyz.co.uk', null, 'To') in Message.php line 85
at Message->to('abc@xyz.co.uk', null) in Mailable.php line 226
at Mailable->buildRecipients(object(Message)) in Mailable.php line 113
at Mailable->Illuminate\Mail\{closure}(object(Message))
at call_user_func(object(Closure), object(Message)) in Mailer.php line 413
at Mailer->callMessageBuilder(object(Closure), object(Message)) in Mailer.php line 207
at Mailer->send('email.user_verification_change_email', array('user' => object(User), 'connection' => null, 'queue' => null, 'delay' => null, 'message' => object(Message)), object(Closure)) in Mailable.php line 117
at Mailable->send(object(Mailer)) in Mailer.php line 192
at Mailer->send(object(UserConfirmationChangeEmail)) in MailableMailer.php line 99
at MailableMailer->send(object(UserConfirmationChangeEmail)) in SendConformationEmailChangedEmail.php line 35
at SendConformationEmailChangedEmail->handle(object(UserEmailChanged))
at call_user_func_array(array(object(SendConformationEmailChangedEmail), 'handle'), array(object(UserEmailChanged))) in Dispatcher.php line 354
at Dispatcher->Illuminate\Events\{closure}(object(UserEmailChanged))
at call_user_func_array(object(Closure), array(object(UserEmailChanged))) in Dispatcher.php line 221
at Dispatcher->fire('App\Events\Users\UserEmailChanged') in helpers.php line 480
at event(object(UserEmailChanged)) in InstructorControllerAdmin.php line 198
at InstructorControllerAdmin->update(object(Request), object(User))
at call_user_func_array(array(object(InstructorControllerAdmin), 'update'), array(object(Request), 'users_admin' => object(User))) in Controller.php line 55
at Controller->callAction('update', array(object(Request), 'users_admin' => object(User))) in ControllerDispatcher.php line 44
at ControllerDispatcher->dispatch(object(Route), object(InstructorControllerAdmin), 'update') in Route.php line 189
at Route->runController() in Route.php line 144
at Route->run(object(Request)) in Router.php line 653
at Router->Illuminate\Routing\{closure}(object(Request)) in Pipeline.php line 53
at Pipeline->Illuminate\Routing\{closure}(object(Request)) in Authenticate.php line 29
at Authenticate->handle(object(Request), object(Closure), 'admins') in Pipeline.php line 137
at Pipeline->Illuminate\Pipeline\{closure}(object(Request)) in Pipeline.php line 33
at Pipeline->Illuminate\Routing\{closure}(object(Request)) in SubstituteBindings.php line 41
at SubstituteBindings->handle(object(Request), object(Closure)) in Pipeline.php line 137
at Pipeline->Illuminate\Pipeline\{closure}(object(Request)) in Pipeline.php line 33
at Pipeline->Illuminate\Routing\{closure}(object(Request)) in VerifyCsrfToken.php line 65
at VerifyCsrfToken->handle(object(Request), object(Closure)) in Pipeline.php line 137
at Pipeline->Illuminate\Pipeline\{closure}(object(Request)) in Pipeline.php line 33
at Pipeline->Illuminate\Routing\{closure}(object(Request)) in ShareErrorsFromSession.php line 49
at ShareErrorsFromSession->handle(object(Request), object(Closure)) in Pipeline.php line 137
at Pipeline->Illuminate\Pipeline\{closure}(object(Request)) in Pipeline.php line 33
at Pipeline->Illuminate\Routing\{closure}(object(Request)) in StartSession.php line 64
at StartSession->handle(object(Request), object(Closure)) in Pipeline.php line 137
at Pipeline->Illuminate\Pipeline\{closure}(object(Request)) in Pipeline.php line 33
at Pipeline->Illuminate\Routing\{closure}(object(Request)) in AddQueuedCookiesToResponse.php line 37
at AddQueuedCookiesToResponse->handle(object(Request), object(Closure)) in Pipeline.php line 137
at Pipeline->Illuminate\Pipeline\{closure}(object(Request)) in Pipeline.php line 33
at Pipeline->Illuminate\Routing\{closure}(object(Request)) in EncryptCookies.php line 59
at EncryptCookies->handle(object(Request), object(Closure)) in Pipeline.php line 137
at Pipeline->Illuminate\Pipeline\{closure}(object(Request)) in Pipeline.php line 33
at Pipeline->Illuminate\Routing\{closure}(object(Request)) in Pipeline.php line 104
at Pipeline->then(object(Closure)) in Router.php line 655
at Router->runRouteWithinStack(object(Route), object(Request)) in Router.php line 629
at Router->dispatchToRoute(object(Request)) in Router.php line 607
at Router->dispatch(object(Request)) in Kernel.php line 268
at Kernel->Illuminate\Foundation\Http\{closure}(object(Request)) in Pipeline.php line 53
at Pipeline->Illuminate\Routing\{closure}(object(Request)) in RedirectsMissingPages.php line 13
at RedirectsMissingPages->handle(object(Request), object(Closure)) in Pipeline.php line 137
at Pipeline->Illuminate\Pipeline\{closure}(object(Request)) in Pipeline.php line 33
at Pipeline->Illuminate\Routing\{closure}(object(Request)) in CheckForMaintenanceMode.php line 46
at CheckForMaintenanceMode->handle(object(Request), object(Closure)) in Pipeline.php line 137
at Pipeline->Illuminate\Pipeline\{closure}(object(Request)) in Pipeline.php line 33
at Pipeline->Illuminate\Routing\{closure}(object(Request)) in Pipeline.php line 104
at Pipeline->then(object(Closure)) in Kernel.php line 150
at Kernel->sendRequestThroughRouter(object(Request)) in Kernel.php line 117
at Kernel->handle(object(Request)) in index.php line 53

A: Make sure that

*

*FROM, TO and REPLY-TO fields are valid, working email addresses

*Domain names are valid

*There are no spaces or other strange characters in addresses (Did you check there are no non-ASCII characters which look like ASCII in string?)

Did you check PHP error logs?


text:
Q: Spring MVC - Error instantiating servlet class I am trying to learn Spring MVC and have gotten into some problems. I suppose there is something wrong either in my web.xml or servlet-config.xml files. When I type localhost:8080/FitnessTracker/greeting.html I get the following error:

HTTP Status 500 - Error instantiating servlet class
  org.springframwork.web.servlet.DispatcherServlet

My web.xml file below:
<web-app id="WebApp_ID" version="2.4"
    xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
    http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">

    <display-name>Spring Web MVC Application</display-name>

    <servlet>
        <servlet-name>fitTrackerServlet</servlet-name>
        <servlet-class>org.springframwork.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>/WEB-INF/config/servlet-config.xml</param-value>
        </init-param>
    </servlet>

    <servlet-mapping>
        <servlet-name>fitTrackerServlet</servlet-name>
        <url-pattern>*.html</url-pattern>
    </servlet-mapping>
</web-app>

My servlet-config.xml file below:
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-3.2.xsd">

        <context:component-scan base-package="com.pluralsight.controller"></context:component-scan>

        <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
            <property name="prefix" value="/WEB-INF/jsp/"/>
            <property name="suffix" value=".jsp"/>
        </bean>

        <mvc:annotation-driven></mvc:annotation-driven>
</beans>

My controller:
package com.pluralsight.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class HelloController {

    @RequestMapping(value = "/greeting")
    public String sayHello(Model model){

        model.addAttribute("greeting", "hello world!");

        return "Hello";
    }

}

What could possible be wrong? Thanks in advance!

A: Replace the servlet class with the below code in web.xml
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>

You mentioned the wrong package name. Check the spelling of springframework in <servlet-class>in web.xml servlet mappings.
If java 8 is used, upgrade to spring version 4 to resolve any incompatibility issues

A: Try to change this line
localhost:8080/FitnessTracker/greeting.html

with this
localhost:8080/FitnessTracker/greeting

try to add the backslash like this in web.xml
 <url-pattern>/*</url-pattern>

A: Solved. My controller returned "Hello" instead of "hello" which is the name of the jsp file I want to show.


text:
Q: ASP.NET Core Newtonsoft Json length issue I have an ASP.NET Core application and I'm trying to return a long JSON object. However inspecting the response i see only half of my list.
I already specified some default configuration in my Startup.cs file:
services.AddMvc()
    .AddJsonOptions(option =>
    {
        option.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
        option.SerializerSettings.ContractResolver = new DefaultContractResolver();
    });

In ASP.NET MVC5 you could use JavaSerializer and specify the length property.
How can I achieve that using ASP.NET Core?
var json = JsonConvert.SerializeObject(FilteredData);


text:
Q: Splash screen immediately disappear on boot I have a Fujitsu Lifebook E780 with Ubuntu 18.04.3 LTS.
When i boot my PC in quiet splash mode after the purple screen I get a black screen for some second and then this splash screen,

But after less then a second the splash screen disappear leaving back just a black screen for the rest of the boot.
The boot is very slow (1 min 40s on average) and gives the following errors:
19:41:36 colord-sane: io/hpmud/pp.c 627: unable to read device-id ret=-1
19:41:25 bluetoothd: Failed to set mode: Blocked through rfkill (0x12)
19:41:25 spice-vdagent: Cannot access vdagent virtio channel /dev/virtio-ports/com.redhat.spice.0
19:41:20 pulseaudio: [pulseaudio] backend-ofono.c: Failed to register as a handsfree audio agent with ofono: org.freedesktop.DBus.Error.ServiceUnknown: The name org.ofono was not provided by any .service files
19:41:11 wpa_supplicant: dbus: Failed to construct signal
19:40:56 bluetoothd: Failed to set mode: Blocked through rfkill (0x12)
19:40:46 kernel: Bluetooth: hci0: unexpected event for opcode 0x0000
19:40:46 kernel: mei mei::55213584-9a29-4916-badf-0fb7ed682aeb:01: FW version command failed -5
19:40:21 kernel: ima: Error Communicating to TPM chip
19:40:21 kernel: ACPI: SPCR: Unexpected SPCR Access Width.  Defaulting to byte size

None of these errors seems to be somehow related to the splash screen problem but I'm not sure of this.
Here there is the /etc/default/grub content that shows my boot settings
# If you change this file, run 'update-grub' afterwards to update
# /boot/grub/grub.cfg.
# For full documentation of the options in this file, see:
#   info -f grub -n 'Simple configuration'

GRUB_DEFAULT=0
GRUB_TIMEOUT_STYLE=hidden
GRUB_TIMEOUT=0
GRUB_DISTRIBUTOR=`lsb_release -i -s 2> /dev/null || echo Debian`
GRUB_CMDLINE_LINUX_DEFAULT="quiet splash"
GRUB_CMDLINE_LINUX=""

# Uncomment to enable BadRAM filtering, modify to suit your needs
# This works with Linux (no patch required) and with any kernel that obtains
# the memory map information from GRUB (GNU Mach, kernel of FreeBSD ...)
#GRUB_BADRAM="0x01234567,0xfefefefe,0x89abcdef,0xefefefef"

# Uncomment to disable graphical terminal (grub-pc only)
#GRUB_TERMINAL=console

# The resolution used on graphical terminal
# note that you can use only modes which your graphic card supports via VBE
# you can see them in real GRUB with the command `vbeinfo'
#GRUB_GFXMODE=640x480

# Uncomment if you don't want GRUB to pass "root=UUID=xxx" parameter to Linux
#GRUB_DISABLE_LINUX_UUID=true

# Uncomment to disable generation of recovery mode menu entries
#GRUB_DISABLE_RECOVERY="true"

# Uncomment to get a beep at grub start
#GRUB_INIT_TUNE="480 440 1"

EDIT:
I have tried to use nomodeset and the splash screen warks fine(obviously with low resolution), so probably is same graphical driver issue
EDIT2:
I have just noticed that pressing esc make the splash screen show up, but this doesn't mean thet the problem is solved

A: The way I see it the output you shared are the reasons for the delay in boot.

*

*You can switch off / uninstall (Bluetooth for example) or install the correct drivers.

*Try looking up for each error on Google.

You can also disable the respective services like
Bluetoothd.
There is a lot of information regarding that on Google.
But I too get a black screen after the splash. So the only difference is the delay.
I suspect the maximum delay is with regards to the Wi-Fi chip. Find out the make and model of your Wi-Fi.
If that does not solve it, you could temporarily disable wireless on boot.
Moreover, since many of the errors are related to Kernel bugs, I would recommend you switch to a different flavor of Linux or Ubuntu ..and repeat the steps wrt Grub and see if you get the same errors.
You can try with a Live Cd first.
If you have a Preference wrt Linux then you are here to solve it.. Is spice-vdagent required for Wayland?
2. How do I disable ACPI when booting?
3. How can I deactivate Bluetooth on system startup?

A: Introduction to the problem
The part responsible for the splash screen is called Plymouth.
As reported by Wiki.ArchLinux:

Plymouth is a project from Fedora and now listed among the freedesktop.org's official resources providing a flicker-free graphical boot process. It relies on kernel mode setting (KMS) to set the native resolution of the display as early as possible, then provides an eye-candy splash screen leading all the way up to the login manager.

According to this if there is some problem with the splash screen Plymouth is the responsible.

Solutions
To solve the problem I came out with a bit drastical solution that worked for me, but before solve the problem in my way I suggest you to use the following safer solution even if I'm not sure it will be enough becouse i have not tested it.

*

*The more quiet solution
The only sure fact is that there is something wrong with the Plymonth, so the firt thing to try is to update the pakage because it could solve the problem end even if don't work surely will be painless.
To do this just use this command into the terminal:
sudo apt-get install plymouth

I was so sure it wouldn't have been enough that I haven't even tried to do this but is better give it a try.

*

*The dangerous solution
If updating Plymouth was not enough to solve the problem, you have to uninstall it and reinstall it.
NOTICE: Plymouth is an important part of ubuntu and I'm not expert enough to say how safe is to uninstall it.
To uninstall the package use this command:
sudo apt-get purge plymouth

Pay attention to the output of this command because in my case it gives:
...
The following packages will be REMOVED:
plymouth* plymouth-label* plymouth-theme-ubuntu-logo*
plymouth-theme-ubuntu-text* plymouth-x11*
0 aggiornati, 0 installati, 5 da rimuovere e 0 non aggiornati.
Dopo quest'operazione, verranno liberati 696 kB di spazio su disco.
Continuare? [S/n]

But i have read that in some cases it also tries to remove packages like ubuntu-desktop*.
If it is your case is safer for you to not go forward and answer no.
otherwise, the next step to do is to reinstall it:
sudo apt-get install plymouth

Then reboot your system and the splash screen will appear but with this theme:

To change the theme, use the following command to display the list of available themes
aptitude search plymouth-theme

Then use this command to install the one you want (the default is plymouth-theme-ubuntu-logo)
sudo aptitude install #PUT THE THEME NAME HERE#

For example, to install the default theme the syntax is:
sudo aptitude install plymouth-theme-ubuntu-logo

This solved my problem and now the splash screen appear after just 6 seconds from the BIOS screen and don't disappear until the end of the boot


text:
Q: Is possible to add post-formats to custom-post-type? I was wondering if there is some way to put together the custom-post-types and post-formats so I can code a new post type and offer some variations as post-formats.
I'm involved in a company directory conceptualization and we have to mix different kind of company. While almost all of this types share the same data fields, there are two specific kind of companies - hotels & bistros - which has especific requirements (custom taxonomies and some data fields).
In your opinion, which is the best approach?

*

*Use three custom-post-type: 'company', 'bistro' & 'hotel'.

*Use one custom-post-type w/ post-formats.

*Use only one custom-post-type and use conditional logic to add or not specific data-models.

Thanks in advance!!!
Xavier

A: For those coming here because of the title of the question:
If you have a look at Post Formats at the Codex you'll see that

[...] New formats cannot be introduced by themes or even plugins. [...]

Which kills you're option 2.
Also have a look at this: Custom Post Formats
For your apparent actual question:
It really depends on how much they differ. But if they have different taxonomies and different data fields I'd say have separate post types.


text:
Q: What HDD to use as an *external* internal drive instead of optical drive in a MacBook Pro early 2011? I was wondering if there are any recommendations on which HDD (Brand, Model) is best to be used in a MacBook Pro early 2011 13" (running El Capitan).
I'm planning on exchanging my optical drive for an internal HDD to use in combination with my Crucial M4 SSD 256GB that I'm using atm.
Here's the case that will hold the HDD.


text:
Q: Java Nested If Help (The Logic is seemingly correct but always outputs the same thing) I am trying to use nested if statements in order to determine the value of a variable and with this code, the correct results are not occurring. Please can someone help? I am using an array to hold values that are being compared to the input (using this in order to show "knowledge" of java). Then, I am calling the function testFlower() to initialize the logic. I am not able to identify where in my logic I went wrong. Every time anything is inputted, the result that is printed out by the print line is always "Roses". This returned String should change when different flower names are typed in but this does not occur. Does anybody have any ideas on the issue in the code?
import java.util.Scanner;

public class A {

    public final double TAX = 1.127;
    public final double s_basket = 10, m_basket = 20, l_basket = 30, s_elephant = 15, l_elephant = 30,
             s_seal = 15, l_seal = 30, s_bear = 15, l_bear = 30, s_penguin = 15, l_penguin = 30,
             mChocolate = 15, wChocolate = 20, dChocolate = 30;

    public String flowers[] = {"ROSE", "TULIP", "DAISY", "DAFFODIL", "SUNFLOWER", "ORCHID"};

    public Scanner s = new Scanner(System.in);

    public String flowerType;

    public void testFlower() {
        if (!(flowerType.equals(flowers[1]))) {
            if (!(flowerType.equals(flowers[2]))) {
                if (!(flowerType.equals(flowers[3]))) {
                    if (!(flowerType.equals(flowers[4]))) {
                        if (!(flowerType.equals(flowers[5]))) {
                            flowerType = "Roses";
                            System.out.println(flowerType);
                        } else {
                            flowerType = "Orchids";
                            System.out.println(flowerType);
                        }
                    } else {
                        flowerType = "Sunflowers";
                        System.out.println(flowerType);
                    }
                } else {
                    flowerType = "Daffodils";
                    System.out.println(flowerType);
                }
            } else {
                flowerType = "Daises";
                System.out.println(flowerType);
            }
        } else {
            flowerType = "Tulips";
            System.out.println(flowerType);
        }
    }

    public static void main(String[] args) {
        A a = new A();

        System.out.println("Hello! Welcome to my flower shop! What type of flowers do you want? (rose, tulip, daisy, daffodil, sunflower, orchid)");
        a.flowerType = a.s.nextLine();
        a.flowerType.toUpperCase();

        a.testFlower();

    }
}

A: As chrylis said in the previous answer, your uppercasing is incorrect. But I also would point out that you don't have to use nested if/else statements, since Java has a HashMap class, which can be used with objects as keys. See the following code:
public HashMap<String, String> flowers = new HashMap<String, String>();
flowers.put("ROSE", "Roses");
...
flowers.put("ORCHID", "Orchids");

//this code basically replaces your testFlower function.
System.out.println(flowers.get(flowerType));

I hope I didn't misunderstand the purpose of your program. In case I did, please disregard my answer.

A: First, learn to use a debugger and inspect values such as flowerType. Doing so would immediately have shown you that the uppercasing doesn't do what you expect: You have to assign the result to a variable, since the string is immutable.
a.flowerType = a.s.nextLine();
a.flowerType = a.flowerType.toUpperCase();

A: If you change the values in the array to
"ROSES", "TULIPS", "DAISIES", "DAFFODILSS", "SUNFLOWERS", "ORCHIDS"

Use a for loop instead of nested if-statements (saves a lot of typing):
for(int i =0; i < flowers.length;i++){
    if(flowers[i].equals(flowerType){
        system.out.println(flowerType);
        break;
    } else if (i == flowers.length - 1) {
        system.out.println("Unknown flowertype " + flowerType);
    }
}

Use a parameter for the flower method:
a.flowerType = a.s.nextLine();
a.flowerType = a.flowerType.toUpperCase();
a.testFlower(flowerType);

public void testFlower(String f){
    flowerType = f;
    // do something
}

Like this your program could work.


text:
Q: SVG relative position I have the following svg shape. How can I make it relative to the div container?
fiddle: http://jsfiddle.net/8421w8hc/20/
<div>

    <svg  viewBox="0 0 1000 2112" style="" xmlns="http://www.w3.org/2000/svg" version="1.1">

        <path id="ma" stroke-linejoin="round" stroke-width="3" d="M276.53125,21.0625C270.2435,21.1337,264.6632,29.710064,257.625,38.15625C254.2095,42.255008000000004,246.70916,40.314622,242.1875,46.34375C236.65521,53.720438,230.99785,62.346888,226.46875,69.59375C215.85686,86.573459,230.16928,97.782258,212.125,111.1875C207.10965,114.77674999999999,201.08841999999999,115.97395,197.6875,119.375C192.96555,124.09715,192.80861,146.86201,183.5,153.84375C179.2572,157.02598,177.89186,161.88925,174.34375,165.4375C171.68483,168.09653,165.60417999999999,166.5658,163.375,170.28125C159.25578,177.1469,152.38471,200.19938,145.5625,203.6875C135.98604,208.58383,130.12789,210.84282,127.15625,215.15625C124.21798,219.42123,128.21307,221.02478,120.40625,232.65625C116.20943,238.90915,125.44735,245.58204,127.5,249.6875C130.03318,254.75407,121.95861,264.95404,121.4375,266.34375C116.03641999999999,273.13373,110.82711,279.75904,106.0625,286.90625C104.9172,288.62427,104.41387,291.14857,103,292.5625C101.23068,294.33189,100.92556,298.02625,99.375,300.09375C98.25112,301.59231,98.340978,305.27722,97.5625,307.09375C96.151137,310.38706,99.710576,316.2122,100.59375,319.15625C101.74974,323.00968,102.93777,328.35011,106.25,331C108.44205,332.75371,110.92774,335.24016,113,337.3125C115.21027,339.52286,119.50015,339.84377,122.125,341.34375C123.7939,342.29745,125.21469,344.74589,126.65625,346.1875C131.13587,350.66731,130.14474,359.6758,134.6875,364.21875C140.22073,369.7522,147.72669,372.17836,151.0625,379.40625C151.6216,380.61769,152.22093,382.11301,152.78125,383.75C153.30442,384.12705,153.81841,384.52134,154.34375,384.96875C159.49011,382.16219,192.47898,377.45858,194.125,375.8125C201.6757,368.26149,216.63142,331.12495,220.25,319.0625C223.11402,309.51541,224.60791,292.67363,231.75,285.53125C238.94927,278.33169,243.64201,268.57702,250.59375,261.625C255.44103,256.77752,268.37051,251.81277,270.40625,247.0625C272.02917,243.27554,261.87965,212.73681,268.09375,194.09375C273.12962,178.98553,292.55847,176.39929,295.6875,165.96875C298.4306,156.82473,307.59017,148.35643,312.5,138.78125C311.95901,138.28635,311.42663,137.7704,310.90625,137.25C306.57248,132.91606,301.96542,134.44373,297.34375,128.28125C294.72734,124.79256,299.28371,117.00322,296.53125,113.5625C293.76217,110.10102,290.4536,104.92346,289.03125,100.65625C286.52797,93.146115,292.375,82.479489,292.375,74.34375C292.375,72.274832,306.32062,71.292295,302.375,66.03125C298.36618,60.685944,297.79382,50.044012,293.28125,45.53125C290.88005,43.129956,297.01201,34.334683,294.71875,32.5C293.39881,31.444011,290.24045,33.879986,289.09375,31.96875C284.34165,24.048267,280.3039,21.019778000000002,276.53125,21.0625Z" stroke="#ffffff" fill="#e9eaee" style="cursor: default; stroke-linejoin: round;"></path>
    </svg>
</div>

A: I am assuming you want the map shapes on the left to all appear at the same place.
One way you can do that is to get the bounding box of the path and offset it by the x and y position.
$("path").hover(function() {
    var  bbox = this.getBBox();
    var d = $(this).attr("d");
    $("#city_map").html('<svg ... snip ...
      <path...  transform="translate('+(-bbox.x)+','+(-bbox.y)+')"></path></svg>');
});

Demo here


text:
Q: Enforcing statement order in C++ Suppose I have a number of statements that I want to execute in
a fixed order. I want to use g++ with optimization level 2, so some
statements could be reordered. What tools does one have to enforce a certain ordering of statements?
Consider the following example.
using Clock = std::chrono::high_resolution_clock;

auto t1 = Clock::now(); // Statement 1
foo();                  // Statement 2
auto t2 = Clock::now(); // Statement 3

auto elapsedTime = t2 - t1;

In this example it is important that the statements 1-3 are executed in
the given order. However, can't the compiler think statement 2 is
independent of 1 and 3 and execute the code as follows?
using Clock=std::chrono::high_resolution_clock;

foo();                  // Statement 2
auto t1 = Clock::now(); // Statement 1
auto t2 = Clock::now(); // Statement 3

auto elapsedTime = t2 - t1;

A: Summary:
There seems to be no guaranteed way to prevent reordering, but as long as link-time/full-program optimisation is not enabled, locating the called function in a separate compilation unit seems a fairly good bet.  (At least with GCC, although logic would suggest that this is likely with other compilers too.)  This comes at the cost of the function call - inlined code is by definition in the same compilation unit and open to reordering.
Original answer:
GCC reorders the calls under -O2 optimisation:
#include <chrono>
static int foo(int x)    // 'static' or not here doesn't affect ordering.
{
    return x*2;
}
int fred(int x)
{
    auto t1 = std::chrono::high_resolution_clock::now();
    int y = foo(x);
    auto t2 = std::chrono::high_resolution_clock::now();
    return y;
}

GCC 5.3.0:
g++ -S --std=c++11 -O0 fred.cpp :
_ZL3fooi:
        pushq   %rbp
        movq    %rsp, %rbp
        movl    %ecx, 16(%rbp)
        movl    16(%rbp), %eax
        addl    %eax, %eax
        popq    %rbp
        ret
_Z4fredi:
        pushq   %rbp
        movq    %rsp, %rbp
        subq    $64, %rsp
        movl    %ecx, 16(%rbp)
        call    _ZNSt6chrono3_V212system_clock3nowEv
        movq    %rax, -16(%rbp)
        movl    16(%rbp), %ecx
        call    _ZL3fooi
        movl    %eax, -4(%rbp)
        call    _ZNSt6chrono3_V212system_clock3nowEv
        movq    %rax, -32(%rbp)
        movl    -4(%rbp), %eax
        addq    $64, %rsp
        popq    %rbp
        ret

But:
g++ -S --std=c++11 -O2 fred.cpp :
_Z4fredi:
        pushq   %rbx
        subq    $32, %rsp
        movl    %ecx, %ebx
        call    _ZNSt6chrono3_V212system_clock3nowEv
        call    _ZNSt6chrono3_V212system_clock3nowEv
        leal    (%rbx,%rbx), %eax
        addq    $32, %rsp
        popq    %rbx
        ret

Now, with foo() as an extern function:
#include <chrono>
int foo(int x);
int fred(int x)
{
    auto t1 = std::chrono::high_resolution_clock::now();
    int y = foo(x);
    auto t2 = std::chrono::high_resolution_clock::now();
    return y;
}

g++ -S --std=c++11 -O2 fred.cpp :
_Z4fredi:
        pushq   %rbx
        subq    $32, %rsp
        movl    %ecx, %ebx
        call    _ZNSt6chrono3_V212system_clock3nowEv
        movl    %ebx, %ecx
        call    _Z3fooi
        movl    %eax, %ebx
        call    _ZNSt6chrono3_V212system_clock3nowEv
        movl    %ebx, %eax
        addq    $32, %rsp
        popq    %rbx
        ret

BUT, if this is linked with -flto (link-time optimisation):
0000000100401710 <main>:
   100401710:   53                      push   %rbx
   100401711:   48 83 ec 20             sub    $0x20,%rsp
   100401715:   89 cb                   mov    %ecx,%ebx
   100401717:   e8 e4 ff ff ff          callq  100401700 <__main>
   10040171c:   e8 bf f9 ff ff          callq  1004010e0 <_ZNSt6chrono3_V212system_clock3nowEv>
   100401721:   e8 ba f9 ff ff          callq  1004010e0 <_ZNSt6chrono3_V212system_clock3nowEv>
   100401726:   8d 04 1b                lea    (%rbx,%rbx,1),%eax
   100401729:   48 83 c4 20             add    $0x20,%rsp
   10040172d:   5b                      pop    %rbx
   10040172e:   c3                      retq

A: No it can't. According to the C++ standard [intro.execution]:

14 Every value computation and side effect associated with a
  full-expression is sequenced before every value computation and side
  effect associated with the next full-expression to be evaluated.

A full-expression is basically a statement terminated by a semicolon. As you can see the above rule stipulates statements must be executed in order. It is within statements that the compiler is allowed more free rein (i.e. it is under some circumstance allowed to evaluate expressions that make up a statement in orders other than left-to-right or anything else specific).
Note the conditions for the as-if rule to apply are not met here. It is unreasonable to think that any compiler would be able to prove that reordering calls to get the system time would not affect observable program behaviour. If there was a circumstance in which two calls to get the time could be reordered without changing observed behaviour, it would be extremely inefficient to actually produce a compiler that analyses a program with enough understanding to be able to infer this with certainty.

A: Reordering may be done by the compiler, or by the processor.
Most compilers offer a platform-specific method to prevent reordering of read-write instructions. On gcc, this is
asm volatile("" ::: "memory");

(More information here)
Note that this only indirectly prevents reordering operations, as long as they depend on the reads / writes.
In practice I haven't yet seen a system where the system call in Clock::now() does have the same effect as such a barrier. You could inspect the resulting assembly to be sure.
It is not uncommon, however, that the function under test gets evaluated during compile time. To enforce "realistic" execution, you may need to derive input for foo() from I/O or a volatile read.

Another option would be to disable inlining for foo() - again, this is compiler  specific and usually not portable, but would have the same effect.
On gcc, this would be __attribute__ ((noinline))

@Ruslan brings up a fundamental issue: How realistic is this measurement?
Execution time is affected by many factors: one is the actual hardware we are running on, the other is concurrent access to shared resources like cache, memory, disk and CPU cores.
So what we usually do to get comparable timings: make sure they are reproducible with a low error margin. This makes them somewhat artificial.
"hot cache" vs. "cold cache" execution performance can easily differ by an order of magnitude - but in reality, it will be something inbetween ("lukewarm"?)

A: I'd like to try to provide a somewhat more comprehensive answer after this was discussed with the C++ standards committee. In addition to being a member of the C++ committee, I'm also a developer on the LLVM and Clang compilers.
Fundamentally, there is no way to use a barrier or some operation in the sequence to achieve these transformations. The fundamental problem is that the operational semantics of something like an integer addition are totally known to the implementation. It can simulate them, it knows they cannot be observed by correct programs, and is always free to move them around.
We could try to prevent this, but it would have extremely negative results and would ultimately fail.
First, the only way to prevent this in the compiler is to tell it that all of these basic operations are observable. The problem is that this then would preclude the overwhelming majority of compiler optimizations. Inside the compiler, we have essentially no good mechanisms to model that the timing is observable but nothing else. We don't even have a good model of what operations take time. As an example, does converting a 32-bit unsigned integer to a 64-bit unsigned integer take time? It takes zero time on x86-64, but on other architectures it takes non-zero time. There is no generically correct answer here.
But even if we succeed through some heroics at preventing the compiler from reordering these operations, there is no guarantee this will be enough. Consider a valid and conforming way to execute your C++ program on an x86 machine: DynamoRIO. This is a system that dynamically evaluates the machine code of the program. One thing it can do is online optimizations, and it is even capable of speculatively executing the entire range of basic arithmetic instructions outside of the timing. And this behavior isn't unique to dynamic evaluators, the actual x86 CPU will also speculate (a much smaller number of) instructions and reorder them dynamically.
The essential realization is that the fact that arithmetic isn't observable (even at the timing level) is something that permeates the layers of the computer. It is true for the compiler, the runtime, and often even the hardware. Forcing it to be observable would both dramatically constrain the compiler, but it would also dramatically constrain the hardware.
But all of this should not cause you to lose hope. When you want to time the execution of basic mathematical operations, we have well studied techniques that work reliably. Typically these are used when doing micro-benchmarking. I gave a talk about this at CppCon2015: https://youtu.be/nXaxk27zwlk
The techniques shown there are also provided by various micro-benchmark libraries such as Google's: https://github.com/google/benchmark#preventing-optimization
The key to these techniques is to focus on the data. You make the input to the computation opaque to the optimizer and the result of the computation opaque to the optimizer. Once you've done that, you can time it reliably. Let's look at a realistic version of the example in the original question, but with the definition of foo fully visible to the implementation. I've also extracted a (non-portable) version of DoNotOptimize from the Google Benchmark library which you can find here: https://github.com/google/benchmark/blob/v1.0.0/include/benchmark/benchmark_api.h#L208
#include <chrono>

template <class T>
__attribute__((always_inline)) inline void DoNotOptimize(const T &value) {
  asm volatile("" : "+m"(const_cast<T &>(value)));
}

// The compiler has full knowledge of the implementation.
static int foo(int x) { return x * 2; }

auto time_foo() {
  using Clock = std::chrono::high_resolution_clock;

  auto input = 42;

  auto t1 = Clock::now();         // Statement 1
  DoNotOptimize(input);
  auto output = foo(input);       // Statement 2
  DoNotOptimize(output);
  auto t2 = Clock::now();         // Statement 3

  return t2 - t1;
}

Here we ensure that the input data and the output data are marked as un-optimizable around the computation foo, and only around those markers are the timings computed. Because you are using data to pincer the computation, it is guaranteed to stay between the two timings and yet the computation itself is allowed to be optimized. The resulting x86-64 assembly generated by a recent build of Clang/LLVM is:
% ./bin/clang++ -std=c++14 -c -S -o - so.cpp -O3
        .text
        .file   "so.cpp"
        .globl  _Z8time_foov
        .p2align        4, 0x90
        .type   _Z8time_foov,@function
_Z8time_foov:                           # @_Z8time_foov
        .cfi_startproc
# BB#0:                                 # %entry
        pushq   %rbx
.Ltmp0:
        .cfi_def_cfa_offset 16
        subq    $16, %rsp
.Ltmp1:
        .cfi_def_cfa_offset 32
.Ltmp2:
        .cfi_offset %rbx, -16
        movl    $42, 8(%rsp)
        callq   _ZNSt6chrono3_V212system_clock3nowEv
        movq    %rax, %rbx
        #APP
        #NO_APP
        movl    8(%rsp), %eax
        addl    %eax, %eax              # This is "foo"!
        movl    %eax, 12(%rsp)
        #APP
        #NO_APP
        callq   _ZNSt6chrono3_V212system_clock3nowEv
        subq    %rbx, %rax
        addq    $16, %rsp
        popq    %rbx
        retq
.Lfunc_end0:
        .size   _Z8time_foov, .Lfunc_end0-_Z8time_foov
        .cfi_endproc

        .ident  "clang version 3.9.0 (trunk 273389) (llvm/trunk 273380)"
        .section        ".note.GNU-stack","",@progbits

Here you can see the compiler optimizing the call to foo(input) down to a single instruction, addl %eax, %eax, but without moving it outside of the timing or eliminating it entirely despite the constant input.
Hope this helps, and the C++ standards committee is looking at the possibility of standardizing APIs similar to DoNotOptimize here.

A: The C++ language defines what is observable in a number of ways.
If foo() does nothing observable, then it can be eliminated completely.  If foo() only does a computation that stores values in "local" state (be it on the stack or in an object somewhere), and the compiler can prove that no safely-derived pointer can get into the Clock::now() code, then there are no observable consequences to moving the Clock::now() calls.
If foo() interacted with a file or the display, and the compiler cannot prove that Clock::now() does not interact with the file or the display, then reordering cannot be done, because interaction with a file or display is observable behavior.
While you can use compiler-specific hacks to force code not to move around (like inline assembly), another approach is to attempt to outsmart your compiler.
Create a dynamically loaded library.  Load it prior to the code in question.
That library exposes one thing:
namespace details {
  void execute( void(*)(void*), void *);
}

and wraps it like this:
template<class F>
void execute( F f ) {
  struct bundle_t {
    F f;
  } bundle = {std::forward<F>(f)};

  auto tmp_f = [](void* ptr)->void {
    auto* pb = static_cast<bundle_t*>(ptr);
    (pb->f)();
  };
  details::execute( tmp_f, &bundle );
}

which packs up a nullary lambda and uses the dynamic library to run it in a context that the compiler cannot understand.
Inside the dynamic library, we do:
void details::execute( void(*f)(void*), void *p) {
  f(p);
}

which is pretty simple.
Now to reorder the calls to execute, it must understand the dynamic library, which it cannot while compiling your test code.
It can still eliminate foo()s with zero side effects, but you win some, you lose some.

A: No.
Sometimes, by the "as-if" rule, statements may be re-ordered. This is not because they are logically independent of each other, but because that independence allows such a re-ordering to occur without changing the semantics of the program.
Moving a system call that obtains the current time obviously does not satisfy that condition. A compiler that knowingly or unknowingly does so is non-compliant and really silly.
In general, I wouldn't expect any expression that results in a system call to be "second-guessed" by even an aggressively optimizing compiler. It just doesn't know enough about what that system call does.

A: noinline function + inline assembly black box + full data dependencies
This is based on https://stackoverflow.com/a/38025837/895245 but because I didn't see any clear justification of why the ::now() cannot be reordered there, I would rather be paranoid and put it inside a noinline function together with the asm.
This way I'm pretty sure the reordering cannot happen, since the noinline "ties" the the ::now and the data dependency.
main.cpp
#include <chrono>
#include <iostream>
#include <string>

// noinline ensures that the ::now() cannot be split from the __asm__
template <class T>
__attribute__((noinline)) auto get_clock(T& value) {
    // Make the compiler think we actually use / modify the value.
    // It can't "see" what is going on inside the assembly string.
    __asm__ __volatile__ ("" : "+g" (value));
    return std::chrono::high_resolution_clock::now();
}

template <class T>
static T foo(T niters) {
    T result = 42;
    for (T i = 0; i < niters; ++i) {
        result = (result * result) - (3 * result) + 1;
    }
    return result;
}

int main(int argc, char **argv) {
    unsigned long long input;
    if (argc > 1) {
        input = std::stoull(argv[1], NULL, 0);
    } else {
        input = 1;
    }

    // Must come before because it could modify input
    // which is passed as a reference.
    auto t1 = get_clock(input);
    auto output = foo(input);
    // Must come after as it could use the output.
    auto t2 = get_clock(output);
    std::cout << "output " << output << std::endl;
    std::cout << "time (ns) "
              << std::chrono::duration_cast<std::chrono::nanoseconds>(t2 - t1).count()
              << std::endl;
}

GitHub upstream.
Compile and run:
g++ -ggdb3 -O3 -std=c++14 -Wall -Wextra -pedantic -o main.out main.cpp
./main.out 1000
./main.out 10000
./main.out 100000

The only minor downside of this method is that we add one extra callq instruction over an inline method. objdump -CD shows that main contains:
    11b5:       e8 26 03 00 00          callq  14e0 <auto get_clock<unsigned long long>(unsigned long long&)>
    11ba:       48 8b 34 24             mov    (%rsp),%rsi
    11be:       48 89 c5                mov    %rax,%rbp
    11c1:       b8 2a 00 00 00          mov    $0x2a,%eax
    11c6:       48 85 f6                test   %rsi,%rsi
    11c9:       74 1a                   je     11e5 <main+0x65>
    11cb:       31 d2                   xor    %edx,%edx
    11cd:       0f 1f 00                nopl   (%rax)
    11d0:       48 8d 48 fd             lea    -0x3(%rax),%rcx
    11d4:       48 83 c2 01             add    $0x1,%rdx
    11d8:       48 0f af c1             imul   %rcx,%rax
    11dc:       48 83 c0 01             add    $0x1,%rax
    11e0:       48 39 d6                cmp    %rdx,%rsi
    11e3:       75 eb                   jne    11d0 <main+0x50>
    11e5:       48 89 df                mov    %rbx,%rdi
    11e8:       48 89 44 24 08          mov    %rax,0x8(%rsp)
    11ed:       e8 ee 02 00 00          callq  14e0 <auto get_clock<unsigned long long>(unsigned long long&)>

so we see that foo was inlined, but get_clock were not and surround it.
get_clock itself however is extremely efficient, consisting of a single leaf call optimized instruction that doesn't even touch the stack:
00000000000014e0 <auto get_clock<unsigned long long>(unsigned long long&)>:
    14e0:       e9 5b fb ff ff          jmpq   1040 <std::chrono::_V2::system_clock::now()@plt>

Since the clock precision is itself limited, I think that is unlikely that you will be able to notice the timing effects of one extra jmpq. Note that one call is required regardless since ::now() is in a shared library.
Call ::now() from inline assembly with a data dependency
This would be the most efficient solution possible, overcoming even the extra jmpq mentioned above.
This is unfortunately extremely hard to do correctly as shown at: Calling printf in extended inline ASM
If your time measurement can be done directly in inline assembly without a call however, then this technique can be used. This is the case for example for gem5 magic instrumentation instructions, x86 RDTSC (not sure if this is representative anymore) and possibly other performance counters.
Related threads:

*

*Is it legal for a C++ optimizer to reorder calls to clock()?
Tested with GCC 8.3.0, Ubuntu 19.04.


text:
Q: PNG image is getting corrupted in Itext7 import static com.itextpdf.kernel.xmp.XMPUtils.decodeBase64;
import com.itextpdf.io.image.ImageData;
import com.itextpdf.io.image.ImageDataFactory;

public  void testPngImage() throws XMPException {
    String orignalImage =  https://gist.github.com/nil96/d9d54200e5329211d2d7455492716500;
    String base64Image = orignalImage.replaceFirst("data:image/png;base64,","");
    byte[] decodedBytes = decodeBase64(base64Image);
    ImageData imageData = ImageDataFactory.create(decodedBytes,true);
    imageData.getData();
}

when I print imageData.getData() I get byte array containing -1 only. Whereas expected png byte array should start with {-119, 80, 78, 71}. This is only happening for PNG images. I can create jpeg images successfully. I have attached png in gist https://gist.github.com/nil96/d9d54200e5329211d2d7455492716500
Am I missing something for initializing Image or is it a bug?
Dependency
<dependency>
    <groupId>com.itextpdf</groupId>
    <artifactId>itext7-core</artifactId>
    <version>7.0.7</version>
    <!--<version>7.1.8</version>-->
    <type>pom</type>
</dependency>

A: You appear to misunderstand the format of the data returned by imageData.getData(). You say

expected png byte array should start with {-119, 80, 78, 71};

but imageData contains no PNG anymore, it contains data in the raw PDF bitmap image format.
Furthermore you inspected those data returned by imageData.getData() very superficially, you claim

when I print imageData.getData() I get byte array containing -1 only

which is wrong: It indeed contains very many -1 entries but also some other byte values:

*

*255898 times -1

*12838 times -2

*3126 times -3
etc etc
And this actually is not very surprising, after all your image is nearly pure white with a bit of scribble on it:

The predominant white (RGB: 255, 255, 255) and near white (RGB values slightly smaller than 255) is the reason for the many -1 (or as unsigned bytes: 255), '-2' / '254', -3 / 253, ... values while the scribble is bringing in the few (unsigned) smaller bytes.

Am I missing something for initializing Image or is it a bug?

First and foremost it is no iText bug but exactly what is to be expected.
The question is what you want to do with those image data which are merely meant for embedding in PDFs after compression. Usually, therefore, iText users don't call getData() here themselves but instead create an iText image object from the image data and add it to a PDF:
ImageData data = ImageDataFactory.create(...);
Image img = new Image(data);

and then
Document document = ...;
document.add(img);

or
Canvas canvas = ...;
canvas.add(img);

or even
PdfCanvas pdfCanvas = ...;
pdfCanvas.addImage(data, ...);

and iText handles the actual image data under the hood.


text:
Q: Angular translate - partialLoader dynamically change urlTemplate I am using angular translate in my webapp. In specific, I use Asynchronous loaders with partialLoader.
An example of my config is:
$translateProvider.useLoader('$translatePartialLoader', {
  urlTemplate: '/i18n/{part}/{lang}.json'
});

As you can see, I specify the urlTemplate of all the json file. What if I want to pack all the *.js file for production and minify purpose?
When I minify all the *.js files, I have all my application deployed in app/* path. So the .json file are not anymore in the urlTemplate path specified in the $translateProvider.
How can I set dynamically the urlTemplate for the json translation files?


text:
Q: Display links from xml data How can I display a clickable a href link on my html page from data exported from a xml page? below is the code I'm using. All the data exports fine, just the links cannot be clicked. so basically if a user clicks the item1.html link in the exported table he gets directed to item1.html page
<?xml version="1.0" encoding="utf-8"?>

<textarea id="xmlcode" style="display:none">
<catalog>
  <cd>
    <title>Item1</title>
    <start>09:15</start>
    <stop>10:00</stop>
    <link>Item 1</link>
  </cd>
  <cd>
    <title>Item2</title>
    <start>10:15</start>
    <stop>11:00</stop>
    <link>Item 2</link>
 </cd>
   <cd>
      <title>Item3</title>
      <start>12:15</start>
      <stop>13:00</stop>
      <link>Item 3</link>
   </cd>
  <cd>
   <title>Item4</title>
   <start>14:15</start>
   <stop>15:00</stop>
   <link>Item 4</link>
 </cd>
  <cd>
   <title>Item5</title>
   <start>15:15</start>
   <stop>16:00</stop>
   <link>Item 5</link>
  </cd>
<catalog>
</textarea>

xsl
<textarea id="xsltcode" style="display:none">
<?xml version="1.0" encoding="ISO-8859-1"?>
<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

<xsl:template match="/">

timetable

    Start
    Stop
    Title
    Link

  <xsl:for-each select="catalog/cd">
  <xsl:sort select="start"/>

    <xsl:value-of select="start"/>
    <xsl:value-of select="stop"/>
    <xsl:value-of select="title"/>
    <xsl:value-of select="link"/>

  </xsl:for-each>

</xsl:template>
 </xsl:stylesheet>
</textarea>

script

Thanks
EDIT
Marcus Rickert -
"You need to replace
  <xsl:value-of select="link"/>

by
  <xsl:copy-of select="link/*"/>

since the former will only copy a text representation of the selected sub tree to your target        document. All tags will be lost. The latter will make a copy of your link tag. I've added a /* to make sure that the  tags themselves will not show up in the HTML. Most likely, they will be ignored but they are not required either."

A: You need to replace
<xsl:value-of select="link"/>

by
<xsl:copy-of select="link/*"/>

since the former will only copy a text representation of the selected sub tree to your target document. All tags will be lost. The latter will make a copy of your link tag.


text:
Q: scrolll in div pushing bottom or left I am doing an MVC 5, bootstrap Application.
I have a page with HTML tags. I know that in order to move up or down a page content it is necessary to embed inside a div with fixed width and height, so you have to scroll on both directions to reach all contents.
What I try to do, is to simulate phones scrolling, i mean, "push" (one touch) bottom or left in order to automatically scroll bottom or left inside the div.

                <div class="dvParPal"

It is a way to do it? with Jquery o bootstrap or HTML?
Thanks

A: You can do something like
$('html, body').animate({scrollTop: '0px'}, 300);

with jQuery to scroll to bottom or left.

A: If you want the scroll bars to always be there.

If you want the scroll bars to only show up when content is greater than the div.


text:
Q: Simple has_many through query I have Event-Tag association through Tagging.
In array tags = %w(tag1 tag2 tag3) I have tag names. I'd like to get all events tagged with one or more tags from this array. How can I do this?

A: Write a scope on Tag
class Tag < ActiveRecord::Base
  def self.with_names(names)
    where(name: names)
  end
end

Then write a scope on Event
class Event < ActiveRecord::Base
  def self.for_tags(tag_names)
    joins(:tags).
    merge(Tag.with_names(tag_names))
  end
end

Query for Events with tags like
tags = %w(tag1 tag2 tag3)
Event.for_tags(tags)

You might need to call uniq if you don't want duplicate Events that match more than one Tag.
Event.for_tags(tags).uniq

A: Finally I found an answer, thanks to Sontya's comment.
Event.includes(:tags).where(tags: {name: tags}) or
Event.includes(:tags).where("tags.name IN (?)", tags).references(:tags)


text:
Q:  only appends last input using cin I'm using a vector to store char* in the array by getting user input using cin. The input is received in a loop and everything works fine until I display the input. The last element that is put in the vector is displayed in all of the indexes.ie.if I put the string "hello" "world" "this' "is" "C++" using cin in a loop. The output is "C++" 5 times.
The code is below.
#include <iostream>
#include <vector>

using namespace std;

int main()
{
    char *str=new char[10];
    vector<char*> vec;
    int i=0;

    for( i=0; i<5; i++ )
    {
        cout<<"Enter string: ";
        cin>>str;
        vec.push_back(str);
    }

    for( i=0; i<5; i++ )
    {
        cout<<vec[i]<<" ";
    }

    return 0;
}

A: vec.push_back(str);

You are putting same address to the vector over and over again.
You will need to move this:
char *str=new char[10];

inside the loop.
And then not forget to call delete on each vector element.
As stated in comments, std::string is probably a better choice.

A: You are overwriting the string with every input.
char *str=new char[10];

creates one c-style string.  Then
cin>>str;

Fills it contents.  When you do
vec.push_back(str);

You copy a pointer to that string an put it into the vector.  Then when you loop again it overwrites str with what you input next.  Since all of the vector elements still point to the same string they will all have the same data.
What you needs is a std::string and then you can use
int main()
{
    std::string str;
    vector<std::string> vec;
    int i=0;

    for( i=0; i<5; i++ )
    {
        cout<<"Enter string: ";
        cin>>str;
        vec.push_back(str);
    }

    for( i=0; i<5; i++ )
    {
        cout<<vec[i]<<" ";
    }

    return 0;
}


text:
Q: Query Collection using Where with a less than or greater than statement in it? Does backbone collections using .where() or like function accept some form of less/greater-than statements such as <=, >=, <, >
I cant find anything in the documentation that says anything either way

A: No, where doesn't support that. From the fine manual:

where collection.where(attributes)
Return an array of all the models in a collection that match the passed attributes. Useful for simple cases of filter.

where is just a filter call in disguise so you can use filter (which is mixed into Backbone collections) directly for more complicated things:
var matches = collection.filter(function(m) {
    /* check model `m` here */
});


text:
Q: Text Labels in kivy are not being updated I am trying to display the numbers of attempts left from a player in a Kivy game. However, while the player can actually run out of attempts in the game, the attempts left are not being updated in the UI. I suspect that it is because the Label just display them once and need to be updated after or maybe it have something to do with Kivy ids.
A simplified version of the code is here
On the main.py we have:
class TreasureHuntGrid(GridLayout):
    attempts = 8
    board = [[0,0][0,0]]
    def __init__(self, *args, **kwargs):
        super(TreasureHuntGrid, self).__init__(*args, **kwargs)

    def lowerattempts(self, button):
        if condition:
            self.attempts = self.attempts - 1

On the .kv file we have:
AnchorLayout:
  anchor_y: 'bottom'
  anchor_x: 'left'
  TreasureHuntGrid:
     id: board
     size: min(self.parent.size), min(self.parent.size)
     size_hint: None, None
  Label:
     size_hint: (1.75, 1)
     height: sp(40)
     text:'You have {} attempts left'.format(board.attempts)

A: Make your attempts variable a kivy property, then the kv language will automatically bind to update when it changes:
from kivy.properties import NumericProperty

class TreasureHuntGrid(GridLayout):
    attempts = NumericProperty(0)
    ...


text:
Q: Windsor circular dependency of a transient-lifestyle component I've got a bunch of classes written like this:
public class MyService1 {
    public MyService1(MyService1Settings settings, <service-dependent list of dependencies filled by Windsor>) { ... }
}

which are registered in the Windsor like this:
container.Register(
    ...
    Component.For<MyService1>().LifestyleTransient(),
    Component.For<MyService2>().LifestyleTransient(),
    ...
);

container doesn't have any of the MyServiceXSettings types registered, so the only way to get a service is to resolve it from container like this:
TService service = windsorContainer.Resolve<TService>(new { settings });

The thing is, depending on the parameters in the settings object, one of the services tries to acquire another instance of its type with different settings object.
Something along the lines of:
public class MyService2 {
    public MyService2(MyService2Settings settings, <service-dependent list of dependencies filled by Windsor>)
    {
        this.uplink = settings.Counter == 1
            ? new AnotherUplink()
            : new RecursiveUplink(
                container.Resolve<MyService2>(new {
                    settings = new MyService2Settings(settings.Counter - 1)
                });
    }
}

This recursive dependency chain is finite (and is about 6 instances deep), but Windsor throws an exception when the first service tries to get another one, stating that it's a circular dependency.
I've advertised all the services as having Transient lifestyles and requesting them with custom parameters. Can I at least specify the maximum allowed depth of the recursion? Or am I missing another way I can do it?
another requirement: I can't use typed factories, because I've got quite many different types of those services, so generating many factory interfaces individually for those services would be undesired.

A:
container doesn't have any of the MyServiceXSettings types registered,
  so the only way to get a service is to resolve it from container like
  this:

You may also use a dedicated SubResolver or a DependsOn during component registration.
Executing code in a constructor(rather than a simply variable assignement) is a smell, even worst using the container: it should never leak in the application layer.
At the first sight, it seems you are using the settings only to choose the proper component within the constructor: that should be done at CompositionRoot, using a TypedFactory or also by naming convention(you may have multiple component registered for same intercace, but a given parameter name drives the component selection)

A: As per this answer, I went with lazy resolution.
/// <summary>
/// Represents single component instance producer.
/// </summary>
/// <typeparam name="TComponent">type of the component to create</typeparam>
public interface IComponentCreator<TComponent>
{
    /// <summary>
    /// Gets the created component.
    /// </summary>
    TComponent Component { get; }
}

/// <summary>
/// Creates the component only when it's first requested.
/// </summary>
/// <typeparam name="TComponent">type of the component to create</typeparam>
public class LazyCreator<TComponent> : IComponentCreator<TComponent>
{
    private readonly Func<TComponent> creatingFunction;
    private bool created;
    private TComponent component;

    public LazyCreator(Func<TComponent> creatingFunction)
    {
        this.creatingFunction = creatingFunction;
    }

    public TComponent Component
    {
        get
        {
            if (!created)
            {
                component = creatingFunction();
                created = true;
            }

            return component;
        }
    }
}

/// <summary>
/// Returns already created component.
/// </summary>
/// <typeparam name="TComponent">type of the component</typeparam>
public class ComponentContainer<TComponent> : IComponentCreator<TComponent>
{
    private readonly TComponent component;

    public ComponentContainer(TComponent component)
    {
        this.component = component;
    }

    public TComponent Component
    {
        get { return component; }
    }
}


text:
Q: Split Footer Content Into Left and Right

&copy 2015. Free Xbox Live Gold Membership and Free Xbox Live Gold Codes. All rights reserved.Contact Us!ToS

I have this footer code and right now I want the copyright to be on the left and then the Contact and TOS to be on the right aligned. However I have hard time just aligning the content to the right.

A:

&copy 2015. Free Xbox Live Gold Membership and Free Xbox Live Gold Codes. All rights reserved.

Contact Us! ToS

I suggest you to place the stylesheet in an external file and target the elements with class names. Inline style is not easy to maintain.


text:
Q: What kind of index on dates for a emp duty table? I have a query that gets all employee duties for a start date and end date against a database.
Basically the table would be like

*

*Emp

*Duty

*StartDate

*EndDate

Should I give indexing for dates? what kind etc? to make things easier on db level (orm level for me it would be an attribute to set).There will be huge data depending on number of employees off course (expected) , better safe than sorry?
Please advice.

A: A combined index on emp, startdate, enddate seems like a good choice. But it really depends on how you plan to access/query your data. A proper answer cannot really be given without knowning how your application works. Because in the end, the best solution is the solution that works for you.

A: Assuming you have a primary key on this table, I would use non clustered indices on the date fields if you need to search them oftenly - this is more important the more data you have in the table.
Adding only two more indexes on the table shouldn't hurt (though I wouldn't index all fields - that is asking for trouble!).


text:
Q: Submitting a form to external link (but a local action before doing so) I have a JSF-page in which the user can submit some data to an external link. However, before doing so I need to call a local action from a backing bean. In what way can I achieve this?
This is an example of my form (using vanilla HTML due to the external link action):
<form method="POST" action="https://EXTERNAL-LINK.com/">
    <input type="hidden" ... />
    <button>Submit</button>
</form>

So in short this is my case:

*

*Submitting the form my hitting the button

*Calling a local method from a bean

*Submitting the form to the external link

Any ideas on how to achieve this?

A: I would submit a JSF form via AJAX behind the scenes first and when the response arrives I would submit your plain HTML form to an external URL.
Example:
<script type="text/javascript">
    function jsf(data) {
        if(data.status == 'success') {
            document.getElementById('plain-submit').click();
        }
    }
    function normal() {
        document.getElementById('jsf-submit').click();
    }
</script>
...
<h:form prependId="false">
    ...
    <h:commandButton id="jsf-submit" action="#{bean.action} value="Submit" style="display:none">
        <f:ajax execute="@form" ... onevent="jsf"/>
    </h:commandButton>
</h:form>
<form method="POST" action="https://EXTERNAL-LINK.com/">
    ...
    <input id="button-submit" type="button" onclick="normal()" ...>Submit</input>
    <input id="plain-submit" type="submit" style="display:none">Submit</input>
</form>

Or it would be even easier to reverse the situation by making plain HTML form invisible, thus decreasing the number of JavaScript operations: you submit the (visible) JSF form via AJAX and then submit (invisible) plain HTML form when response successfully arrives back.

A: Change the <form> to <h:form> and other HTML components to JSF components, bind their values with your managed bean and let the user submit the data. Then, in your action method you evaluate the data and then use a library like Apache HttpClient to send a POST request to the URL you want/need.
This could be a raw example of this (based on your example).
JSF code
<h:form >
    <h:inputHidden value="#{bean.aField}" />
    <h:commandButton value="Submit" action="#{bean.anAction}" />
</h:form>

Managed bean code
@ManagedBean
@RequestScoped
public class Bean {
    private String aField;
    //constructor, getter and setter...
    public void anAction() {
        //do your form processing...
        HttpRequestHandler httpRequestHandler = new HttpRequestHandler();
        httpRequestHandler.handlePost(...); //send the arguments here
    }
}

public class HttpRequestHandler {
    public void handlePost(String ... parameters) {
        //you do the Apache HttpClient POST handling here
        //always create a class between your application and your third party libraries
        //code adapted from HttpClient examples: http://hc.apache.org/httpcomponents-client-ga/examples.html
        HttpClient httpclient = new DefaultHttpClient();
        try {
            HttpPost httpPost = new HttpPost(...);// your URL goes here
            //do as you please with the HttpPost request

        } finally {
            httpclient.getConnectionManager().shutdown();
        }
    }
}

If you don't want to add the Apache HttpClient library for this job, then you could use native Java classes like URLConnection as shown here: Using java.net.URLConnection to fire and handle HTTP requests


text:
Q: Not Able to connect mysql server running on docker container I am running sql server in docker container`
docker pull mysql/mysql-server:latest

docker run --name=my_sql -d -p 3306:3306 -e MYSQL_ROOT_PASSWORD=1234 mysql/mysql-server:latest

docker exec -it my_sql mysql -u root -p

#Create table in mysql running in container.
CREATE DATABASE hello_java CHARACTER SET utf8 COLLATE utf8_general_ci;

All of this is done successfully.
Now when I try to connnect to db using Java, I am getting error.
String url = "jdbc:mysql://192.168.56.101:3306/hello_java";
DriverManager.getConnection(url, "root", "1234");
System.out.println("Connection establised....");

192.168.56.101 is the ip of my VM. I am running Linux on VM.
I am getting communications link failure error.
I googled and found out few solutions on following links, but none of the worked for me.
Solving a "communications link failure" with JDBC and MySQL
How to connect with MySQL DB running as container in docker?
I made changes to /etc/my.cnf file, but it does not seem to help.
Thanks.

A: I did some more RnD and found the following solution.
String url = "jdbc:mysql://192.168.56.101:3306/mysql?allowPublicKeyRetrieval=true&useSSL=false";

Adding allowPublicKeyRetrieval=true&useSSL=false to the query helped me to connect with the database.
The following links were useful for solution.
Connection Java-MySql : Public Key Retrieval is not allowed
https://www.tutorialspoint.com/how-to-disable-establishing-ssl-connection-without-server-s-identity-verification-is-not-recommended-warning-when-connecting-to-mysql-database-in-java
Thanks.


text:
Q: Using Blaze Persistence optional parameter in subquery In Blaze Persistence, is there a way to use an optional parameter in a subquery?
In my current use case, let's say I have topics, users, and a third table called topic_last_seen to record the date at which each user has last read each topic. I would like to create an entity view for the Topic entity which also maps that date for each topic with the current user given as an "optional parameter". This is roughly what I've been trying:
@EntityView(Topic.class)
public interface TopicView
{
    @IdMapping
    Long getId();

    String getSummary();

    @MappingParameter("currentUserId")
    Long getCurrentUserId();

    @MappingSubquery(LastSeenDateSubqueryProvider.class)
    Date getLastSeenDate();

    class LastSeenDateSubqueryProvider implements SubqueryProvider
    {
        @Override
        public <T> T createSubquery(SubqueryInitiator<T> subqueryBuilder)
        {
            return subqueryBuilder.from(TopicLastSeen.class, "lastSeen")
                    .select("dateSeen")
                    .where("lastSeen.user.id").eqExpression("EMBEDDING_VIEW(currentUserId)")
                    .where("lastSeen.topic.id").eqExpression("EMBEDDING_VIEW(id)")
                    .end();
        }
    }
}

Unfortunately, this results in an exception:
java.lang.IllegalArgumentException: Attribute 'currentUserId' not found on type 'Topic'

Is there any way to use an optional parameter in a subquery like this at all? Or is there a different way to map this information? Changing the DB schema is not an option at this point.

A: Looks like I figured this out a possible suolution by trial and error. It seems that the "optional parameters" from EntityViewSetting can be used like regular parameters in JPQL:
return subqueryBuilder.from(TopicLastSeen.class, "lastSeen")
        .select("dateSeen")
        .where("lastSeen.user.id").eqExpression(":currentUserId")
        .where("lastSeen.topic.id").eqExpression("EMBEDDING_VIEW(id)")
        .end();

Unfortunately though, with this subquery mapping the currentUserId parameter is no longer "optional". When it is not set I get another exception:
org.hibernate.QueryException: Named parameter not bound : currentUserId


text:
Q: Cakephp 3 Full Calendar setup Does anyone have any experience of getting this (Cake 2 plugin) working with Cakephp 3? Is it just case of copying the files to what should be their relevant places in Cake 3?
I've been trying for a couple of hours - installing under plugins doesn't work - complaints about a missing controller. I address that by copying the controller files into the controller folder but that makes no difference (I renamed a file to match the controller it was looking for only for Cake to then complain about another controller referred in the first).
Any help, even a simple what should go where, would be appreciated.
For clarity, the plugin I was referring to was: https://github.com/silasmontgomery/CakePHP-Full-Calendar-Plugin rather than the jQuery fullcalendar...

A: A Cake 3 branch has been created by someone who knows a lot more about this than I.
It is here: Cake 3 Full Calendar
Tested, working.


text:
Q: Creating a text file that could be read using c fscanf This is my program using which I am trying to read a simple text file and store the output in an structure. The problem I am facing currently is on the while loop where it does not to work. File handle seems to read the file. Also, the input file has been created using a simple windows notepad with the given text - can this be a problem?
#include<process.h>
#include<stdio.h>
#include<conio.h>
#include<string.h>

struct studyCentre {
    char stdCode[10], stdName[40], regName[40], coord[20], prgin[20], address[35], email[40], webs[45];
    int ph;
} std;

int flag=0;

void main() {
    FILE *fp;

    fp  = fopen("studyCentre.txt", "r+");
    if (fp==NULL) {
        printf("No file found");
        exit(0);
    }

    while(feof(fp)!=0) {
    //while(!fp.EOF()) {
        fscanf(fp, "%s%s%s%s%s%s%s%s%d", std.stdCode, std.stdName, std.regName, std.coord, std.prgin, std.address, std.email, std.webs, &std.ph);
        printf("\n Study Center Name :: %s \n Regional Centre Name :: %s \n Coordinator Name = %s \n Program incharge Name :: %s Address %s \n Email :: %s \n Website :: %s \n Phone :: %d", std.stdName, std.regName, std.coord, std.prgin, std.address, std.email, std.webs, &std.ph);
        flag=1;
    }
    if (flag==0) {
        printf ("No record found");
    }
    fclose(fp);
}

Output
No record found

This is the text in my text file.
111
a
b
c
d
e
f
g
h
122

Edit: Corrected a typo.

A: Also you need to look at what the function feof is returning :
Return :
A non-zero value is returned in the case that the end-of-file indicator associated with the stream is set.
Otherwise, zero is returned.
You should write
while(feof(fp)==0)


text:
Q: Deploying Multiple Microservices in different repositories to a single VM using bitbucket pipelines and docker-compose I have a total of 8 Nodejs services in 8 different repositories on bitbucket. The services share some common code which is present in another repository called Brain. I want to create bitbucket pipelines in all of these repositories so that I can do the following things:

*

*Build the docker image for each service and store it in Google Container Registry

*Use ssh-run or a similar runner to ssh into my GCE VM and run a docker-compose pull and docker-compose up to deploy the latest versions.

*Perform zero downtime update, i.e, keep the old containers running until the new containers are ready.

What would be the best way of doing this? Currently I'm facing the following problems:

*

*When I push changes to the Brain repository, I need to build images for all the different services. Most of the time I'm pushing both to my brain repository and some other service repository. So multiple images are being built.

*When I push changes to the Brain repository, as I build the different images for the services, all of them try to deploy using ssh-run. I don't know if this is sustainable and may crash my VM?

Any suggestions would be appreciated. Thanks in advance!


text:
Q: Determine if non-numerical characters have been pasted into UITextField For a specialized calculator I would like to allow copy / paste for a textfield which is meant for numerical values only. So, only numerical characters should be actually pasted or the pasted string should be rejected if it contains non-numerical characters.
I was thinking about using UITextFieldDelegates textField:shouldChangeCharactersInRange:replacementString: method to check the pasted string for non-numerical characters. But NSString offers no method for checking whether it does NOT contain characters specified in a single set. So this way I would need to check occurances of characters from several sets, which is clumsy and these checks would run for every single number that would be typed in, which appears like quite some overhead to me.
Another way would be to iterate and check for every character in the replacement string whether there's a match in a numerical set.
Either way would propably work, but I feel like I'm missing something.
Do you have any advice? Is there a convenience method to achieve this?

A:
But NSString offers no method for checking whether it does NOT contain characters specified in a single set

sure it does.
if([myString rangeOfCharacterFromSet:myCharacterSet].location ==NSNotFound)
{
//means there is no character from specified set in specified string
}


text:
Q: Adding a filter to the page based on the textbox value I have the following two tables:
Table1
___________
ID
Name
Company
Industry
Rank
Key - guid

and
Table2
_____________
Key - guid
FieldValue
StartDate
EndDate

I am using MVC pattern, not regular web forms. I created 2 separate model classes for each and separate DBContext classes.
Initially when page loads, I display all the data from Table1 on the page. I want to add a textbox at the top of the page and when a user enters a value and hits enter, I want to data in the table on the page to be filtered based on the user-entered value:
SELECT ID, Name, Company,Industry, Rank
FROM Table1 INNER JOIN Table2 ON Table1.Key=Table2.Key
WHERE FieldValue=TextBox1.Text

I already have the code to display data from Table1 on the page working fine, but I need help adding the filter based on the value of the textbox. Can anyone point me in the right direction?
Here is my code from the view:
<input type="text" id="TextBox1" />

Records

            ID
            Name
            Company
            Industry
            Rank

 @foreach (ProjectName.Models.Records item in Model)
        {

                @item.ID
                @item.Name
                @item.Company
                @item.Industry
                @item.Rank

        }

Here is updated view code:

   @using (Html.BeginForm())
   {
    <input type="text" id="TextBox1" />
    <input type="submit" name="submit" />
   }

Records

        ID
        Name
        Company
        Industry
        Rank

    @foreach (ProjectName.Models.Records item in Model)
    {

            @item.ID
            @item.Name
            @item.Company
            @item.Industry
            @item.Rank

    }

P.S. Dear editors, please please pretty please, stop editing word MVC out of the title - otherwise people assume it is Web Forms pattern and not MVC. SO PLEASE PRETTY PLEASE stop editing it out, you are not helping, only making things difficult. Thank you so much in advance, my appreciation is above and beyond

A: Even though you're using MVC, you still need a <form> to submit the filter value to a controller method.
This is your textbox within an MVC form:
@using (Html.BeginForm())
{
    <input type="text" name="TextBox1" />
    <input type="submit" name="submit" />
}

This is rendered as HTML <form> tags. Your Controller looks like this:
public ActionResult Index(string TextBox1)
{
    // You don't say how you're interacting with the database,
    // but you need to check the `TextBox1` parameter for null,
    // and use it in your query if it's not - simplified:
    if(TextBox1 != null)
    {
        // do qry with parameter
    }
    else
    {
       // do qry without parameter
    }
    ...

There are several ways to do what I've written above, but this is a simple version that doesn't require modifying your ViewModel (mainly because I don't know what it looks like!)

A: You can use datatables plugin, you have filters with static or server tables.
The very basic example:
$(document).ready(function() {
    $('#example').DataTable();
});

A: First, create something that postback, like an <as:button>  and correctly link the event in the code behind, then :
using(context db = new context())
{
    List<Table2> var1 = db.Table2.ToList()
    List<Table2> var2 = new List<Table2>()
    foreach(Table2 t in var1)
    {
        if(t.FieldValue == textbox.Text)
        {
            var2.Add(t);
        }
    }
}

and then :
 foreach(Table2 t in var2)
  {
      //Bind your things here
  }

Sorry if it dosen't help you or if i misunderstood the question.


text:
Q: detect cross domain redirects on ajax request We have our authentication delegated to another domain (Window Identify framework, federated authentication setup). Now, if the the session timed out before an ajax request , server redirects the request to authentication server. Since it becomes a cross domain call, ajax request is cancelled by the browser. Is there a way i can detect this in jquery/javascript ?
I inspected the status property of the xhr object which set to 0 in such case, but is it a good indicator for cancelled requests? (I am using jquery $.ajax to make ajax requests)

A: I have been looking into this, too, and have found very little evidence that what you want to detect is perfectly detectable.  However, I have found a way to detect that it probably happened.
Here is what transpires with your event:

*

*The JavaScript code initiates the request.

*The browser makes the request to the server.

*The server answers with a redirect.

*The browser determines that the new location is a different domain.

*The browser cancels the request (to keep you safe).

*The browser reports (not entirely truthfully) that the request was never sent.

In your error callback, check your XMLHttpRequest object's readyState field.  If it is 0 ("UNSENT"), then it means that your AJAX request was never sent.
Of course, it may not always be entirely clear why it was not sent.  For example, it's possible that the user simply unplugged his network cable.  However, if you are willing to assume that the network is functioning perfectly, then it may be reasonable to also assume, when you see readyState == 0, that the request was not sent because of cross-domain concerns.  That means the redirect happened.
If you are working with jQuery, then you can check jqXHR.readyState instead.

A: You can check this page: http://api.jquery.com/jQuery.ajax/
There is an error parameter where you can catch if the request fails.
error(jqXHR, textStatus, errorThrown)
Hope this will help.


text:
Q: Curiosity Rover (MSL): specification / dimensions I have been looking all over and I can't find a detailed specification about the Curiosity Rover.
The length is about 10 feet but it would be cool to find out the dimensions of the wheels, clearance and so on.
Anybody know where I would find this information?

A: The actual mission is called the Mars Science Laboratory.

*

*The NASA Mission page as some basic information and images, including this fact sheet.

*The mission is run out of JPL and they have a mission page as well.  This one actually has more information on the technology involved.

*There is also a general Wikipedia article on the Mars Science Laboratory but I think you'll find more information on the JPL site.

A: The wheels are 50 cm in diameter.
Here is a picture of Curiosity next to some people, for scale.

A: Unfortunately, it might be slightly difficult to find precise specifications and dimensions. This isn't necessarily because they are trying to be secretive; it's just not something the public in general would need or benefit from.
That being said, you can certainly find some more information regarding dimensions. As Andrew already said, the wheels are half a meter (50 cm) in diameter. This blog post states that the clearance from the ground is 60 cm, but it doesn't given any references, so that information may not be completely accurate.
If you are truly interested in specific dimensions, then I suppose one thing that you could do (if you can't find them online) is find a scale model of it, and try to figure out the dimensions (such as this one from AAAS).
More interesting, in my opinion, are the numerous papers and discussions on the engineering challenges and electronic and software systems that went into making the rover. The JPL robotics website has a few freely available papers, but more are available from other sources if you look.

A: Though demensions are not covered, a detailed and complete account of the scientific instrumentation, especially the cameras, aboard MSL can be found on JPL's "Science Corner" site.

The JPL mission page has links that cover most of the physical specs, though not in the same detail as the instrumentation. Here you can, for example, confirm that the wheels are indeed about 50 cm in diameter:

A: According to CNES, the rover's dimensions are 2.9 x 2.7 x 2.2 m. That link has a few more details on the payload weights, but not much more than that.


text:
Q: Twilio - status call back - recording url I use statuscallbackurl to get the call details and post to another system. documentation says we can get the recording url from RecordingUrl the posted parameters.
But I do not get this url. My response xml is below. Let me know how to get the recording url.
Thanks.
<?xml version="1.0" encoding="UTF-8"?>
<Response>
<Dial action="url" callerId="+19999999999" timeout="15" sequential="true" record="true">
    <Number>+19999999999</Number>
</Dial>
</Response>

A: Twilio evangelist here.
I believe that the recording URL will only be sent to the URL you've specified in the action parameter.
From the docs:
"...a RecordingUrl parameter will be sent to the 'action' URL on the associated  verb. You must set an 'action' URL to receive the RecordingUrl."
I see that you've specified the action parameter.  Are you saying that the RecordingUrl parameter is not included in the request to that URL?
Hope that helps.


text:
Q: How do I change an iframe's source from a button click inside another iframe?

                  <div class="tab-pane"

I have 2 iframes inside a parent page (all same domain). They display 2 different pages as tabs . When I click a button inside frame1, I want to set the src of frame2 to src="page3".  If the user go the the parent page, the
src of frame2 is defaulted to page2. It's only that a specific button is clicked inside frame1 that I need to change the source

Thank you!

A: To access the parent DOM, you use parent.document.
So to change the src of frame2 from frame1, you do:
document.getElementById("buttonid").addEventListener("click", function() {
    parent.document.getElementById("frame2").src = "page3";
});


text:
Q: parse multipe types of logs for Fortimail with LogStash I would like to know if it's possible to parse several types of logs for the same logs source.
For example, I have two different logs for two different types :

*

*type = statistics :
date=2012-07-16 time=12:22:56 device_id=FE100C3909600504 log_id=0200001075 type=statistics
pri=information session_id="q6GJMuPu003642-q6GJMuPv003642" client_name="[172.20.140.94]"
dst_ip="172.20.140.92" from="user@external.lab" to="user5@external.lab" subject="" mailer="mta"
resolved="OK" direction="in" virus="" disposition="Reject" classifier="Recipient Verification"
message_length="188"

*type = spam
date=2012-07-16 time=12:22:56 device_id=FE100C3909600504 log_id=0300001075 type=spam
pri=information session_id="q6GJMuPu003642-q6GJMuPv003642" client_name="[172.20.140.94]"
dst_ip="172.20.140.92" from="user@external.lab" to="user5@external.lab" subject="" msg="
... User unknown"
In the filter (logstash), how can I do multiple regex for each type for logs in Fortimail ?

A: Try this filter
filter {
    ruby {
            code => "
                    event['type'] = event['message'].split('type=')[1].split(' ')[0]
            "
    }
    if [type] == "statistics" {
         grok {
              //  parsing statistics logs
         }
    }

    if [type] == "spam" {
         grok {
              //  parsing spam logs
         }
    }
}

First, Get the type of the logs, then use condition if to parse different type of logs.
Hope this can help you. :)