text:
Q: Pyparsing indents and de-indents I am parsing a configuration file of router. Usually I am using regex with named groups and for this purpose:
https://regex101.com/r/EcyPeh/5
In this example I use 'svcindent' named group + keyword "exit" as de-indent of service configuration context.
How to make the same thing with pyparsing?
There is SkipTo(intend + Keyword("exit") in following source code. I am trying to use it as de-indent. But it match various number of white spaces. That is why it match the "exit" keyword of stp context.
from pyparsing import *

data = """
        vpls 82 customer 700 i-vpls create
            service-mtu 9040
            send-flush-on-failure
            propagate-mac-flush
            stp
                shutdown
            exit
            sap 2/2/8:0.1 create
                ingress
                    qos 13
                    queue-override
                        queue 1 create
                            cbs 1000
                            rate 10240 cir 10240
                        exit
                    exit
                exit
            exit
            spoke-sdp 4:82 endpoint "vpls-82-uplink" create
                stp
                    shutdown
                exit
                precedence primary
                no shutdown
            exit
            spoke-sdp 6:82 endpoint "vpls-82-uplink" create
                stp
                    shutdown
                exit
                no shutdown
            exit
            mac-move
                no shutdown
            exit
            no shutdown
        exit
        vpls 121 customer 700 i-vpls create
            service-mtu 9040
            send-flush-on-failure
            propagate-mac-flush
            stp
                shutdown
            exit
            sap 2/2/9:900 create
                ingress
                    qos 13
                    queue-override
                        queue 1 create
                            cbs 3000
                            rate 10240 cir 10240
                        exit
                    exit
                exit
            exit
            spoke-sdp 4:121 endpoint "vpls-121-uplink" create
                stp
                    shutdown
                exit
                precedence primary
                no shutdown
            exit
            spoke-sdp 6:121 endpoint "vpls-121-uplink" create
                stp
                    shutdown
                exit
                no shutdown
            exit
            mac-move
                no shutdown
            exit
            no shutdown
        exit
        vpls 1986692 customer 555 i-vpls create
            service-mtu 9040
            send-flush-on-failure
            propagate-mac-flush
            stp
                shutdown
            exit
            sap 2/2/9:130 create
                ingress
                    qos 13
                    queue-override
                        queue 1 create
                            cbs 1000
                            rate 10240 cir 10240
                        exit
                    exit
                exit
            exit
            spoke-sdp 4:1986692 endpoint "vpls-1986692-uplink" create
                stp
                    shutdown
                exit
                precedence primary
                no shutdown
            exit
            spoke-sdp 6:1986692 endpoint "vpls-1986692-uplink" create
                stp
                    shutdown
                exit
                no shutdown
            exit
            mac-move
                no shutdown
            exit
            no shutdown
        exit
"""
indent = LineStart() + OneOrMore(White(' ', exact=4))
deident = matchPreviousExpr(indent) + Keyword("exit")
svc_id = Word(nums)
customer_id = Word(nums)
sp = White(' ', exact=1)
svc_stmt = Combine(indent("int_s") + Keyword("vpls") + sp + svc_id + sp + Keyword("customer") + sp + customer_id + SkipTo(Keyword("create"), include=True)) + Combine(SkipTo(deident, include=True))

svc_stmt.leaveWhitespace()
parseTree = svc_stmt.searchString(data)
parseTree.pprint()

Result:
[['        vpls 82 customer 700 i-vpls create',
'\n'
'            service-mtu 9040\n'
'            send-flush-on-failure\n'
'            propagate-mac-flush\n'
'            stp\n'
'                shutdown\n'
'            exit'],
['        vpls 121 customer 700 i-vpls create',
'\n'
'            service-mtu 9040\n'
'            send-flush-on-failure\n'
'            propagate-mac-flush\n'
'            stp\n'
'                shutdown\n'
'            exit'],
['        vpls 1986692 customer 555 i-vpls create',
'\n'
'            service-mtu 9040\n'
'            send-flush-on-failure\n'
'            propagate-mac-flush\n'
'            stp\n'
'                shutdown\n'
'            exit']]


text:
Q: Trouble with antiforgery token using owin I'm setting OWIN authentication with my app but I have one problem. I set the validate and anti-forgery token on my login page and when I make a POST all works fine, but on another page setting the validate and anti-forgery token when I make a POST causes the following error to appear:

Anti-forgery token provider was designed for user "user@domain.com" but the current user is "" ...

So how I can fix this without using AntiForgeryConfig.SuppressIdentityHeuristicCheck in Global.asax?
Why doesn't the anti-forgery token take the current user?
UPDATE
The Task<ClaimsIdentity> implements like this:
public override Task<ClaimsIdentity> CreateIdentityAsync(AppUser user, string authenticationType)
    {
        return Task<ClaimsIdentity>.Factory.StartNew(() =>
        {
            var claimsList = new List<Claim>()
            {
                new Claim(ClaimTypes.Name, user.Email),
            };

            return new ClaimsIdentity(authenticationType);
        });
    }

And the Task SignInAsync like this:
public override async Task SignInAsync(AppUser user, bool isPersistent, bool rememberBrowser)
    {
        AuthenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie);
        var identity = await UserManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie);
        identity.AddClaim(new Claim(ClaimTypes.Name, user.Email));
        AuthenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = isPersistent }, identity);
    }

The user.Email is user@domain.com

A: If the user is logged on then anti forgery token will be issued for that user. Let me give you an example:

*

*Say you have two pages with anti forgery token that submit with form data: Login Page and Search Page

*Open search page and perform a search, it will be fine.

*Now open login page on another tab (in browser) and login successfully.

*Now go back to search page that is already open in the previous tab. Try to perform a search and boooom, you will get anti forgery token error.

*Now re-fresh the search page and do another search, it will be fine.
It is because initially the token on search page didn't have user info but the server expects it because the user is logged on. On re-fresh of the search page token gets updated with logged on user info, so it throws no error.

redpajama_set_name: RedPajamaStackExchange


text:
Q: BeautifulSoup4, get info from data-stat element I'm a high school student organizing an event for some friends. For the event, I need to scrape data of players for a video game called Rainbow 6 Siege.
I need to extract a number from a thing called data-stat in the HTML code. For example, below I'm trying to extract the 1.03 from "RankedKDRatio". How can I cleanly do this? Thanks for taking a look!
<div class="trn-defstat__value" data-stat="RankedKDRatio">
            1.03

My current code:
from urllib.request import Request, urlopen
from bs4 import BeautifulSoup as soup

url = "https://r6.tracker.network/profile/pc/Juke.TMT"

req = Request(url, headers={'User-Agent': 'Mozilla/5.0'})
webpage = urlopen(req).read()

soup = soup(webpage, "html.parser")

print(soup.prettify())


text:
Q: Integrating a linear-map valued function My textbook for an Analysis course I am taking presents the Mean Value Equality theorem as
Suppose $\mathbb{X}, \mathbb{Y}$ are Banach Spaces.
Let $U\subseteq \mathbb{X}$ be an open set, and let $f\colon U\to \mathbb{Y}$ be Fréchet differentiable everywhere on $U$. Let $x,v\in\mathbb{X}$ be such that the line segment from $x$ to $x+v$ lies completely in $U$, then
$$f(x+v)-f(x)=\left[\int_0^1 df(x+tv)\,dt \right](v).$$
My question is: How do I interpret this integral? Integrating over a series of functions and then evaluating afterwards confuses me, as this doesn't fit in with what I've learnt about integration (I'm only used to integrating over $\mathbb{R}$-valued functions).
note: i should say $df(x+tv)\colon\mathbb{X}\to\mathbb{Y}$ is the Fréchet derivative at $x+tv$.

A: It is standard to assume that $df(x)$ is a bounded linear operator on $X$. You should probably also assume that $x\mapsto df(x)$ is continuous as a function from $X$ into $\mathcal{L}(X)$, the space of bounded linear operators on $X$. The chain rule applies to the function $t \mapsto f(x+tv)$ to give a derivative
$$
            \frac{d}{dt} f(x+tv) = df(x+tv)\frac{d}{dt}(x+tv)=df(x+tv)v.
$$
Therefore
\begin{align}
              f(x+v)-f(x) & =\int_{0}^{1}\frac{d}{dt}f(x+tv)dt \\
                & = \int_{0}^{1}df(x+tv)v\;dt \\
                & = \left[\int_{0}^{1}df(x+tv)dt\right]v
\end{align}
The first two integrals on the right can be viewed as Riemann integrals on $[0,1]$ of continuous functions which take values in $X$. The last integral can be viewed as a Riemann integral of a continuous function from $[0,1]$ into the vector space of bounded linear operators $\mathcal{L}(X)$; the result is another bounded linear operator, which is then applied to the vector $v$. The last identity is easily proved using Riemann sums, assuming that $t\mapsto df(x+tv)$ is continuous from $[0,1]$ into $\mathcal{L}(X)$. Keep in mind that $\mathcal{L}(X)$ is just another Banach space.


text:
Q: Troubleshooting "VC: Tinymce error! Compatibility with other plugins" for custom post_type While using Visual Composer on a custom post_type you get the following error when editing a text field with a Tiny MCE wysiwyg:
visual composer "VC: Tinymce error! Compatibility problem with other plugins."

A: You need to enable the 'editor' for your custom post_type for WordPress to load the Tiny MCE client-side script files.
register_post_type( 'my_post_type', array(
[...]
'supports'           => array( 'editor')
);


text:
Q: Turning a WP Site Into an iPhone/iPad App With the advent of responsive design, it's beginning to simply make sense that we could make a site into an app.  The concept is simple:

*

*When the user is on the site, remove the browser around the site so that it appears to be like any other app

*Provide the appropriately-sized icons for devices (tablets, smartphones, etc.)

*Meet all criteria necessary to distribute the app via the Apple app store

I'm curious if anybody has the hacks, tutorial, or information necessary to achieve this.

A: The best way to do this would be to use CSS3 media quires: @media (max-device-width: 480px) but requires more work.
The quick and dirty way to make your WordPress theme app-like would be to add the viewport meta tag to the <head> of your page:
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
Viewport scales you page to fit the users device.
To hide the address bar in iOS and Android Just add this line of JavaScript to your page:
// When ready...
window.addEventListener("load",function() {
  // Set a timeout...
  setTimeout(function(){
    // Hide the address bar!
    window.scrollTo(0, 1);
  }, 0);
});
You can also add this meta tag witch tells iOS your site is a web app and to hide the address bar:
<meta name="apple-mobile-web-app-capable" content="yes" />

A: *

*How much of the browser you can hide depends on the browser you're using.  This might help out:

*

*HTML5 Full Screen Web Apps: No browser bars

*Full Screen Web Apps

*You can't simply submit a website to the App Store, but you do have options.

*

*Suggest (perhaps via a well-placed overlay on your mobile site) that the user adds your website to their home screen by tapping the share button (in Safari), then "Add to Home Screen."  Your website is more like an app there: no browser interface and an icon of your choice on the home screen.

*

*This should prove helpful: Safari Web Content Guide: Configuring Web Applications

*Look into a framework like PhoneGap

Hope that helps!


text:
Q: XACML2: XACML2.0 implementation in java I'm writing my master-these and i have some problemes with the PDP evaluation of request. I use sunxacml:2.0 in java. when i define a request and evalue it with PDP the response is NotApplicable but when i define a request and encoding in file and i define another request through the encoding's file, the response of the evaluation for this request is permit or deny.
Question: with sunxacml:2.0, the request should always encoding ? or how can i do it?
Resquest request= new Request(Set subjects, Set Resource, Set action, Set environment); request.encoding(FileOutputStream file); pdp.evalue(request)-> response: Notapplicable RequestCtx req=RequestCtx.getInstance(new FileInputStream(file))   pdp.evalue(req)-> response: permit or deniy


text:
Q: request.subdomain not returning anything I am a new Rails Developer
My application_controller is:
class ApplicationController < ActionController::Base
  protect_from_forgery

  before_filter :sshow

  def sshow
    puts "==========================="
    puts YAML::dump(request.subdomains)
  end
end

now when I put kausik.localhost:3000 in my browser address bar it
returns blank Array [] instead ['kausik'] .
Also I rewrite etc/host file for this subdomain.

A: As @injekt said in the comments, you can't work with subdomains using localhost. The simplest alternative is to use the lvh.me domain which points all subdomains to 127.0.0.1. To do this, simply start your rails server and go to kausik.lvh.me:3000.
Also, if you simply need the first subdomain, you can use request.subdomain, which in this case would return "kausik".
There's a very nice RailsCast about subdomains in Rails.


text:
Q: bash: reading list of values from variable in file STATUS QUO
i have an external properties file, where a couple of variables are stored. one of these has a list of values (min 1 value, max X values).
when declaring this single list within the shell script, it would look like this:
NODES=(
    "node"
    "node-2"
    "node-3"
)

I read the values from the properties file like this:
# checks, if file exists and is readable
file="./properties.credo"
if [ ! -r "$file" ]
then
    echo "fatal: properties file $file not found / readable."
    exit 2
fi

# loads properties into variables
. $file
[[ -z "$VALUEA" ]] && echo "fatal: VALUEA not specified in .credo" && exit 2
...

PROBLEM
When defining the NODES values in the properties like this:
NODES=node,node-2,node-3

... and reading with that:
...
[[ -z "$NODES" ]] && echo "fatal: NODES not specified in .credo" && exit 2
...

... it will be read from the file as a single string node,node-2,node-3, but not as a list or one-dimensional array.

A: Beware! This is dangerous as the config file can contain PATH=/some/path and the script can then execute commands over which you have no control.
You can use read -a to populate an array. Set IFS to the separator and send the values read from the file to read's standard input.
#! /bin/bash
file=$1

IFS== read var values < "$file"
IFS=, read -a $var <<< "$values"

echo "${NODES[@]}"

For a multiline config, I tried the following:
nodes=node1,node2,node3
servers=server1,server2

and modified the script to loop over the input:
#! /bin/bash
file=$1

while IFS== read var values ; do
    IFS=, read -a $var <<< "$values"
done < "$file"
echo "${nodes[@]}"
echo "${servers[@]}"

You might need to skip over lines that don't follow the var=val1,val2,... pattern.


text:
Q: Twig zebra-stripping without loop I have a table whose rows are generated dynamically depending on users' input (it is a summary of charges that may or may not take a promo code--if the user have one--and a gift message--if the user sends one). There is no way to generate the items of the summary of charges on a loop since the items come from different places in my application. I only have conditionals for the items to appear or not on the users' order depending on what the order is like. The table needs to have zebra-stripping. Because the number of items may vary, I cannot hardcode the color inline (it is an e-mail). I tried twig's divisibleby and modulo on the rows, so the colors would alternate for even and odd rows. Although the color changes it does not change to the color I want and it is not doing the zebra stripping (all rows change to blue. I need colors to alternate between light beige (#fcf9f5) and white (#ffffff)). What am I missing?
Here is the code for one tr:
{% set index = 0 %}

            Order Subtotal:

            {{ order.itemsTotal|sylius_price }}

{% index++ %}

A: Sorry but Twig can't correct the fact that your code is dirty.
Let's say you have 3 diferents sources. If you display them all in an array they have all comon attributes right?
you just have to combine all the source objects in a simple displayable object (a DTO).
Twig can't contain business logic, it just display stuff.
If you want to keep your logic in your view, try to use twig merge fuction to combien your arrays and display them in a loop


text:
Q: Passing dynamic data to Jquery Highcharts I am using jquery Highcharts plugin to show charts on web page and facing difficulties to pass dynamic data to chart series data. Code is

How to pass review_sites to series: [{
      type: 'pie',
      name: 'Sites',
      data:
    }],
I want to pass review_sites value to above one code. For now I leave data:


text:
Q: Passing a URL as a parameter to Node/Express app I have a simple Node/Express route, as follows:
var app = express();

app.get('gettags/:page', function(request,response)
{
    var thePage = request.params.page;
    ...
    ...
}

The problem I'm having is that if I pass a URL as the parameter, I get a "Cannot GET" error. So, if I call this like:
http://www.mynodeapp.com/gettags/http://www.someurl.com/?withquery=something

I get the "Cannot GET" error. It's been a couple years since I've used Node, so I am probably forgetting something very basic. But I can't get past this, and Googling this issue hasn't turned up anything useful.
Thanks for any help!

A: Your node code looks fine but for this to work you'll need to URI encode your argument:
var url = 'http://www.mynodeapp.com/gettags/' + encodeURIComponent('http://www.someurl.com/?withquery=something')

//becomes: http://www.mynodeapp.com/gettags/http%3A%2F%2Fwww.someurl.com%2F%3Fwithquery%3Dsomething

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent

A: The Problem in your code is

/ 's of http://www.someurl.com

so to overcome this use url encoding functions in node such as
encodeURIComponent("Your url goes here")


text:
Q: Help identifying diode so I have this diode that is under a transformer on a battery charger. I was looking for faults on it with a thermal camera and noticed the one next to it was glowing at over 120C . I removed the hot one and it is pretty much shorted as shows 0.03 in both directions with the diode test. Iv also got a peak tester dca 75 and it won't even identify it as a component.
The one next to it is marked with V21 and is just a regular looking brown / orange looking colour and is glass.
I would go on what the dca 75 says, but each time it tests the working one, the vf goes up.
It's been so hot that it's burnt 99% of the markings off it, but it looks to be paired with the one next to it.
The problem is I can't seem to find a replacement for it. "V21 Zener diode" just brings up an smd diode sot 23 package and not a through hole glass diode like this.

A: SMD devices typically are marked with random letters/numbers, but through-hole devices usually try to use markings that resemble the actual name.
"V21" sounds like the BAV21, which is a general-purpose diode made by many manufacturers.

A: Looks like a standard IN4148 diode. Google for it and see pictures.
If it is hot it means a lot of current is going thru. Check your
schematics.


text:
Q: How to change the language of Windows 8 apps
Possible Duplicate:
How to set start screen tiles' language in Windows 8

Just upgraded to Windows 8 (from Windows 7) and I noticed that some apps from store are displayed in my native language (which is Romanian).
The thing is that the only settings that are related to Romania are the keyboard and the timezone. The UI is in English, the Locale is set to United States.
There is a way of preventing this and make all apps to be displayed in English?

A: Did you choose multi language while installing Windows 8 and not just English?
Try checking with Control Panel » Clock, Language, Region » Language. Try and set English as default or deleting the other languages.


text:
Q: Replace IBOutlet view in code I'm using storyboards and a tableview. Each cell in my tableview has a UIView in it. Is it possible to replace the IBOutlet of this UIView programmatically? For example doing something like this:
class CustomTableViewCell: UITableViewCell {
    @IBOutlet weak var videoPlayerView: UIView! /// Really this is a VIMVideoPLayerView (from library below) which inherits from UIView.

    func configureCell(with customObject: CustomObject) {

        // Set the IBOutlet in code here.
        self.videoPlayerView = customObject.videoPlayerView
    }
}

If I try to do this nothing happens.
I know many people will ask: "Why do you want to do this?". Here it goes: I am using this library VIMVideoPlayer and I create the actual player which contains a UIView in code. Instead of reusing the players I create them all at once in code and now want to display them. It really comes down to performance reasons regrading scrolling and lagging on main thread.
NOTE: I have this working in code already but really want to use storyboards. The way I have it working in code is by doing this:
videoHolderView.addSubview(customObject.videoPlayerView)
Any thoughts?

A: Modifying the variable is fine, but that won't change the view hierarchy.
You will need to insert the new view into the original views superview, then remove the old view.
Keep in mind this will not retain any layout constraints, you will need to re-create them after adding the replacement view.
class CustomTableViewCell: UITableViewCell {
    @IBOutlet weak var videoPlayerView: UIView! /// Really this is a VIMVideoPLayerView (from library below) which inherits from UIView.

    func configureCell(with customObject: CustomObject) {
        // Replace the view by inserting a new view into the same location
        // in the view hierarchy
        let newVideoPlayerView = customObject.videoPlayerView
        videoPlayerView.superview.insertSubview(newVideoPlayerView, belowSubview: videoPlayerView)
        videoPlayerView.removeFromSuperview()

        // Set the IBOutlet in code here.
        videoPlayerView = newVideoPlayerView

        // TODO: Recreate your layout constraints
    }
}

A: You can do this, but all your current code is doing is updating the property.  You need to remove the existing view from the view hierarchy and add the new view as a sub-view.
func configureCell(with customObject: CustomObject) {

    // Set the IBOutlet in code here.

    self.videoPlayerView.removeFromSuperview()

    self.videoPlayerView = customObject.videoPlayerView

    self.addSubView(self.videoPlayerView)

}

Note that you may also have to add any constraints that are required for the new view


text:
Q: Calling the Button from other form Good day to all. i am facing another problem. i have 2 forms, 1 form is the main form where the listview(show my data from database), refresh button(refreshing listview) and add new item button ( where to add new item).
when i pressed add new item, another form showing.
so my problem is how can i refresh my listview when im done adding new item using the btn_Refresh_Click(object sender, EventArgs e) or how can i access the btn_Refresh_Click
private void btn_Refresh_Click(object sender, EventArgs e)
    {
        ShowItems("B.S. in Information Technology", 1, 18);
        ShowItems("B.S. in Entrepreneurial Management", 19, 36);
        ShowItems("B.S. in Industrial Engineering", 37, 54);
        ShowItems("B.S. in Electronics Engineering", 55, 72);
        ShowItems("Technical-Vocational Courses", 73, 90);
    }

ShowItems is a method for sql select statement to show the items to listview.
thank you in advance.

A: Create a public member function for refreshing:
public void Refresh()
{
    ShowItems("B.S. in Information Technology", 1, 18);
    ShowItems("B.S. in Entrepreneurial Management", 19, 36);
    ShowItems("B.S. in Industrial Engineering", 37, 54);
    ShowItems("B.S. in Electronics Engineering", 55, 72);
    ShowItems("Technical-Vocational Courses", 73, 90);
}

And call it from your button handler:
private void btn_Refresh_Click(object sender, EventArgs e)
{
    Refresh();
}

And now you can also call it from anywhere else!

A: You can either do something like this:
MyAddForm fmAdd = new MyAddForm();
fmAdd.ShowDialog();
btn_Refresh_Click(null,null);

OR

MyAddForm fmAdd = new MyAddForm();
fmAdd.ShowDialog();
RefreshData()

Take your logic out of the refresh button click and add it to a new method called RefreshData and make sure the button click calls RefreshData

A: If you dont want to create a new method change the access of btn_Refresh_Click event to public and call that using
btn_Refresh_Click(null,null);

and when you call this from other form use the object of form2 and call this event
Let f2 is the object of Form2
f2.btn_Refresh_Click(null,null);

If you want to be more good programmer try to use delegates


text:
Q: How to use workspace in IntelliJ IDEA I am familiar with eclipse. with eclipse I am able to create workspace and I used to work on that. similar to this is there any way to create workspace in intellij?. By default when importing the project the intellij is pointing actual path of the project not asking for workspace to work.

A: Please refer to the documentation:

No workspace
The first thing you'll notice when launching IntelliJ IDEA is that it
  has no workspace concept. This means that you can work with only one
  project at a time. While in Eclipse you normally have a set of
  projects that may depend on each other, in IntelliJ IDEA you have a
  single project that consists of a set of modules.
If you have several unrelated projects, you can open them in separate
  windows.
If you still want to have several unrelated projects opened in one
  window, as a workaround you can configure them all in IntelliJ IDEA as
  modules.


text:
Q: Multiple echoes of an include error with set_error_handler Why is an include error echoed four times?
Does the system attempts 4 times to "open stream"?
I did :
function errorHandler($errno, $errstr, $errfile, $errline) {
    if ($errno == E_NOTICE ) {
        echo "
".$errno."== E_NOTICE
";
    }
    if ($errno == E_USER_NOTICE) {
        echo "
".$errno."== E_USER_NOTICE
";
    }
    if ($errno == E_DEPRECATED) {
        echo "
".$errno."== E_DEPRECATED
";
    }
    if ($errno == E_USER_DEPRECATED) {
        echo "
".$errno."== E_USER_DEPRECATED
";
    }
    if ($errno == E_STRICT) {
        echo "
".$errno."== E_STRICT
";
    }
    if ($errno == E_WARNING) {
        echo "
".$errno."== E_WARNING
";
    }
    if ($errno == E_USER_WARNING) {
        echo "
".$errno."== E_USER_WARNING
";
    }
    if ($errno == E_ERROR) {
        echo "
".$errno."== E_ERROR
";
    }
    if ($errno == E_USER_ERROR) {
        echo "
".$errno."== E_USER_ERROR
";
    }
}
set_error_handler("errorHandler");

Result :
2== E_WARNING

2== E_WARNING

2== E_WARNING

2== E_WARNING

A: Without seeing additional information pertaining to your error its hard to say.

Files are included based on the file path given or, if none is given,
  the include_path specified. If the file isn't found in the
  include_path, include will finally check in the calling script's own
  directory and the current working directory before failing. The
  include construct will emit a warning if it cannot find a file; this
  is different behavior from require, which will emit a fatal error.

Docmumentation for include().

PHP considers each entry in the include path separately when looking for files to include. It will check the first path, and if it
  doesn't find it, check the next path, until it either locates the
  included file or returns with a warning or an error. You may modify or
  set your include path at runtime using set_include_path().

Per the PHP docs on the include process.
On a side note, I've made a few modifications to your provided custom errorHandler() function.
<?php
function errorHandler($errno, $errstr, $errfile, $errline) {
    $response;

    switch ($errno){
        case E_NOTICE:
            $reponse = 'E_NOTICE';
            break;

        case E_USER_NOTICE:
            $reponse = 'E_USER_NOTICE';
            break;

        case E_DEPRECATED:
            $reponse = 'E_DEPRECATED';
            break;

        case E_USER_DEPRECATED:
            $reponse = 'E_USER_DEPRECATED';
            break;

        case E_STRICT:
            $reponse = 'E_STRICT';
            break;

        case E_WARNING:
            $reponse = 'E_WARNING';
            break;

        case E_USER_WARNING:
            $reponse = 'E_USER_WARNING';
            break;

        case E_ERROR:
            $reponse = 'E_ERROR';
            break;

        case E_USER_ERROR:
            $reponse = 'E_USER_ERROR';
            break;
    }
    echo "
Errno: [$errno]; Type: [$reponse]
";
    echo "
Error on line [$errline] in file [$errfile]
";
    echo "
Error: ". $errstr . "
";
}

set_error_handler("errorHandler");

?>


text:
Q: How to Use jQuery UI Autocomplete w/ Chrome Speech Input I've just recently started utilizing a nifty feature in Chrome that allows you to turn any input field into a speech input a user can dictate into. More info here.
Adding this feature itself is dead-simple in Chrome:
<input type="text" x-webkit-speech="x-webkit-speech" /> <!-- you're all set -->

I want to implement this feature in my website's main search box, which heavily utilizes jQuery UI's autocomplete widget... However I can't get the autocomplete widget to fire after the dictated text is inserted into the input field.
I've already tried variations of the following:
<input id="search-input-box" type="search" x-webkit-speech="x-webkit-speech" onwebkitspeechchange="$('.search-input-box').trigger('autocompleteopen')">

How can I trigger the autocomplete "open" event after the speech input change event has occurred?
UPDATE: Solved - jsFiddle of solution here

A: Just bind it to the webkitspeechchange event, eg:
$('#tags').on('webkitspeechchange', function() {
    $('#tags').trigger('autocompleteopen');
});

jsFiddle


text:
Q: Form validation to ng-click directive I am unable to find the solution with the existing answers,so I am creating new post.
I want to add a validation to button click .
I have the scenario like this,
I have the form with two input fields and one image uploading one,here we have the default image and users also have the chance to upload new one.
if the user not uploaded the image we have to show an error message after click on submit.

          <button type="button" class="btn btn-primary-outline btn-xs pull-right dash-post-button" aria-label="Post" ng-click="changeImage()">

            change image
          </button>
          please choose the image

for image upload:
  $scope.iSupportImageUrl = "images/iceland.jpg";

      var setiSupportImageUrl = function (iSupportImgId) {
          $scope.iSupportImageUrl = AWSBucketNameConverter.getAWSURL('TELEKHA_ISUPPORT_IMG', iSupportImgId);

      };

      $scope.changeiSupportImage = function() {
        var iSupportImgUpldmodalInstance = $modal.open({
            controller: 'EventimageuploadCtrl',
            templateUrl: 'views/isupportimageupload.html',
            animation: true
        });

        iSupportImgUpldmodalInstance.result.then(
            function (result) {
            setiSupportImageUrl(result.fileId);
            result.status='a';
            result.createdTS='2014-05-04';
            result.containerName='TELEKHA_ISUPPORT_IMG';
            result.createdById=23;
            result.createdName='abc';
            $scope.newiSupport.bannerImage=result
            },
            function () {

            }
        );
      };

A: You can write your function like this:
$scope.changeImage = function(imageModel){
    if(imageModel){
        // upload the image
    }
    else {
        // Show up the error message
    }
  }

A: Best solution would be to add an hidden input field on your img. So you could use required on it. Something along those lines

    <md-icon ng-if="display_icon_picture">add_a_photo</md-icon>

<md-input-container class="form-error" id="Photo" style="font-weight:bold;">
    <input style="display: none;" type="text" ng-model="profile_picture_url" name="Photo" required aria-label="input">

Requis

</md-input-container>


text:
Q: Flash and Sessions First of all, I'm using KohanaPHP Framework.
I've impletemented SWFUpload successfully, working quite nice. I'm having only one issue.
The main problem is I need to allow users to upload attachments before submitting form. So I decided to use Session var to store attachments array. Unfortunately, it is working inly if I use HTML upload (based on iframe), but not when I use SWFUpload.
I tried to Google for that, but without any working solution. Any ideas?
Update & Solution
Basically, I didn't know there's an issue with Flash and sessions. Providing the same session id didn't helped me because I got unlogged. Anyway I got a solution for people with the same issue.
I created an unique ID of an item. I upload files to temporary directory, then... I'm scanning this directory and I'm adding uploaded filenames to session.
Tom

A: What you need to is pass the session id to SWFUpload by hand. In a nutshell, you do this in your template:
<script type="text/javascript">
var PHPSESSID = <?php echo json_encode(session_id()); ?>;
</script>

Then you do this with your SWFUpload code:
var settings = {
   post_params: {"PHPSESSID" : PHPSESSID},
   /* the rest of the settings */
};

And finally, in your application code, before you call session_start, you need to do this (usually just in your index.php or whatever bootstrap you use):
// Restore session that came from SWFUpload
if(isset($_REQUEST['PHPSESSID']))
    session_id($_REQUEST['PHPSESSID']);

After this session_start() will use the correct session even for SWFUpload requests.


text:
Q: Only one of the recipients receives email, why? What am I doing wrong here? Only one e-mail address receives email and not the other one. So my@email.com receives it and yours@email.com does not receive it.
#!/usr/bin/python3

import smtplib, ssl
import email.message
import email.utils
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email.mime.text import MIMEText
from email.utils import formatdate
from email import encoders
def sendfile(subject, body_text, f_name):

    """
    Sends e-mail with attachment.
    """

    msg = MIMEMultipart()
    msg['From'] = 'him@email.com'
    msg['To'] = 'my@email.com,yours@email.com'
    msg['Date'] = formatdate(localtime=True)
    msg['Subject'] = subject
    msg.attach(MIMEText(body_text))

    part = MIMEBase('application', "octet-stream")
    part.set_payload(open(f_name, "rb").read())
    encoders.encode_base64(part)
    part.add_header('Content-Disposition', 'attachment; filename={}'.format(f_name))
    msg.attach(part)

    smtp_obj = smtplib.SMTP("localhost")
    smtp_obj.sendmail(msg['From'], [msg['To']], msg.as_string())
    smtp_obj.quit()

A: If you're sending to multiple addresses, msg['To'] should be a list of each address:
msg['To'] = ['my@email.com', 'yours@email.com']

And when you call sendmail(), since msg['To'] is already a list, don't enclose it in square brackets.

A: I was able to send e-mail using the following code.
recipients = ['my@email.com','yours@email.com'
msg['To'] = ", ".join(recipients)

smtp_obj.sendmail(msg['From'], recipients, msg.as_string())


text:
Q: How to add array data to the firestore I have a firestore document where 'comments' is a array i need to add data of string to the existing array
FirebaseFirestore.instance
                  .collection('products')
                  .doc('${widget.product.id}')
                  .update({"comments": FieldValue.arrayUnion(_currentName});

A: Here is how I do it:
Firestore.instance
    .collection('products')
    .document('${widget.product.id}')
    .updateData({"comments": FieldValue.arrayUnion([_currentName])});


text:
Q: How do I fetch the last element of an array in Swift? I can do this:
var a = [1,5,7,9,22]
a.count               // 5
a[a.count - 1]        // 22
a[a.endIndex - 1]     // 22

but surely there's a prettier way?

A: Update: Swift 2.0 now includes first:T? and last:T? properties built-in.

When you need to you can make the built-in Swift API's prettier by providing your own extensions, e.g:
extension Array {
    var last: T {
        return self[self.endIndex - 1]
    }
}

This lets you now access the last element on any array with:
[1,5,7,9,22].last

A: You can also get and remove last element from array
removeLast()
Example:
var array = [1, 2, 3]
let removed = array.removeLast()
// array is [1, 2]
// removed is 3

Taken from Apple docs (this source expired but you can find examples in this documentation page)

A: You can fetch the last element of an Array by using the last property.
Code:
let lastElement = yourArray.last

A: edit for swift 2.2
extension Array {
    var last: Element {
        return self[self.endIndex - 1]
    }
}

A: swift 5:
if let last = a.last {
   print(last)
}

A: As of beta5 there is now a first and last property

In addition to Array acquiring first and last, the lazy collections also implement first (and last if they can index bidirectionally), as well as isEmpty.


text:
Q: Capture stdout and stderr as separate variables in fish shell Is this even possible?
I'd like to run a command but capture its stdout and stderr as separate variables. Currently I'm using set -l var (cmd), which leaves stderr untouched. I can do set -l var (cmd ^&1) which will merge stdout and stderr into var, but then I can't easily separate them again.
Is there any way to get var and var_err to hold stdout and stderr from cmd?

A: begin; cmd ^|read -z err; end |read -z out

From fish-shell/fish-shell #2463,

An issue in your fish example is that it redirects [stdout] of both [cmd] and [read], so if the latter prints anything, it'll be carried through the pipe.

But I don't think read should ever print anything (especially to stdout) in the normal case, so this should be fine.
Edit: If the exact semantics of set var (cmd) are needed, that can be achieved using set var (printf '%s' $out) and set var_err (printf '%s' $err)

A: The simplest method would  be to redirect one of the streams to a file:
set tmpf (mktemp)
trap "rm $tmpf" EXIT

set var (cmd ^ $tmpf)
set var_err (cat $tmpf)


text:
Q: got crash when try to use intent to send email (Kotlin) I got a crash when I try to send an email using intent with kotlin
here's my function
/**
 * intentEmail is called when we need to send email
 *
 * @param price int
 */
fun intentEmail(price: Int) {

    var intent =  Intent(Intent.ACTION_SEND)

    //intent.putExtra(Intent.EXTRA_EMAIL, addressees)
    intent.data= Uri.parse("mailto:")
    intent.putExtra(Intent.EXTRA_SUBJECT, "Just Java order for $name")
    intent.putExtra(Intent.EXTRA_TEXT, createOrderSummary(price))

    if(intent.resolveActivity(packageManager) != null){
        startActivity(intent)
    }

}

and the crash happens when calling startActivity(intent)
and here's my LogCat

A: maybe your phone is not accept this intent action. you should use try catch the avoid this crash.
you can also use the phone's other "send mail" app, so that  you can find out what's the correct intent.

A: The issue was in
var intent =  Intent(Intent.ACTION_SEND)
when I changed it to
var intent =  Intent(Intent.ACTION_SENDTO)
it works fine thanks to @lampenlampen


text:
Q: Filter JSON using bs4 or other and organize in excel using openpyxl I want to filter a json file from pool.pm
For example, https://pool.pm/wallet/$1111 and I want to get all the "policy"'s and how many time it repeats and organize it on a excel using openpyxl and in the first column the policies and in the 2nd column how many time it repeats
What I have:
import openpyxl
import json
import requests
from bs4 import BeautifulSoup

pooladd = str(input("Insira o address:\t"))

api_pool = "https://pool.pm/wallet/{}"
api_pool2 = api_pool.format(pooladd)
data = requests.get(api_pool2).json()

Output:

Policy
How Many

f0ff48bbb7bbe9d59a40f1ce90e9e9d0ff5002ec48f232b49ca0fb9a
10

8728079879ce4304fd305b12878e0fcea3b8a3a5435a21b5dec35a11
3

A: I don't see pandas tag but in case you're interested, here is an approach with value_counts :
#pip install pandas
import pandas as pd

out = (
        pd.Series([t["policy"] for t in data["tokens"]])
            .value_counts()
            .to_frame("How Many")
            .reset_index(names="Policy")
      )

If you wanna make an Excel spreadsheet, use pandas.DataFrame.to_excel :
out.to_excel("output_file.xlsx", sheet_name="test_name", index=False)

# Output :
print(out)
                                                     Policy  How Many
0  f0ff48bbb7bbe9d59a40f1ce90e9e9d0ff5002ec48f232b49ca0fb9a        10
1  8728079879ce4304fd305b12878e0fcea3b8a3a5435a21b5dec35a11         3

A: another implementation!, comments are added to the code.
Build the dictionary and then write the excel.
import openpyxl
import json
import requests
from bs4 import BeautifulSoup

pooladd = str(input("Insira o address:\t"))

api_pool = "https://pool.pm/wallet/{}"
api_pool2 = api_pool.format(pooladd)
data = requests.get(api_pool2).json()

policies= [e_tkn['policy'] for e_tkn in data['tokens']]
unique_policies=set(policies)
result={}
for each_policy in unique_policies:
    result[each_policy]=policies.count(each_policy)

result=sorted(((value,key) for (key,value) in result.items()),reverse=True)# sort in decending order, reverse=True
print(result)
from openpyxl import Workbook

wb = Workbook()
ws = wb.active
ws['A1'] = 'Policy' # header
ws['B1'] = 'How Many' # header

row=2
for count,policy in result:
    ws['A' + str(row)]=policy # for each row, for example A2=policy
    ws['B' + str(row)]=count # for each row , for example B2 = count
    row=row+1

wb.save('policies.xlsx')


text:
Q: correct usage of PositionIncrement I recently created a custom TokenFilter to split existing tokens that are CamelCased in separate additional tokens. For example, the phrase MyClassName would result in the following 4 tokens:
MyClassName, My, Class, Name
Here is the code:
private class CamelCaseFilter extends TokenFilter {

    private final CharTermAttribute termAttribute = addAttribute(CharTermAttribute.class);
    private final OffsetAttribute offsetAttribute = addAttribute(OffsetAttribute.class);
    private final PositionIncrementAttribute posIncAttribute = addAttribute(PositionIncrementAttribute.class);

    private boolean processing;
    private int processingIndex;
    private int processingCharPos;
    private String[] splittedValues;

    protected CamelCaseFilter(TokenStream input) {
        super(input);
    }

    @Override
    public boolean incrementToken() throws IOException {
        if (!processing) {
            if (!input.incrementToken()) {
                return false;
            }

            posIncAttribute.setPositionIncrement(1);
            splittedValues = splitCamelCase(termAttribute.toString());
            if (splittedValues.length > 1) {
                processing = true;
                processingIndex = 0;
                processingCharPos = 0;
            }
            return true;
        }

        String part = splittedValues[processingIndex];

        termAttribute.setEmpty();
        termAttribute.append(part);
        offsetAttribute.setOffset(processingCharPos, processingCharPos + part.length());

        processingCharPos += part.length();
        processingIndex++;

        if (processingIndex >= splittedValues.length) {
            processing = false;
        }

        return true;
    }

    private static String[] splitCamelCase(String s) {
        // TODO maybe replace with splitByCharacterTypeCamelCase from commons?
        // http://commons.apache.org/proper/commons-lang/javadocs/api-3.1/org/apache/commons/lang3/StringUtils.html#splitByCharacterTypeCamelCase%28java.lang.String%29
        return s.split("(?<!(^|[A-Z]))(?=[A-Z])|(?<!^)(?=[A-Z][a-z0-9])");
    }
}

My question is, if it is correct (and necessary) to use the PositionIncrementAttribute like this. The documentation says:

Determines the position of this token relative to the previous Token in a TokenStream, used in phrase searching.
The default value is one.
Some common uses for this are:

*

*Set it to zero to put multiple terms in the same position. This is useful if, e.g., a word has multiple stems. Searches for phrases including either stem will match. In this case, all but the first stem's increment should be set to zero: the increment of the first instance should be one. Repeating a token with an increment of zero can also be used to boost the scores of matches on that token.

*...

However, that doesn't really match my usecase. Another part also says:

Note that a filter that filters out tokens must increment the position increment in order not to generate corrupt tokenstream graphs.

In my case I do not remove, but add tokens. Since I keep the original term, but additionally store the parts of it as well, I thought setting the positional increment to zero would be important to not negatively affect search through adding new tokens. Is that the really the case, or did I make a mistake?


text:
Q: Can "fish" really be spelled "pheti"? My teacher has a sign in his room that says:

The English Language is a Challenge: This is why "Fish" can be spelled "Pheti"!

Is this true or is just to confuse students?

A: StoneyB is absolutely correct in that Pheti is a joke, a play on the idiosyncrasies of the English spelling and pronunciation but it doesn't end there. In fact, it should arouse a phonic and phonemic awareness in the reader or student reading that word. As it appears to have done so with you.
In order to pronounce this word as "fish" /fɪʃ/, you need be familiar with some of the so-called conventional spelling  guidelines.

*

*ph is often pronounced as /f/. For example; photos;  photocopier; elephant /ˈelɪfənt/.

*e is sometimes pronounced as /ɪ/. For example; England, women /ˈwɪmɪn/. N.B. See how the letter o is pronounced in the same way!

*ti is sometimes pronounced as /ʃ/. For example; inflation /ɪnˈfleɪʃən/;  station /ˈsteɪʃən/.
Note that in all the examples I said "is sometimes pronounced" because as nearly everyone knows by now, there are no fixed rules in English spelling or pronunciation.

A: Whilst it is a joke nowadays, it's because before Dr Johnson wrote the dictionary, there wasn't any correct way of spelling something as there weren't any rules to our spelling, hence why our phonetics don't tend to make much sense. For example if you look through Shakespeare's original scripts you'll find that he spells his own name in different ways as well as words. So whilst 'ghoti' and 'pheti' are jokes, in a time before the dictionary was established, these two spellings would be accepted as one of the numerous spellings for fish.


text:
Q: GCP DataPrep- moving window I have a CSV file of the following format that I am trying to wrangle with GCP dataprep.
   Timestamp                 Tag           Value
   2018-05-01 09:00:00     Temperature     40.1
   2018-05-01 09:00:00     Humidity        80
   2018-05-01 09:05:00     Temperature     40.2
   2018-05-01 09:05:00     Humidity        80
   2018-05-01 09:10:00     Temperature     40.0
   2018-05-01 09:10:00     Humidity        82

The data extends in 5 minutes interval for 2 weeks.
I would like to transform it such that at each 10 minute interval, I am displaying the average(or min/max/median) of the previous 10 minutes and also pivot it,so that the end result I get is as follows:
  Timestamp             Temperature    Humidity
 2018-05-01 09:10:00      40.1         80.06

So essentially, the value at 09:10 is the average of the values at 09:00, 09:05 and 09:10.
And the value at 09:25 would be the average at 09:15,09:20,09:25.
I have tried window functions and aggregate, but seem to be unable to get it to work.
Thank you for your input!

A: I would start by reformatting the data were each line is of the form:
  Timestamp                Temperature      Humidity
  2018-05-01 09:00:00      40.1             80
  2018-05-01 09:05:00      40.2             80
  2018-05-01 09:10:00      40               82
  2018-05-01 09:15:00      41               81
  2018-05-01 09:20:00      40.8             81
  2018-05-01 09:25:00      40.2             84

This will reduce the size of your data in half and reduce the amount of storage space you are utilizing. You can use the 'convert values to columns' function in Dataprep. This will create a column for Temperature and one for Humidity.
Once in that format, you can use the window function ROLLINGAVERAGE to compute the averages. Make the function compute the average for the two rows which precedes it by setting the following parameters:
rollingaverage(Temperature, 2, 0)

The first argument is the column name, the second is the preceding rows, and the last one is the number of following rows on which the average is computed. Repeat the above function for the Humidity column. The results should resemble the following:

Next, under the filter rows option, use the 'rows at regular intervals' function to keep every third row starting from the third entry. Set the parameter as follows:

Remove the two original Temperature and Humidity rows and you will get the following:
  Timestamp                Temperature      Humidity
  2018-05-01 09:10:00      40.1             80.67
  2018-05-01 09:25:00      41               82


text:
Q: how to make "Selection.Start" start after the first 3 line? when searching through a document how can i skip the first 3 line of text. I am currently starting at the top of the document. I have added a code snip and i was wondering how can i start at the third line?
if (newSearch)
{
    lastOffset = -1;

    searchRange = new TextRange(
        body.Selection.Start.GetPositionAtOffset(1),
        body.Document.ContentEnd);

    lastSearch = searchText;
}


text:
Q: Java android capture photo with custom resolution I want to do this : I choose a resolution next I set the closest resolution and take a photo , but I don't know how I get a list of resolution and set a resolution.
I take a photo just like this :
  private void clickpic() {
        // Check Camera
        if (getApplicationContext().getPackageManager().hasSystemFeature(
                PackageManager.FEATURE_CAMERA)) {
            // Open default camera
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
            // start the image capture Intent
            startActivityForResult(intent, REQUEST_CAMERA);
        } else {
            Toast.makeText(getApplication(), R.string.no_camera, Toast.LENGTH_LONG).show();
        }
    }

A: ACTION_IMAGE_CAPTURE does not grant you control over the resolution. The closest thing that it does is let you choose between a full-size image (provided if you supply EXTRA_OUTPUT) or a thumbnail (provided if you do not supply EXTRA_OUTPUT).


text:
Q: Undfined variable 'posts' - Laravel 5 In my ShowController, I returned a view with variable posts, like
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Depress;
use DB;
use App\Http\Requests;

class ShowController extends Controller
{
    public function showPost(Request $request)
    {
        $posts = Depress::all();
        return view('homeview')->with('posts', $posts);
    }
}

And in my, homeview.blade.php ,
 @foreach($posts as $post)

{{ $post->name }}

                {{ $post->depression }}

 @endforeach

But, it's showing,
 Undefined Variable: posts
Can anyone please help ?

A: The posts variable is in session. So use Session::get('posts') to get it.
Or use return view('homeview', compact('posts')); and $posts will be available in view as php variable.

A: add use App\Post; to your ShowController


text:
Q: Why did Quark have different skin coloration around his eyes? In Deep Space Nine, Quark seems to be the only Ferengi who has dark skin around his eyes. No members of his family have this feature - and further, as far as I can remember, he is the only Ferengi in the entire Star Trek series (TNG, DS9, Voyager) with this feature.

I'm curious if there's an in-universe reason for this, but I'm sure I could come up with something reasonable.
The more important question - what was the out-of-universe reason for Quark's extra eye makeup?

A: In-universe
In the final episode, "What You Leave Behind", we have the following admission from Quark:

QUARK: They think they have it rough? They should try leading my life for a day. The hospitality industry isn't for the faint-hearted.
VIC: A bartender's life is a lonely one.
QUARK: That's true, but few people understand that. They think it's one big, happy party. They forget that the person giving the party never has any fun. He's too busy making sure everybody else is having fun. All I do all day long is give, give, give.

It seems that, as the manager of a very busy dining, gambling, and holo-entertainment establishment for more than a decade, Quark has lived a rather stressful life.
Combine this with having to manage the logistics of various interstellar business deals, and there is more than enough cause for lack of restful sleep and some subsequent dark rings around the eyes.
Out-of-universe
Out-of-universe, I suspect that the extra makeup is partly to support the in-universe perception of Quark as weary and more concerned with his business than with his health, and partly because it probably looked better on Armin Shimerman (Quark actor) than not having it.
According to the Deep Space Nine Companion, Armin Shimerman's facial prosthetic was constructed as the first episode, "Emissary", was being filmed and was not ready in time for Quark's scenes (and so they had to use Rom's nose on Quark's face).  One could theorize that the extra eye makeup was initially applied to compensate for defects in the original prosthetic, and was perhaps retained because it enhanced rather than detracted from Quark's character.
Finally, Armin Shimerman himself has the following to say:

"Quark was much more challenging because of the make-up. It is very difficult to be an actor and work with something on your face. Very difficult because all you have is your face to work with. When it's covered up with rubber it leaves you only two things to work with and that's your eyes and your soul. And hopefully the soul comes out through the eyes."

(Source — thanks @Richard)
In other words, Shimerman realizes the importance of conveying emotion with your eyes when your face is hindered by makeup, and so the extra makeup may have been part of a deliberate attempt to emphasize his eyes.
We probably can't say more than these speculations.  Unfortunately, there doesn't seem to be a definitive statement from Michael Westmore, the lead makeup artist for DS9.

A: This question was recently answered by Armin Shimerman himself in a YouTube video "Star Trek: Deep Space Nine Deep Dive: Ep 1, "Emissary" with Armin Shimerman | T7R #208". According to him, his makeup artist, Karen Westerfield, took the liberty to apply the dark red color around Quarks eyes on their first day of work, in order to make Shimerman's blue eyes to stand out better. When the makeup supervisor, Michael Westmore, saw that, he was furious. However, since they already shot for several days with this makeup, it was to late to change it.


text:
Q: what is the mathematical definition of "binomial logistic regression" this post and wiki mentioned binomial logistic regression without giving a mathematical definition.
this post gives this formula
$log(\dfrac{p}{(1-p)})$
this seems to be related to binomial logistic regression, but not clear.

what is the mathematical definition of "binomial logistic regression"

A: Let $X \in \mathbb R^d, Y \in \{ 0, 1 \}$ be a feature vector and label describing a randomly selected member of a population. Both $X$ and $Y$ are random variables. Our goal is to predict the value of $Y$, given the value of $X$. Logistic regression makes a modeling assumption that
$$
\tag{1}P(Y = 1 \mid X = x) = \sigma(\beta_0 + \beta_1^T x),
$$ where $\sigma(u) = e^u/(1 + e^u)$ is the logistic function (which you can think of as converting a real number into a probability) and $\beta_0 \in \mathbb R, \beta_1 \in \mathbb R^d$ are parameters of the model. These parameters can be estimated using maximum likelihood estimation.
This version of logistic regression, where there are only two possible classes (two possible values of the label $Y$) is sometimes called "binary logistic regression" or "binomial logistic regression", though I don't see why the term "binomial" would be used here.

Comment: If you want to predict the probability that an item described by a feature vector $x$ has label $Y = 1$, the model (1) is about the simplest thing you could possibly come up with. You might at first try making a modeling assumption that $P(Y = 1 \mid X = x) = \beta_0 + \beta_1^T x$, but that model is flawed because a probability must be between $0$ and $1$, whereas $\beta_0 + \beta_1^T x$ could be any real number. The logistic function $\sigma$ is the simplest device for converting a real number into a probability. (One elegant property of $\sigma$ is that $\sigma' = \sigma - \sigma^2$, which simplifies some calculations.)
If the logistic function seems like a weird or arbitrary thing to inject into our model, and if we view "odds" as a natural quantity to work with, we could express the model (1) equivalently as
$$
\log\left( \frac{P(Y = 1 \mid X = x)}{P(Y = 0 \mid X = x)} \right)= \beta_0 + \beta_1^T x.
$$
But to me the equation (1) seems simpler and more clear.

A: $\dfrac{p}{1-p}$ translates a probability into odds. So $\log\left(\dfrac{p}{1-p}\right)$ is the logarithm of the odds, also known as the logit function.  It has the advantage that multiplication of odds corresponds to addition of log-odds, and odds ratios to the subtraction of log-odds, allowing linear methods like linear regression to be applied
The inverse function of taking log-odds is $\dfrac{e^{x}}{e^{x}+1}=\dfrac{1}{1+e^{-x}}$, called the logistic function. This can be given a scale and location generalisation of the form $\dfrac{1}{1+e^{-(\beta_0+\beta_1 x)}}$
So with some binomial outcomes where you think the probability parameter is related to an explanatory variable, you could use maximum likelihood methods and a logistic model.  The log-likelihood function you are trying to maximise then has a relatively simple translation to log-odds, and the logistic function then allows the results of this modelling to be translated back to probabilities


text:
Q: Maybe weird behaviour of DOM tree updating (client side blazor, razor, C# .net ASP.net hosted) Hello there,
i have just made a weird experience with the DOM tree updating of blazor.
The code is easy:
1) the user can choose between 2 Types A or B with radiobuttons.
2) when A or B is chosen, more options appear as checkboxes (A lets you select A1 and/or A2, B lets you select B1 and/or B2).
Big question is: what happens, if you do the following:
3) select A  (=> two checkboxes A1 and A2 appear)
4) check A1
5) select B  (=> A1 and A2 vanish, checkboxes B1 and B2 appear)
6) look at the state of B1
I made 2 different versions:
7) one, where i define the checkboxes for A and B separately   -> this works as intended (=B1 and B2 unchecked)
8) one, where i define them directly, but with the right name   -> this does not work! B1 is checked!
As i understand it, when selecting B (step 5), blazor updates the DOM tree. But i dont get why the browser remembers the checkbox B1 as checked, only because i checked A1, and even though i created it completely new. This looks like a bug to me. I mean, i even give the checkbox another name.
Is there a possibility to "clear the browser memory regarding the checking-state of the checkbox" or something else?
I created this minimum-example for simplicity. In my code, the checkboxes are created in a foreach, and i also have the not-intended behaviour.
Happy to hear your opinion and/or hints.
Tim
Here is the code of my razor component:

    <input type="radio" name="RB_Type" @onclick="@(() => SelectType("A"))" /> Type A

    <input type="radio" name="RB_Type" @onclick="@(() => SelectType("B"))" /> Type B

@if (accType == "A")
{
    <input type="checkbox" name="A1" unchecked>A1

    <input type="checkbox" name="A2" unchecked>A2

}
else if (accType == "B")
{
    <input type="checkbox" name="B1" unchecked>B1

    <input type="checkbox" name="B2" unchecked>B2

}

@if (accType != "")
{
    <input type="checkbox" name="@(accType + "1")" unchecked>@(accType + "1")

    <input type="checkbox" name="@(accType + "2")" unchecked>@(accType + "2")

}

@code {

    private string accType = "";

    private void SelectType(string type)
    {
        this.accType = type;
        StateHasChanged();
    }
}

A: Add some @key="" attributes like so:
@if (accType != "")
{
    <input type="checkbox" @key="@(accType + "1")" name="@(accType + "1")" unchecked>@(accType + "1")

    <input type="checkbox" @key="@(accType + "2")" name="@(accType + "2")" unchecked>@(accType + "2")

}

The blazor diff engine tries to minimize changes. So when it sees 2 checkboxes at the same place it will assume they are the same. The name property doesn't help to distinguish between A and B controls.
But you will find this 2nd version (@(accType + "1")) of your code is difficult in databinding too.


text:
Q: No resource identifier found for attribute 'hardwareAccelerated' when building with apache ant My app targeted to the android API level 7 (2.1) and under the Eclipse all work good (resulting APK also works fine on the 2.1 devices). I try to build app with the apache ant and got this error. All of the solutions for the same problems tells me that I must set another target API level.
I want to simple ignore this attribute in manifest - as I find, in old devices it just ignored without any errors

A: I don't think it's possible to have hardware acceleration with API level less than 11. Check here for more info.
Your best bet is to simply remove hardware acceleration attributes from your manifest.

A: I declared
   <uses-sdk
    android:minSdkVersion="8"
    android:targetSdkVersion="21" />

in manifest file. It resolved my problem. Hope it help others.


text:
Q: CSS - Hover One Element, Change Visibility on Another HTML is as Follows

Item

Sub One

CSS is
.sub { visibility: hidden; }
#master .has-sub:hover > .sub { visibility: visible;}

I pretty much took the approach from a site where this works, but on my adventure the hero fails. Badly.  What am I doing wrong?

A: Your HTML is invalid...you have closed
Item
 too soon.

.sub {
    visibility: hidden;
}
#master .has-sub:hover > .sub {
    visibility: visible;
}

Item

Sub One

A: First your html is invalid please fix that
And Try this
Change your html to

Item

Sub One

  .sub {
    visibility: hidden;
}
#master .has-sub:hover > .sub {
    visibility: visible;
}

DEMO


text:
Q: how to use jQuery.when() with multiple jsonp requests? I have 2 cross domain jsonp requests that need to be completed before another method can be executed.  So I tried the $.when() function
$.when(getX(), getY()).then(createXY);

getX() and getY() make $.ajax() requests to two different domains with separate jsonp callbacks.
Contrary to my original thought, createXY() gets invoked before the callbacks return.  createXY() therefore does not have the data it needs.
Can someone please provide me an example on invoking a function when multiple async jsonp requests are completed?

A: For $.when() to work, it must be passed a deferred object that it is waiting for.  Make sure that your getX() and getY() functions are returning the deferred object created by the jQuery ajax call that each makes.
If you want help doing that, then post the code for getX() and getY().
Here's an example right from the jQuery doc for $.when():
$.when($.ajax("/page1.php"), $.ajax("/page2.php")).done(function(a1,  a2){
  /* a1 and a2 are arguments resolved for the
      page1 and page2 ajax requests, respectively */
  var jqXHR = a1[2]; /* arguments are [ "success", statusText, jqXHR ] */
  if ( /Whip It/.test(jqXHR.responseText) ) {
    alert("First page has 'Whip It' somewhere.");
  }
});

A: very silly mistake in the code.  getX() and getY() called $.ajax() but never returns it.  wrap the $.ajax() calls with return and the code is working fine now.  Thanks for all your help!


text:
Q: interject synchronous code into asynchoronous I'm running the lighthouse cli against a ~50 site list of sites. I'm simply running it in a .forEach loop, which, if I understand, is blocking, aka, synchronous. However, I end up spinning up 50 Chrome Canary instances all at once. In my limited understanding of these things I think the thread is started synchronously, but then node can pass the thread off to the kernel and happily start the next. Again, that's just my hand-wavy understanding of what's going on.
I'm using this function that I cribbed from somewhere:
function launchChromeAndLighthouse(url, opts, config = null) {
  return chromeLauncher.launch({chromeFlags: opts.chromeFlags}).then(chrome => {
    opts.port = chrome.port;
    return lighthouse(url, opts, config).then(results =>
      chrome.kill().then(() => results));
  });
}

I tried nextTick in the loop:
asyncFuncs().then( async (sites) => {
  sites.forEach( (site) => {
    process.nextTick(launchChromeAndRunLighthouse(site.url, opts))
  })
})

But this still spawns a bunch of Chrome instances. How do I pause execution while one lighthouse completes?

A: Since launchChromeAndRunLighthouse() returns a promise to mark when it's done, if you want to only run them serially one at a time, you can switch to a for loop and use await:
asyncFuncs().then( async (sites) => {
  for (let site of sites) {
    await launchChromeAndRunLighthouse(site.url, opts);
  }
});

If you're trying to collect all the results:
asyncFuncs().then( async (sites) => {
    let results = [];
    for (let site of sites) {
      let r = await launchChromeAndRunLighthouse(site.url, opts);
      results.push(r);
    }
    return results;
}).then(results => {
    // all results here
}).catch(err => {
    // process error here
});

If you want to run N chrome instances at a time such that it initially starts up N instances and then each time one finishes, you launch the next one that's waiting, that is more complicated to keep track of how many instances are running.  There's a helper function call pMap() or mapConcurrent() that can do that for you in these answers:
Make several requests to an API that can only handle 20 request a minute
Promise.all consumes all my RAM

The Bluebird Promise library also has concurrency control in its Promise.map() function.


text:
Q: Build system that allows sharing modules amongst different binaries I'm trying to choose the most appropriate build system to work in enterprise with a common source repository, emphasizing sharing of common code.  I'd like the source hierarchy to look something like this:

 - src
   - java
     - common
       - net
       - database
     - team1
     - team2
     - team3
       - lib
 - tests
   - java
     - common
       - net
       - database
     - team1
     - team2
     - team3
       - lib

The goal is to have a build system where team[1-3] can have independent builds that explicitly specify their dependencies.  Dependencies might look like:

 - team1
   - common/net
   - team3/lib
 - team2
   - common/database
 - team3

So, for example, the build for team1 would include everything within the team1, common/net, and team3/lib; but nothing else.  Ideally, tests would be integrated in the same fashion (testing team1 would run tests for team1, common/net, and team3/lib).
I'm currently using Ant, but haven't found a sane way to manage a hierarchy like this.  I started to look at Maven 2 for its ability to manage a dependency hierarchy, but it seems to want full-fledged projects for each module.  That wouldn't be a problem, but it seems to force me into a directory structure that does not map well to the traditional java package hierarchy.  It seems like I might be able to do what I want with buildr using an alternative layout, but I'm worried that might prove to be brittle.
Can someone recommend something that might work for me?

A: I think you actually have three issues here.

*

*How to layout your project so that the artifacts make sense.

*How to best handle the sharing of these artifacts for each project.

*How to handle the loss in productivity while converting the development team to use the new project structure.

For the first issue, try to use Maven conventions wherever possible and organize the project into multiple artifacts.  If the artifacts should be nested under a parent, do so.  Start off with the simplest artifact which has no dependencies and work your way through the code.
I'm not sure why you believe the layout won't support the traditional Java hierarchy?  It should work, especially if you use parent poms.
Obviously the second issue can become quite a handful depending upon how you handle the first one.  I would err on the side of creating more artifacts instead of fewer and using a repository manager like Nexus or Artifactory to manage them.  At least that way, your team's builds can rely on pre-built and tested jars by hitting your repository to pull down the latest SNAPSHOT or RELEASE of the jar they are working with.
For the third, make sure you're using IDEs that have Maven support.  If you're stuck using something like Rational Application Developer 7.0.x or an IDE based on something less than Eclipse 3.4, then you won't be able to use the M2Eclipse plugin. Without M2Eclipse, the developers will have to jump through some manual hoops which are not ideal. Netbeans 6.7 and 6.8 have very good Maven support.

A: As you say, Maven 2 is the preferred option for your case.
Maven folder structure is not madnatory - it is configurable, if you consider it unsiutable. However, I think it is a good structure that you can follow without remorse.
You can use a repository manager so that people who use some dependencies don't necessarily need to checkout the projects they depend on.

A:
I'm currently using Ant, but haven't found a sane way to manage a hierarchy like this.

This is surprising as Ant (+Ivy?) gives you all the flexibility you want.

I started to look at Maven 2 for its ability to manage a dependency hierarchy, but it seems to want full-fledged projects for each module.

If by this you mean one pom.xml per module, then that's correct.

That wouldn't be a problem, but it seems to force me into a directory structure that does not map well to the traditional java package hierarchy.

Yes, Maven comes with some conventions, the project directory structure being one of them. This is (a bit) configurable though but I don't think you'll be able to match the wanted layout (with tests and sources into separated hierarchies). And actually, I would strongly advice to use defaults if you go for Maven, you should adopt its philosophy, it will save you a lot, really a lot, of pain (not even mentioning that some plugins might use these default in an hard coded way).
To be honest, I don't really understand what you mean by a directory structure that does not map well to the traditional java package hierarchy. First, Maven is perfect for Java, so this doesn't make any sense to me. Second, and this might be more subjective, your layout (with separated tests and sources trees) doesn't look traditional at all to me. Maybe you should clarify what you mean exactly by traditional...

It seems like I might be able to do what I want with buildr using an alternative layout, but I'm worried that might prove to be brittle

I don't know buildr really well so I can't say much about it but I know it is indeed more flexible. That said, if Ant doesn't give you satisfaction in terms of flexibility, then I don't see why buildr would be better.
And don't forget that buildr and Ant+Ivy have much smaller communities compared to Maven. Don't underestimate this, this might become a real concern.
Personally, I would go for Maven and reconsider your layout. But let's say I'm biased.

A:
I started to look at Maven 2 for its ability to manage a dependency hierarchy, but it seems to want full-fledged projects for each module.

That's one way to do it.  Alternatively, a multi-module Maven project can be organized like this:
project
    module-1
        src
            main
                ....
            test
                ....
        pom.xml
    module-2
        src
            main
                ....
            test
                ....
        pom.xml
    ...
    pom.xml

where each pom.xml could also refer to modules defined by other trees.  BTW, the Eclipse maven plugin supports this approach as well as the more common one-module-per-project approach.

A: What you are going for is going to give you lots of trouble in the long-term... each standalone component should really be made into its own project with its own repository, otherwise, you can get into lots of issues with changes in one component breaking the other components and updating taking excessively long. I strongly recommend that you make each component into its own project and using Maven2 to build.

A: You can do it with Buildr. You could live for some time with it.
Of course, like most people on the thread, I would rather not recommend this approach.
You can also use base_dir to change the base directory of the projects.


text:
Q: Cloud Composer is not getting deleted Cloud Composer is not getting deleted properly with this error:

DELETE operation on this environment failed 4 days ago with the following error message:
  RPC Skipped due to required preoperation not finished yet.
RPC Skipped due to required preoperation not finished yet.

here's the error screenshot:

A: Please, follow the below steps to delete environments resources manually:

*

*Delete GKE cluster, that corresponds to environment

*Delete the Google Storage bucket used by environment

*Delete the related deployments with:

gcloud deployment-manager deployments delete <DEPLOYMENT_NAME> --delete-policy=ABANDON

*Then try again to delete the Composer environments with:

gcloud composer environments delete <ENVIRONMENT_NAME> --location <LOCATION>
The problem you are facing could be also related with a misconfiguration with the Cloud Composer service account in your project. By default, Cloud Composer environments run as the Compute Engine default service account, but when you are using a custom service account, at a minimum, that service account requires the permissions that the composer.worker role provides to access resources in the Cloud Composer environment. Please refer to this documentation for further details about how to grant a role to a service account.
Please, try to add the policy binding for Cloud Composer API Service Agent role to the service account, so the command would be:
gcloud projects add-iam-policy-binding <PROJECT_ID> --member=<MEMBER>  --role=roles/composer.serviceAgent
The member should be of the form user|group|serviceAccount:email or domain:domain (refer to documentation).
Then, please retry the action of remove your Composer environments. I hope you find the above pieces of information useful.


text:
Q: Clustering words together by looking at vector similiarity (Python) I have a long list with the format
mylist =[([256, 408, 147, 628], 'ezis'), ([628, 526, 236, 676], 'camera'), ([526, 876, 676, 541], 'camera'), ([567, 731, 724, 203], 'size'), ([822, 187, 256, 172], 'camera'), ([489, 628, 214, 428], 'esu'), ([648, 487, 487, 338], 'take'), ([487, 606, 338, 428], 'pictur'),.....]

#The full list can be found at https://pastebin.com/Mn9En3r6

Where the vectors paired with each word in this represent the unique index of words surrounding it in a sentence (i.e the number 256 represents 'big' etc.)
In this long list there is only 100 unique words, 50 real words and 50 words which are just those real words reversed (size -> ezis)
I want to cluster them together by comparing their vector values and hopefully, most of the real words and their reversed counterpart should be paired.
I'd ideally like to use the Sklearn clustering library (https://scikit-learn.org/stable/modules/generated/sklearn.cluster.AgglomerativeClustering.html) but the problem I'm having is I'm not too sure how to implement this.
Would taking the 'average vector' value of each of these 100 words and then clustering them together work? If so, how would I do this?

A: Maybe this?
import numpy as np
from sklearn.cluster import AffinityPropagation
import distance

words = '''[([256, 408, 147, 628], 'ezis'), ([628, 526, 236, 676], 'camera'), ([526, 876, 676, 541], 'camera'), ([567, 731, 724, 203], 'size'), ([822, 187, 256, 172], 'camera'), ([489, 628, 214, 428], 'esu'), ([648, 487, 487, 338], 'take'), ([487, 606, 338, 428], 'pictur')'''.split(',') #Replace this line
words = np.asarray(words) #So that indexing with a list will work
lev_similarity = -1*np.array([[distance.levenshtein(w1,w2) for w1 in words] for w2 in words])

affprop = AffinityPropagation(affinity="precomputed", damping=0.5)
affprop.fit(lev_similarity)
for cluster_id in np.unique(affprop.labels_):
    exemplar = words[affprop.cluster_centers_indices_[cluster_id]]
    cluster = np.unique(words[np.nonzero(affprop.labels_==cluster_id)])
    cluster_str = ", ".join(cluster)
    print(" - *%s:* %s" % (exemplar, cluster_str))

You could do this too.
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.cluster import KMeans
from sklearn.metrics import adjusted_rand_score

documents = ["([256, 408, 147, 628], 'ezis')",
             "([628, 526, 236, 676], 'camera')",
             "([526, 876, 676, 541], 'camera')",
             "([567, 731, 724, 203], 'size')",
             "([822, 187, 256, 172], 'camera')",
             "([489, 628, 214, 428], 'esu')",
             "([648, 487, 487, 338], 'take')"]

vectorizer = TfidfVectorizer(stop_words='english')
X = vectorizer.fit_transform(documents)

true_k = 8
model = KMeans(n_clusters=true_k, init='k-means++', max_iter=1000, n_init=1)
model.fit(X)

print("Top terms per cluster:")
order_centroids = model.cluster_centers_.argsort()[:, ::-1]
terms = vectorizer.get_feature_names()
for i in range(true_k):
    print("Cluster %d:" % i),
    for ind in order_centroids[i, :10]:
        print(' %s' % terms[ind]),
    print

print("\n")
print("Prediction")

Y = vectorizer.transform(["chrome browser to open."])
prediction = model.predict(Y)
print(prediction)

Y = vectorizer.transform(["My cat is hungry."])
prediction = model.predict(Y)
print(prediction)


text:
Q: inheritance getter from superclass and subclass Here are my class's feature:

I have to override toString method to make each class print out:
"[Superclass]: [name-of-superclass] ---[subclass]: [name-of-subclass]"

and I have getter getDescription for each classes' name
I know for subclasses, they only have to do super.getDescription and this.getDescription.

*

*But I don't understand for the superclass LivingRoomItem, how can it call all the getDescription from its subclass?

EDIT:
class livingRoomItem{
    int id;
    double price;
    String color;
    String description = "livingRoomItem";

    livingRoomItem(int id, double price, String color, String description){
        this.id = id;
        this.price = price;
        this.color = color;
        this.description = description;
    }

    @Override
    public String toString(){
        return "[Superclass] :" + this.description + "----" + "[subclass]: ";
    }

 public String getDescription() {
    return "livingRoomItem";
}

public void setDescription(String description) {
    this.description = description;
}

class Sofa extends livingRoomItem{
private int seater;

Sofa(int id, double price, String color, String description, int seater){
    super(id, price, color, description);
    this.seater = seater;
}
@Override
public String getDescription(){
    return "Sofa";
}

public int getSeater() {
    return seater;
}

public void setSeater(int seater) {
    this.seater = seater;
}
 @Override
public String toString(){
    return "[Superclass] :" + super.getDescription() + "----" + "[subclass]: "+ this.getDescription() ;
}

}

A: Your line of thinking is right, maybe only your execution is not.
Considering the following classes:
public class LivingRoomItem
public class Sofa extends LivingRoomItem
public class Table extends LivingRoomItem
public class Lighting extends LivingRoomItem

You can handle all of them as they are LivingRoomItem
In your calculatePrice method, you will use the LivingRoomItem as expected to handle all the objects:
public static BigDecimal calculateTotalPrice(List<LivingRoomItem> items) {
    return items.stream().map(item -> item.getPrice()).reduce(BigDecimal.ZERO, BigDecimal::add);
}

Since you are instantiating all the objects as themselves (not as LivingRoomItem), and setting the price, it should work properly:
public static void main(String[] args) {

    Sofa sofa = new Sofa();
    sofa.setPrice(BigDecimal.valueOf(200L));

    Lighting lighting = new Lighting();
    lighting.setPrice(BigDecimal.valueOf(652L));

    Table table = new Table();
    table.setPrice(BigDecimal.valueOf(598L));

    System.out.println(PriceUtil.calculateTotalPrice(Arrays.asList(sofa, lighting, table)));
}

Result:

I got your point in your toString, for the purpose of your exercise you can use the instanceof operator inside your superclass toString:
Example (inside your LivingRoomItem class):
return (this instanceof Sofa ? "Superclass... Subclass: Sofa" : "Regular LivingRoomItem toString");

But like I said, I believe it is right to show Object as superclass :) And only show LivingRoomItem on the subclasses.
Hope I was able to help you!


text:
Q: The use of the verb abstract in a question Is this correct?
What Java object type would abstract the number of apples to?
The context: An apple or another real-world object can be abstracted into a specific object in the Java programming language. I am trying to ask the other person what Java object type they would use abstract to.

A: Grammatically speaking - the verb needs a subject.
What Java object type would you abstract the number of apples to?
Alternatively you can put it in the passive voice:
What Java object type would the number of apples be abstracted to?
On more of a technical level, I probably wouldn't use abstract for assigning a simple count of the number of objects, only when there is more indirection at play.  But I assume this is just a simplified example for the sake of the English question, and the real situation is a more complex refactoring.

A: To expand on stevekeiretsu's answer, "abstract" needs a subject, and with your current wording, the only one available is the interrogative pronoun "what". That leaves "to" without an object.
And you're a bit ambiguous whether you're abstracting the number of apples or the apples themselves. The former can be handled just with the existing object type of integer.


text:
Q: A2LiX Translation Form - no errors printed I work with Symfony 2.4, KnpLabs DoctrineBehaviors bundle for translation in database, and A2LiX Translation Form for fields translation.
Form display and insertion in database work fine but errors for translation fields are not printed.
For example :

*

*the error of the field "photo" is print

*the error of the translatable field "title" is not print

Post.php
/**
*
* @ORM\Column(name="photo", type="string", length=255)
* @Assert\NotBlank(message="no photo")
*/
private $photo;

PostTranslation.php
/**
*
* @ORM\Column(name="title", type="string", length=255)
* @Assert\NotBlank(message="no title")
*/
private $title;

PostType.php
$builder
    ->add('translations', 'a2lix_translations')
    ->add('photo')
    ->add('submit', 'submit');

form.html.twig
<form method="post" novalidate {{form_enctype(form)}}>

{{ form_widget(form.translations) }}

{{ form_label(form.photo, 'photo') }}
{{ form_widget(form.photo) }}

{{ form_widget(form.submit) }}

{{ form_widget(form._token) }}

{{ form_errors(form.translations) }}

{{ form_errors(form.photo) }}

<form>

When i submit the form, i have this
Thanks for your help

A: First update to the last version of A2lixTranslationFormBundle.
And check that you have well in your Post entity, the @Assert\Valid annotation on the $translations field.
See http://symfony.com/doc/current/reference/constraints/Valid.html
use Symfony\Component\Validator\Constraints as Assert;

 /**
  * @Assert\Valid
  */
 protected $translations;

A: To do it inside YAML configuration, you can do this:
CRMPicco\GolfBundle\Entity\CourseGuide:
    properties:
        name:
            - NotBlank: ~
        translations:
            - Valid: ~


text:
Q: Django form integrityerror for concurrent operation on unique fields I noticed a thing that I don't know if it is a real issue or I'm doing some wrong design.
I have a model:
class A(Model):
    name = CharField(unique=True, max_length=255)

and a modelform linked to A, this modelform has a clean_name() method, that checks if that field is unique in the db (ignore the fact that modelforms already do that by default, I'm specifying that for the example here).
In the view if I do
o = form.save(commit=False)
# xyz
o.save()

and in #xyz I have another client that inserts an A object with the same name field value, o.save() triggers an Integrityerror exception, correctly preventing the duplicate record to be inserted.
What I want to know is how to handle those cases, should I wrap that o.save() with a try/except block and then populate the error field on the form specifying to choose another name value?
This is somewhat a common case that should happen to everyone and that solution is horrible, so I think I'm doing something terribly wrong.

A: I suspect this might be the case:
Model forms provide uniqueness validation only when a flag is set in xx_clean(). If you override clean with your own (as you have), you need to call the superclass's clean(). See overwriting the clean method.


text:
Q: ORA-00933 before update query Good day.
I create some repository for objects and try to update same object.
I used 'ExecuteStoreCommand' and next method
public void UpdatePatienAccount(long modelId, long patientId, long accountId)
{
//ExecuteStoreCommand(@"UPDATE PATIENT_ACCOUNT SET PATIENT_ID = :1 AND ACCOUNT_ID = :2 WHERE ID == :3", patientId, accountId, modelId);
ExecuteStoreCommand(String.Format("UPDATE PATIENT_ACCOUNT SET PATIENT_ID = {0} AND ACCOUNT_ID = {1} WHERE ID = {2};", patientId, accountId, modelId));
}

And there accrue next exception:
"ORA-00933: SQL command not properly ended"

P.S. Parameters of the called method is not zero(not null and not object in not empty).

A: CREATE TABLE PATIENT_ACCOUNT
(
    ID         NUMBER
,   PATIENT_ID NUMBER
,   ACCOUNT_ID NUMBER
);

INSERT INTO PATIENT_ACCOUNT VALUES(1, 11, 22);

UPDATE  PATIENT_ACCOUNT
SET     PATIENT_ID = 1
AND     ACCOUNT_ID = 2
WHERE   ID = 3;
-- ORA-00933: SQL command not properly ended

UPDATE  PATIENT_ACCOUNT
SET     PATIENT_ID = 33
,       ACCOUNT_ID = 44
WHERE   ID = 1;
-- 1 rows updated.

A: Additional the semicolon (;) at the end of the statement is incorrect. Even in a "execute immediate" command you have not to use the semicolon.


text:
Q: How to delete empty sub folders from s3 buckets? I'm performing 2 loops in my code. Below is the pseudo code.
get the subfolder list in the bucket
Loop through every subfolders
    loop through every objects in a subfolder
        read the objects
        delete the objects (So at the end the subfolder will be empty)
    get the subfolder list again (asuming the empty subfolder also will be deleted and new subfolders can be created by someone)

But as the result i'm getting an infinite loop since the subfolders are still there in the bucket. So i was finding a solution to delete the subfolder after the deletion of every objects in it. But I couldn't find a solution for this. Please suggest your idea
Below is the s3 folder structure
├── bucket
    └── folder-1
    └── folder-2
    └── folder-3

A: Folders do not actually exist in Amazon S3. Instead, the Key (filename) of each object consists of the full path of the object.
Therefore, you merely need to loop through each object for a given Prefix and delete the objects.
Here's an example in Python:
import boto3

s3_resource = boto3.resource('s3')

for object in s3_resource.Bucket('bucket-name').objects.filter(Prefix='folder-name/'):
    print('Deleting:', object.key)
    object.delete()

This will also delete objects within subfolders, since they have the same Prefix (and folders do not actually exist).


text:
Q: Approximation for Lambert W function near zero I am looking for a good approximation for the $W_0$ branch of the Lambert $W$ function. I am looking for values $0 < x < e$ only, so I expect something simpler than the general Taylor expansion. Thanks.

A: I don't know how simple you need it, and since you never said anything on how accurate you want your approximant to be (i.e., to how many correct decimal places should the approximant match the Lambert function?),
$$W_0(z)\approx\ln(1+z)\frac{1+\frac{123}{40}z+\frac{21}{10}z^2}{1+\frac{143}{40}z+\frac{713}{240}z^2}$$
should be good enough, which has a maximum error of around $1.6\times 10^{-4}$ for $z\in[0,e]$.
The rational portion here is a Padé approximant; probably one might do better with a minimax rational approximation, but I don't have the patience and inclination to derive it since your question's rather vague to begin with.


text:
Q: How can I install Laidout in Ubuntu 16.04? How can I install Laidout, the desktop publishing software, in Ubuntu 16.04?

A: How to install Laidout in Ubuntu 16.04 (Source)
If you are unaware of what the terminal is, please see this question first:
What is a terminal and how do I open and use it?
1. Install dependencies
Open up the terminal and type this command to install Laidout dependencies.
sudo apt install g++ pkg-config libpng-dev libgegl-dev libreadline-dev libx11-dev libxext-dev libxi-dev libxft-dev libcups2-dev libimlib2-dev libfontconfig-dev libfreetype6-dev libssl-dev xutils-dev libcairo2-dev libharfbuzz-dev libsqlite3-dev libgraphicsmagick++1-dev zlib1g-dev mesa-common-dev libglu1-mesa-dev libftgl-dev

2. Download and extract Laidout
Download Laidout from Github as a compressed file and save it in your desktop.
Using your terminal go to your desktop, extract it there and then enter into the Laidout folder. Run these commands one at a time.
cd ~/Desktop
tar xvfj laidout-0.097.tar.bz2
cd laidout-0.097/

3. Install Laidout
Make sure you are in the Laidout folder in the terminal and then run these commands one at a time:
./configure --prefix=/usr/local
sudo make
sudo make install

4. Open Laidout
If the above steps produce no error, we can now open Laidout by typing in the terminal:
laidout

This should open a Laidout window where you can create new documents or open existing ones. The screenshot below I have opened one of the example files, monkey.doc

5. Uninstall
If somehow you want to uninstall Laidout from your system, follow these steps.
Enter into your extracted Laidout folder in your desktop, then run this terminal command:
sudo make uninstall


text:
Q: NSOperation for persistent thread I have an external tool (written in perl) that does work through a C++ object interface. The launching and tear-down take time so I'd like to have an NSOperationQueue and 4 NSOperation threads that run throughout the life of my app but only do work when I feed them a file to work on. I can round-robin feed them as every file will take roughly the same amount of work.
How can I best do this, or is this asking too much of NSOperation in a way it was not designed to do.
I have tried a normal NSOperation task for each file and the launch & tear-down of the perl tool slows things down and sometimes hangs (not sure why - but seems related to the launch process happening too quickly in sequence).
I'm looking to launch the perl tool once on each of 4 threads and then keep them around for the life of the app as the perl tool will stay open waiting for commands... but those commands have to come from the thread that were launched from.


text:
Q: selecting only values having difference greater than 0 (no negatives and 0) i've two columns in mysql db table votes : accept and reject
i want to query only the top result after the accept-reject column values
table : votes
=================
 accept | reject
=================
   7    |   9
   5    |   1
   2    |   15
   5    |   1

i want just the positive and top value, here 5-1 = 4
actually, i've lot of other columns along with accept and reject..i just want to ORDER the results by the top value of difference(positive only) and LIMIT it to 1 so that i can get the one row i want..was i clear? :)
how to write query for this?
thanks..

A: Use:
   SELECT t.accept,
          t.reject,
          t.accept - t.reject AS difference
    FROM VOTES t
   WHERE t.accept - t.reject > 0
ORDER BY difference DESC
   LIMIT 1

Alternate using subquery:
SELECT v.accept,
       v.reject
  FROM VOTES v
 WHERE v.accept - v.reject > 0
  JOIN (SELECT MAX(t.accept - t.reject) AS difference
          FROM VOTES t
         WHERE t.accept - t.reject > 0) x ON x.difference = (v.accept - v.reject)

A: SELECT (accept - reject) as top_value FROM table WHERE (accept - reject) > 0

So if you have values like this:
=============================
 accept | reject | top_value
=============================
   5    |   1    |   4
   7    |   9    |  -2
   2    |   15   |  -13
   5    |   5    |   0

the query will select only row 1.

A: I'm assuming those two columns are just an extract from your table, and you want the entire row where (accept-reject) is maximum. Then you can do it like this:
SELECT * FROM votes
WHERE accept-reject = (SELECT MAX(accept-reject) FROM votes)
LIMIT 1


text:
Q: "User is not enrolled in Duo Security" after adding a security key I succesfully added a YubiKey to Snowflake MFA:

Next time I try to login I immediately get following "User is not enrolled in Duo Security. Contact your local system administrator." error:

After inputting my username and password, I expect the site to ask me to touch my YubiKey. Instead I immediately get the error described above.
How can I setup Snowflake MFA using a YubiKey security key?
Our local admin disabled my MFA and I repeated the steps and I got the same result.

A: Unfortunately this is not available on Snowflake side as of now.
I do agree there is a bit of confusion the fact that you are allowed to enroll with Yubikey but then fail to authenticate.
We do have an internal improvement request pending for this feature. I don't know a timeline yet but you can reach out to your Snowflake representative if you need more information.

A: Functionality might not be available with Snowflake, you can always enable Single Sign-on with your Identity provider and enable the yubi on the IDP end.

A: Snowflake has removed that "Security Key" option for all regions to avoid this problem. That option for Snowflake MFA is not supported at the moment