text:
Q: SCCM deployment of Office 2019 Standard (KMS activation) I have been looking everywhere for an answer to this and so far all searches have come up short with irrelevant information for this scenario.
I need to deploy Office 2019 Standard through SCCM into an environment with no internet access. I have read this cannot be done post-2010, but we already have builds that defy this information for Office 2013.
I have made a build using ODT and it fails during install, presumably because although it predownloads 2.6 Gb or so of data, it still needs the internet during the install for god-only-knows why.
I also have the full ISO for 2019 Standard, have extracted it and followed the instructions to run the "Office Customization Tool" by running setup.exe /Admin
This just installs Office, so that too is useless.
Does anyone know how I can actually deploy this in my environment? There must be a way.

A: Please check whether you have added the "source path" attribute in configuration file (.xml). This attribute defines the location (Such as a shard folder) of the Office installation files both for download mode and configure mode of ODT.
To deploy Office 2019 from a local source, you need to run ODT to download the instalation content first. There would be an Office folder created automatically.
Then you may install Office 2019 on clients using the installation content which is specified on configuration file.


text:
Q: Can't erase folder
sudo rm -rf

Doesn't work: rm: .../abc: Directory not empty which is.
~/Desktop/abc $ ls -anw
total 0
drwxr-xrwx   3 501  20   96 Nov  4 20:30 .
drwx------+ 11 501  20  352 Nov 11 23:34 ..

~/Desktop $ lsof | grep .../Desktop/abc

shows nothing
I've restarted my mac, but it continues. If I throw it to trash it says cannot be emptied because files are being used... I don't know what else I can do.
I've tried to move the file to an external card (and then format) but it says the file cannot be moved...
macOS Mojave 10.14.1

redpajama_set_name: RedPajamaStackExchange


text:
Q: PIP installing module gives warning but installs module I just installed pip and a module. The module installed correctly but it gives the following error.
WARNING: Ignoring invalid distribution -ip (d:\python 3.8\lib\site-packages)

I mean to ask if this is bad or should I ignore it.
[1]: https://i.stack.imgur.com/a6v5Y.png


text:
Q: display one ul list in blocks It is possible to display on screen 'ul' list like this?:

 a

 f

 k

 b

 g

 k

 c

 h

 l

 d

 i

 m

 e

 j

 n

I need to be everything in one ul  and li in blocks (for example 5 elements).

A: ul {width: 120px;}
li {margin: 0; padding:0; float: left; width: 40px;}

A: try looking into display: table-cell. I'm almost certain its what you want.
CSS-Tricks Display Property

A: You can do this with column-count CSS3
Try
ul {

    -webkit-column-count: 3;
       -moz-column-count: 3;
            column-count: 3; /*3 in those rules is just placeholder -- can be anything*/
}

SEE DEMO

A: You use CSS3 multi-column layouts. Apply following style to the UL:
UL {
    column-count:3;
    -moz-column-count:3;
    -webkit-column-count:3;
}

(you may need to rearrange your LI as needed)
Demo: http://jsfiddle.net/2N7rB/


text:
Q: Def function not working for last elif statement I am trying to write a grade calculator based on class rank, both functions work up until the last elif statement that would classify the grade input as an 'A', any ideas on what's wrong?
def undergradg(rank,score):
    if rank=='U' and score>='52' and score<='63':
            return ('D')
    elif rank=='U' and score>='64' and score<='75':
            return ('C')
    elif rank=='U' and score>='76' and score<='87':
            return ('B')
    elif rank=='U' and score>='88' and score<='100':
            return ('A')

def gradgrades(rank,score):
    if rank=='G' and score>='60' and score<='69':
            return ('D')
    elif rank=='G' and score>='70' and score<='79':
            return ('C')
    elif rank=='G' and score>='80' and score<='89':
            return ('B')
    elif rank=='G' and score>='90' and score<='100':
            return ('A')


text:
Q: Javascript processing functions simultaneously? Since I'm not very experienced with regard to Javascript, I'm kinda baffled about the function order.
In the following example I'd expect console.log() to be processed AFTER wait() is finished.
function wait() {
    setTimeout(function () {
        console.log("wait " + new Date().getTime());
    }, 3000);
}

wait();

console.log("global " + new Date().getTime());

The console shows those values:

global 1499993535591  wait 1499993538592

Why is the second function being processed before the first one isn't even completed?
This is causing me some problems when I fill an array inside a function and need to do something with it outside of that function, because it's still empty then.

A: setTimeout is async, it doesn't wait before executing the next line but instead will execute the code when the delay you've set is done.

A: setTimeout is non-blocking - whatever you do, don't just "use async: false", unless you want the user experience to involve just "freezing up" while they wait. Instead learn how to work with async patterns (link credit SLaks)


text:
Q: How can I optimize these Postgres queries and DB performance? I need some help in optimizing the following two queries which are almost similar but data selection is a little different. Here is my table definition
CREATE TABLE public.rates (
  rate_id          bigserial NOT NULL PRIMARY KEY,
  prefix           varchar(50),
  rate_name        varchar(30),
  rate             numeric(8,6),
  intrastate_cost  numeric(8,6),
  interstate_cost  numeric(8,6),
  status           char(3) DEFAULT 'act'::bpchar,
  min_duration     integer,
  call_increment   integer,
  connection_cost  numeric(8,6),
  rate_type        varchar(3) DEFAULT 'lcr'::character varying,
  owner_type       varchar(10),
  start_date       timestamp WITHOUT TIME ZONE,
  end_date         timestamp WITHOUT TIME ZONE,
  rev              integer,
  ratecard_id      integer,
  /* Keys */
  CONSTRAINT rates_pkey
    PRIMARY KEY (id)
) WITH (
    OIDS = FALSE
  );

and two queries here I am using,
SELECT
    rates.* ,
    rc.ratecard_prefix ,
    rc.default_lrn ,
    rc.lrn_lookup_method ,
    customers.customer_id ,
    customers.balance ,
    customers.channels AS customer_channels ,
    customers.cps      AS customer_cps ,
    customers.balance  AS customer_balance
FROM
    rates
        JOIN ratecards rc
        ON rc.card_type = 'customer' AND
        rc.ratecard_id = rates.ratecard_id
        JOIN customers
        ON rc.customer_id = customers.customer_id
WHERE
    customers.status = 'act' AND
    rc.status = 'act' AND
    rc.customer_id = 'AB8KA191' AND
    owner_type = 'customer' AND
    '17606109973' LIKE concat (rc.ratecard_prefix, rates.prefix, '%') AND
    rates.status = 'act' AND
    now() BETWEEN rates. start_date AND
    rates.end_date AND
    customers.balance > 0
ORDER BY
    LENGTH(PREFIX) DESC LIMIT 1;

and the second one,
SELECT
    *
FROM
    rates
        JOIN ratecards rc
        ON rc.card_type = 'carrier' AND
        rc.ratecard_id = rates.ratecard_id
        JOIN carriers
        ON rc.carrier_id = carriers.carrier_id
        JOIN carrier_switches cswitch
        ON carriers.carrier_id = cswitch.carrier_id
WHERE
    rates.intrastate_cost < 0.011648 AND
    owner_type = 'carrier' AND
    '16093960411' LIKE concat (rates.prefix, '%') AND
    rates.status = 'act' AND
    carriers.status = 'act' AND
    now() BETWEEN rates.start_date AND
    rates.end_date AND
    rates.intrastate_cost <> -1 AND
    cswitch.enabled = 't' AND
    rates.rate_type = 'lrn' AND
    rates.min_duration >= 6
ORDER BY
    rates.intrastate_cost ASC,
    LENGTH(rates.prefix) DESC,
    cswitch.priority DESC

I created an index on field owner_type (not shown in schema above) but the query performance is not really what is expected. CPU usage becomes too high for the DB server and everything starts to slow down. Explain output for first query is here and the second one is here.
When the number of records are less in the table, things work fine, naturally, but when the number of records increases the CPU goes higher. I currently have around 341821 records in the table.
How can I improve the query execution or possibly change the query in order to speed things up?
I have set enable_bitmapscan = off because I think this gives me better performance. If set to on, every index scan is followed up with a Bitmap heap scan.
Things did ease up a little bit by changing the query to
SELECT
    rates.*,
    rc.ratecard_prefix,
    rc.default_lrn,
    rc.lrn_lookup_method,
    customers.customer_id,
    customers.balance,
    customers.channels AS customer_channels,
    customers.cps      AS customer_cps,
    customers.balance  AS customer_balance
FROM
    rates
        JOIN ratecards rc
        ON rc.card_type = 'customer' AND
        rc.ratecard_id = rates.ratecard_id
        JOIN customers
        ON rc.customer_id = customers.customer_id
WHERE
    customers.status = 'act' AND
    rc.status = 'act' AND
    rc.customer_id = 'AB8KA191' AND
    owner_type = 'customer' AND
    (CONCAT (rc.ratecard_prefix, rates.prefix) IN ('16026813306',
    '1602681330',
    '160268133',
    '16026813',
    '1602681',
    '160268',
    '16026',
    '1602',
    '160',
    '16',
    '1')) AND
    rates.status = 'act' AND
    now() BETWEEN rates.start_date AND
    rates.end_date AND
    customers.balance > 0
ORDER BY
    LENGTH(PREFIX) DESC LIMIT 1

Postgres.conf is here
But still each Postgres process takes around 25%+ CPU. I now also using pgbouncer to utilize connection pooling but still not helping.


text:
Q: How to Aggregate Data from a Subquery that Requires a Filter? Sorry if the title is confusing, I'll try to explain. I have a query that needs to have a couple of aggregate fields, but I don't know how to write one of them. Here's the current script:
DECLARE @Date DATETIME;
DECLARE @FromDate VARCHAR(25);
DECLARE @ToDate VARCHAR(25);

SET     @Date = GETDATE();
SET     @FromDate = CONVERT(VARCHAR(25), DATEADD(dd, -(DAY(@Date) - 1), @Date),101);
SET     @ToDate = CONVERT(VARCHAR(25), DATEADD(dd, -(DAY(DATEADD(mm, 1, @Date))), DATEADD(mm,1,@Date)), 101);

SELECT  DISTINCT    [A].[Name],
                    COUNT([O].[Id]) AS [OpportunityCount],
                    (CASE WHEN (SUM([O].[Amount]) IS NULL) THEN 0.00 ELSE SUM([O].[Amount]) END) AS [OpportunityTotalAmounts]
                    --(SELECT COUNT(1) FROM [Opportunity] AS [O1] WHERE ([O1].[Id] = [O].[Id]) AND ([O1].[StageName] != 'Not Sold'))
FROM                [Account] AS [A]
                    JOIN [RecordType] AS [RT] ON ([A].[RecordTypeId] = [RT].[Id])
                    JOIN [Contact] AS [C] ON ([A].[Id] = [C].[AccountId])
                    JOIN [OpportunityContactRole] AS [OCR] ON ([C].[Id] = [OCR].[ContactId])
                    LEFT OUTER JOIN [Opportunity] AS [O] ON ([OCR].[OpportunityId] = [O].[Id])
WHERE               ([RT].[Name] = 'PHX')
                    AND ([A].[TypeMS__c] != 'Customer')
                    AND ([O].[CreatedDate] BETWEEN @FromDate AND @ToDate)
GROUP BY            [A].[Name];

You'll notice a commented out line. On that line I want to get a count of all Opportunities that are not marked as 'Not Sold'. It works if I add [O].[Id] to the GROUP BY, but then the result set expands because the grouping gets messed up.
How can I get the count I want?
Thanks in advance!

A: DECLARE @Date DATETIME;
DECLARE @FromDate VARCHAR(25);
DECLARE @ToDate VARCHAR(25);

SET     @Date = GETDATE();
SET     @FromDate = CONVERT(VARCHAR(25), DATEADD(dd, -(DAY(@Date) - 1), @Date),101);
SET     @ToDate = CONVERT(VARCHAR(25), DATEADD(dd, -(DAY(DATEADD(mm, 1, @Date))), DATEADD(mm,1,@Date)), 101);

SELECT  DISTINCT    [A].[Name],
                    COUNT([O].[Id]) AS [OpportunityCount],
                    (CASE WHEN (SUM([O].[Amount]) IS NULL) THEN 0.00 ELSE SUM([O].[Amount]) END) AS [OpportunityTotalAmounts],
                    SUM(CASE WHEN [O].[StageName] != 'Not Sold' THEN 1 ELSE 0 END)
FROM                [Account] AS [A]
                    JOIN [RecordType] AS [RT] ON ([A].[RecordTypeId] = [RT].[Id])
                    JOIN [Contact] AS [C] ON ([A].[Id] = [C].[AccountId])
                    JOIN [OpportunityContactRole] AS [OCR] ON ([C].[Id] = [OCR].[ContactId])
                    LEFT OUTER JOIN [Opportunity] AS [O] ON ([OCR].[OpportunityId] = [O].[Id])
WHERE               ([RT].[Name] = 'PHX')
                    AND ([A].[TypeMS__c] != 'Customer')
                    AND ([O].[CreatedDate] BETWEEN @FromDate AND @ToDate)
GROUP BY            [A].[Name];

This is the trick, you already defined a join so you just need to Sum the StageName  differents from Not Sold using a CASE statement
 SUM(CASE WHEN [O].[StageName] != 'Not Sold' THEN 1 ELSE 0 END)


text:
Q: Bool issue - changing value Morning all.
I have the following method that I use to to try and bring back a bool:
public static bool GetShowCatSubProdStatus(string memberid, string username)
    {
        MyEnts showcatsubprodstatus = new MyEnts.PDC_VDSOREntities35();

        var r = from p in showcatsubprodstatus.tblKeyAccountInfoes
                where p.MemberID == memberid && p.UserName == username
                select p.ShowCatSubProd;

        return r.Any();
    }

When I call this method and debug it, the result is correct. However, when I run this method in a page load, although the method result returns the correct result, when I step through, the boolean value changes!
 bool showcatsubprodstatus = MyEnts.GetShowCatSubProdStatus(_memberid, _username);

        if (showcatsubprodstatus != true)
        {
            panCatSubProd.Visible = false;
        }

Can someone explain what is going on here and how I can solve this puzzler?!
PS: Apologies for being thick.
EDIT - Right, narrowed it down to the variable. It is always return 'true' regardless of the method result?!?!

A: This piece of code returns an IEnumerable<bool> :
var r = from p in showcatsubprodstatus.tblKeyAccountInfoes
        where p.MemberID == memberid && p.UserName == username
        select p.ShowCatSubProd;

By calling the .Any() you are asking it if there are any items in the IEnumerable. If there are you return true;
That is why you always get true back, because it always finds something.
The solution
Either you go for calling .SingleOrDefault() which returns the only element there is (if there is one) or returns the default value of that type.
var r = from p in showcatsubprodstatus.tblKeyAccountInfoes
        where p.MemberID == memberid && p.UserName == username
        select p.ShowCatSubProd;
return r.SingleOrDefault(); //assuming p.ShowCatSubProd is a bool and not a Nullable<bool> else you need to adjust your return type or cast it to a boolean using .GetValueOrDefault().


text:
Q: Json iteration Javascript I have a json string
{"email" : "Hello", "username" : "Not taken"}
how do I iterate through this json to display the text (Like Hello)
I want to display the following text
Email : Hello
Username : Not taken
I tried the following:
    arr = json
    $.each(arr, function(k, v) {
      message += k + ':' + v + '
';
    });

A: You need to change the JSON string to a Javascript object. Use JSON.parse().
Demo:
Output:

Script:
var json = '{"email" : "Hello", "username" : "Not taken"}',
    arr = window.JSON.parse( json ),
    message = '';

$.each(arr, function(k, v) {
    message += k + ': ' + v + '
';
});

document.getElementById( 'message' ).innerHTML = message;

HTML:


text:
Q: cordova SMS plugin -- javascript error I am using cordova 3.6.3.
I am using following SMS plugin.
http://plugins.cordova.io/#/package/com.rjfun.cordova.sms
https://github.com/floatinghotpot/cordova-plugin-sms/tree/master/docs
I have added plugin in following way :--
cordova plugin add com.rjfun.cordova.sms
My cordova app when loaded calls the following function doc_onload().
<body onload="doc_onload()">

Then this register the handler for "deviceready". When the device is ready this device ready function is called.
Now the problem inside the  initApp() handler is that SMS plugin check does not display any alert message.
I am able to get the alert --> "kk" .
But in the following check  if (! SMS ) I did not get any display message.  Neither if nor else got satisfied.
Even alert("end");  Does not get displayed  inside initApp() event handler.
Please suggest why it is failing ?
function initApp()
{
    alert("initApp");
    // attach Fastclick handler
    FastClick.attach(document.body);

    alert("kk");

    if (! SMS )
    {
        alert( 'SMS plugin not ready' );
        return;
    }
    else
    {
        alert( 'SMS plugin Ok ' );
    }

    alert("end");

    //add SMS arrive listner handler
    document.addEventListener("onSMSArrive", processSMS(), false);

}

//function doc_onload(page_type)
function doc_onload()
{

   // Do some task
    alert("doc_onload");

    // add event handler for deviceready function
    document.addEventListener("deviceready", initApp(), false);

}

A: remove the brackets from 'initApp()' in
document.addEventListener("deviceready", initApp, false);
EDIT ** The above is just for semantics
I think you need to change !SMS to
typeof SMS === 'undefined'


text:
Q: Ubuntu 18.04 liblapack.so.3gf not found I am trying to use the old photogrammetry software Phython Photogrammetry Toolbox. However, during the PMVS step I get an error message in the terminal saying that the program cannot find the library liblapack.so.3gf. I got some other missing libraries which I could successfully solve by installing the corresponding packages.
liblapack3 and libblas3 are installed (as suggesting in this similar case: liblapack.so.3gf not found). They, however, do not seem to include the liblapack.so.3gf anymore as I could not locate the file anywhere and I still get the error message.

A: The only place that I could find liblapack.so.3gf is "revolution-mkl" package from multiverse category.
Make sure multiverse repository is enabled then install it:
sudo apt install revolution-mkl

To enable multiverse (if it's not): How do I enable the "multiverse" repository?


text:
Q: Parsing radio button values from form to GA on button SUBMIT I have a form that I'm able to capture user selection from radio buttons that I have on the form as well as being able to capture what selected they make in a drop-down element. But the thing is I've only been able to capture these as events using .blur()
I need to be able to push this data to GA when the user clicks submit (which takes them to another step in the form).
I currently have this:
<script>
(function($) {
$(document).ready(function() {
    $(':input[name=HasPreviousHealthFund]').blur(function () {
        if($(this).val().length > 0) {
            _gaq.push(['_trackEvent', 'Existing Health Insurance', 'completed', $(this).attr('value')]);
        }
        else {
            _gaq.push(['_trackEvent', 'Existing Health Insurance', 'skipped', $(this).attr('value')]);
        }
    });
});
})(jQuery);
</script>

This is showing events for each click on a radio button but I'm not sure how to trigger those events only on submission of the button.
I appreciate any help.

A: Put your event handler on the submit event of the form, not on the buttons. It can then check which button is checked and perform the appropriate GA action.
$("form").submit(function() {
    var buttonValue = $(":input[name=HasPreviousHealthFund]:checked").val();
    var status = buttonValue.length > 0 ? 'completed' : 'skipped';
    _gaq.push(['_trackEvent', 'Existing Health Insurance', status, buttonValue]);
});


text:
Q: Problem parsing Alexa json response in python to get value name I have the following intent passed to my handler:
"request": {
    "type": "IntentRequest",
    "requestId": "amzn1.echo-api.request.3af5c8c3-1d1f-4169-8ce8-fde1a99a7c8d",
    "timestamp": "2019-04-03T04:08:06Z",
    "locale": "en-US",
    "intent": {
        "name": "get_speeds",
        "confirmationStatus": "NONE",
        "slots": {
            "direction": {
                "name": "direction",
                "value": "inbound",
                "resolutions": {
                    "resolutionsPerAuthority": [
                        {
                            "authority": "amzn1.er-authority.echo-sdk.amzn1.ask.skill.e76bf13b-71ac-4a90-94d4-597aa597ae87.direction",
                            "status": {
                                "code": "ER_SUCCESS_MATCH"
                            },
                            "values": [
                                {
                                    "value": {
                                        "name": "inbound",
                                        "id": "a8e6fe5b9e68f30a146cefebaa7edcc3"
                                    }
                                }
                            ]
                        }
                    ]
                },
                "confirmationStatus": "NONE",
                "source": "USER"
            }
        }
    },
    "dialogState": "COMPLETED"
}

I want to extract the actual value, not the utterance, e.g., the value name, in this case, "inbound". I've tried this and various similar iterations (the prints are for debugging):
    slots = handler_input.request_envelope.request.intent.slots
    resolutions = slots["direction"].resolutions
    print(resolutions)
    print(resolutions["resolutions_per_authority"])
    direction = resolutions["resolutions_per_authority"][0]["values"][0]["value"]["name"]
    session_attr = handler_input.attributes_manager.session_attributes

I've also tried the same with "resolutionsPerAuthority" which is the JSON that is passed, but apparently not what comes out to my program, as the log has:
04:08:07
{'resolutions_per_authority': [{'authority': 'amzn1.er-authority.echo-sdk.amzn1.ask.skill.e76bf13b-71ac-4a90-94d4-597aa597ae87.direction',

04:08:07
'status': {'code': 'ER_SUCCESS_MATCH'},

04:08:07
'values': [{'value': {'id': 'a8e6fe5b9e68f30a146cefebaa7edcc3',

04:08:07
'name': 'inbound'}}]}]}

04:08:07
'Resolutions' object is not subscriptable

This is the error I keep getting with all my approaches: 'Resolutions' object is not subscriptable. Can someone help me with how to extract the canonical slot values? I need to do the same thing for several other intents, but I figure if I can get this one working, it will be a model for the others.

A: As you already pointed out, your problem was that you treated the resolution object as it was subscriptable, accessing it via
resolutions.resolutions_per_authority[0].values[0].value

is the right way to obtain it.
It may be helpful to point out that, in case of multiple matches, Alexa will return the resolutions in the order of the most likely to match the user intent.
This code snippet iterates the slots and return a python dictionary with just the keys to know if it was validated and the id of the matched value:
from ask_sdk_model.slu.entityresolution import StatusCode

@staticmethod
def get_slot_values(filled_slots):
    """Return slot values with additional info."""
    slot_values = {}
    logger.info("Filled slots: {}".format(filled_slots).replace("\n", "\r"))

    for key, slot_item in six.iteritems(filled_slots):
        name = slot_item.name
        try:
            status_code = slot_item.resolutions.resolutions_per_authority[0].status.code

            if status_code == StatusCode.ER_SUCCESS_MATCH:
                slot_values[name] = {
                    "synonym": slot_item.value,
                    "resolved": slot_item.resolutions.resolutions_per_authority[0].values[0].value.__dict__,  # to make it JSON serializable
                    "is_validated": True,
                }
            elif status_code == StatusCode.ER_SUCCESS_NO_MATCH:
                slot_values[name] = {
                    "synonym": slot_item.value,
                    "resolved": slot_item.value,
                    "is_validated": False,
                }
            else:
                pass
        except (AttributeError, ValueError, KeyError, IndexError, TypeError) as e:
            # for BUILT-IN intents, there are no resolutions, but the value is specified
            if slot_item.value is not None and slot_item.value != 'NONE':
                slot_values[name] = {
                    "synonym": slot_item.value,
                    "resolved": slot_item.value,
                    "is_validated": True,
                }
            else:
                logger.info("SLOT {} UNRESOLVED".format(name))
                slot_values[name] = {
                    "synonym": slot_item.value,
                    "resolved": slot_item.value,
                    "is_validated": False,
                }
    return slot_values

where filled_slots = handler_input.request_envelope.request.intent.slots

A: OK, I finally located a python example that uses the object-oriented version of the relatively new SDK, as I am. The example is the python version of Amazon's PetMatch example.
Based on that, the following is working:
slots = handler_input.request_envelope.request.intent.slots
direction = slots["direction"].resolutions.resolutions_per_authority[0].values[0].value.name

I'm still looking to understand better HOW it works, but at least it's working, and may also help someone else. I find that with Alexa examples and documentation, there is a ton out there, but it's not well organized and the api keeps changing, so some of what you find turns out to be obsolete.


text:
Q: WPF Datagrid tabbing adds row but loses focus So I have a WPF datagrid, and it has 2 columns (Name and Quantity) and I want to enter the following:
Name       Quantity
Apples       2
Bananas       3
Watermelon     1
So I go to the first cell, type 'Apples' hit TAB, which takes me to the second column in edit mode, so I type '2', hit TAB. Notice that TAB adds a new row but takes the focus away from the datagrid.
Instead I want TAB to go to the second row in Edit Mode so I can type 'Bananas' on the first column right away. And I can just hit TAB and keep typing and add more items.
I've tried every possible way I can find to make this happen but no luck so far... Anybody willing to help me THANKS a lot!

A: you can see below answer for your reference as it is showing same scenarion.
DataGrid select last cell programatically


text:
Q: Find specific data-availability class I have the following webpage source:

     FREE delivery

I want to print "Free delivery" to the screen if data-availability == homeDelivery.
I tried with the below code but I get no match.
result = soup.find_all("option", {"data-availability": 'homeDelivery'})
print(result)

ANy ideas? Thank you!

A: You should be looking for
 tag not option.
Try this:
from bs4 import BeautifulSoup

sample = """

     FREE delivery

"""

result = BeautifulSoup(sample, "html.parser").find_all("li", {"data-availability": 'homeDelivery'})
print([i.getText(strip=True) for i in result])

Output:
['FREE delivery']


text:
Q: PHP - help appending to textarea values I currently have the example below working to take each value from a textarea, and split it as follows name1 name2 name3 and so forth.  I would like to append a single quote on each side of the values, followed by a comma like this 'name1', 'name2', 'name3'.  Finally I'd like to put all of this into a single $string value that I can reference later.  Any suggestions on how to accomplish this would be appreciated.
<?php

//trim off excess whitespace off the whole
$text = trim($_POST['ServerName']);

//explode all separate lines into an array
$textAr = explode("\n", $text);

//trim all lines contained in the array.
$textAr = array_filter($textAr, 'trim');

//loop through the lines
foreach($textAr as $line){
echo "$line";

}

?>

A: *

*Add quotes: foreach ($textAr as $k=>$v) { $textAr[$k] = "'".$v."'"; }

*Concat: `$text = implode(", ", $textAr);

A: @jason-000 Thanks for your help I was able to figure out what you meant after doing some more research.  I removed the foreach loop and was able to get it to output the way I wanted as follows -
$text = trim($_POST['ServerName']);
$textAr = explode("\n", $text);
$values = array_values($textAr);
$string = implode("','", $values);
$string = "'".$string."'";
$output = "(".$string.")";

I end up with ('Server1 ','Server2 ','Server3') which is fine.  Not sure why it added the space before the last ' except on the last value.


text:
Q: read Xml file with JAXB I want to read a xml file (like below) but I get an Execption.
    Could you please help me how can I fix this problem?
<?xml version="1.0" encoding="UTF-8"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation=
"file:///C:/Documents%20and%20Settings/mojalal/Desktop/FirstXSD.xml">
<log>
    <property key="firstKey" value="firstValue"></property>
    <property key="secoundKey" value="secoundKey"></property>
    <property key="thirdKey" value="thirdValue"></property>
</log>

<env>
    <property key="firstenv" value="fo"></property>
    <property key="123" value="333"></property>
</env>
</config>

and this is my code that I want to read xml file:
    public class ReadXMLFilewithJAXB {
private static List<Property> customer;

@SuppressWarnings("unchecked")
public static void main(String[] args) {

 try {

    File file = new File("c:\\FirstXML.xml");
    JAXBContext jaxbContext = JAXBContext.newInstance(Log.class);
    Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
    customer = (List<Property>) jaxbUnmarshaller.unmarshal(file);
 } catch (JAXBException e) {
    e.printStackTrace();
  }

}

}
Finally this is the Exception that I get:
javax.xml.bind.UnmarshalException: unexpected element (uri:"", local:"config"). Expected elements are (none)
    at com.sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallingContext.handleEvent(UnmarshallingContext.java:631)
    at com.sun.xml.internal.bind.v2.runtime.unmarshaller.Loader.reportError(Loader.java:236)
    at com.sun.xml.internal.bind.v2.runtime.unmarshaller.Loader.reportError(Loader.java:231)
    at com.sun.xml.internal.bind.v2.runtime.unmarshaller.Loader.reportUnexpectedChildElement(Loader.java:105)
    at com.sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallingContext$DefaultRootLoader.childElement(UnmarshallingContext.java:1038)
    at com.sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallingContext._startElement(UnmarshallingContext.java:467)
    at com.sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallingContext.startElement(UnmarshallingContext.java:448)
    at com.sun.xml.internal.bind.v2.runtime.unmarshaller.SAXConnector.startElement(SAXConnector.java:137)
    at com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser.startElement(AbstractSAXParser.java:501)
    at com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl.scanStartElement(XMLNSDocumentScannerImpl.java:400)
    at com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl$NSContentDriver.scanRootElementHook(XMLNSDocumentScannerImpl.java:626)
    at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl$FragmentContentDriver.next(XMLDocumentFragmentScannerImpl.java:3103)
    at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl$PrologDriver.next(XMLDocumentScannerImpl.java:922)
    at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl.next(XMLDocumentScannerImpl.java:648)
    at com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl.next(XMLNSDocumentScannerImpl.java:140)
    at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanDocument(XMLDocumentFragmentScannerImpl.java:511)
    at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:808)
    at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:737)
    at com.sun.org.apache.xerces.internal.parsers.XMLParser.parse(XMLParser.java:119)
    at com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser.parse(AbstractSAXParser.java:1205)
    at com.sun.org.apache.xerces.internal.jaxp.SAXParserImpl$JAXPSAXParser.parse(SAXParserImpl.java:522)
    at com.sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallerImpl.unmarshal0(UnmarshallerImpl.java:200)
    at com.sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallerImpl.unmarshal(UnmarshallerImpl.java:173)
    at javax.xml.bind.helpers.AbstractUnmarshallerImpl.unmarshal(AbstractUnmarshallerImpl.java:137)
    at javax.xml.bind.helpers.AbstractUnmarshallerImpl.unmarshal(AbstractUnmarshallerImpl.java:142)
    at javax.xml.bind.helpers.AbstractUnmarshallerImpl.unmarshal(AbstractUnmarshallerImpl.java:151)
    at javax.xml.bind.helpers.AbstractUnmarshallerImpl.unmarshal(AbstractUnmarshallerImpl.java:169)
    at firstExample.ReadXMLFilewithJAXB.main(ReadXMLFilewithJAXB.java:21)

Env POJO Class:
public class Env {
    List<Property> properties2;

    public Env() {
    }

    public Env(List<Property> properties2) {
        super();
        this.properties2 = properties2;
    }

    public List<Property> getProperties2() {
        return properties2;
    }

    public void setProperties2(List<Property> properties2) {
        this.properties2 = properties2;
    }

LOg POJO Class:
@XmlRootElement
public class Log {
    List<Property> properties=new ArrayList<Property>();;

    public Log(){

    }

    public List<Property> getProperties() {
        return properties;
    }

    public void setProperties(List<Property> properties) {
        this.properties = properties;
    }

A: javax.xml.bind.UnmarshalException: unexpected element (uri:"", local:"config"). Expected elements are (none)
    at com.sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallingContext.handleEvent(UnmarshallingContext.java:631)

You need to ensure that you associate a class with the root element of the XML document using @XmlRootElement or @XmlElementDecl (see:  http://blog.bdoughan.com/2012/07/jaxb-and-root-elements.html).  Alternatively you can use one of the unmarshal methods that take a Class parameter to tell JAXB what type of object you are unmarshalling.

Domain Model (Config)
I would recommend having a domain class like the following from which you could obtain the two lists of Property objects.
import java.util.*;
import javax.xml.bind.annotation.*;

@XmlRootElement
public class Config {

    private List<Property> logProperties = new ArrayList<Property>();
    private List<Property> envProperties = new ArrayList<Property>();

    @XmlElementWrapper(name="log")
    @XmlElement(name="property")
    public List<Property> getLogProperties() {
        return logProperties;
    }

    @XmlElementWrapper(name="env")
    @XmlElement(name="property")
    public List<Property> getEnvProperties() {
        return envProperties;
    }

}

Demo
import java.io.File;
import javax.xml.bind.*;

public class Demo {

    public static void main(String[] args) throws Exception {
        JAXBContext jc = JAXBContext.newInstance(Config.class);

        Unmarshaller unmarshaller = jc.createUnmarshaller();
        File xml = new File("src/forum17059227/input.xml");
        Config config = (Config) unmarshaller.unmarshal(xml);

        Marshaller marshaller = jc.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.setProperty(Marshaller.JAXB_NO_NAMESPACE_SCHEMA_LOCATION, "file:///C:/Documents%20and%20Settings/mojalal/Desktop/FirstXSD.xml");
        marshaller.marshal(config, System.out);
    }

}

input.xml/Output
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="file:///C:/Documents%20and%20Settings/mojalal/Desktop/FirstXSD.xml">
    <env>
        <property key="firstenv" value="fo"/>
        <property key="123" value="333"/>
    </env>
    <log>
        <property key="firstKey" value="firstValue"/>
        <property key="secoundKey" value="secoundKey"/>
        <property key="thirdKey" value="thirdValue"/>
    </log>
</config>

A: When you describing an XML model, you need to begin with a root entity (in your case it's the<config> element).
@XmlRootElement(name="config")
class Config implements Serializable {
   private Log log;
   private Env env;

   @XmlElement(name="log")
   public Log getLog() {
      return this.log;
   }

   @XmlElement(name="env")
   public Env getEnv() {
      return this.env;
   }

   // Setters are omitted
}

And then you parse the XML like the following:
JAXBContext jaxbContext = JAXBContext.newInstance(Config.class);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
Config config = (Config) jaxbUnmarshaller.unmarshal(file);
if (config != null && config.getLog() != null) {
   customer = config.getLog().getProperties();
}


text:
Q: Minecraft command block logging I had just updated my friend's minecraft server to the beta build of bukkit (1.4.6 R0.1). This restored all of the plugins that weren't available when it was vanilla.
However, the internet (and its users) seem to hate me. Just after resolving most problems, I logged on. I keep on dying and dying and dying continuously. I narrowed the issue down to the Essentials /kill command. I used PluginManager to disable the command, and the dying stopped. Apparently someone put a command block on a clock, with the command set to /kill werdnaminer (me!).
Is there a way to log the triggering of command blocks? I need a way to locate and disable that clock without messing up what contraptions others have created.
EDIT: Looks like it was added in the 1.6 update! YAY! Thanks Mojang! (or was it Spigot or Bukkit?)

EDIT2: Yup, it's Spigot. Boohoo.

A: Only ops are able to program command blocks, so that should narrow the list of suspects. Some (virtual) face time with your ops should reveal the guilty party.
In the meantime, if your map doesn't rely heavily on command blocks, they can be disabled by setting enable-command-block=false in the server.properties file and restarting the server.
To locate the offending block you can render the world map showing just command blocks and redstone, using one of the many 3rd-party cartography tools. (I quite like Minecraft Overviewer for this use, and though it's not technically 1.4.6-up-to-date, it can handle Anvil and custom block IDs so it's still compatible.) This will give you a high-level view of the problem and let you zero in on the possible culprits. Compare it to a regular overworld render to find a recognisable landmark nearby, then fly/tp there, unearth it, and render it inoperable.

A: Command Block dont have the kill command inside.
all other things comes with Mods/Plugins
read this http://www.minecraftwiki.net/wiki/Command_Block and you know what the command block can do.


text:
Q: Unable to Define Auto Scaling for SageMaker Endpoint I have deployed an AWS endpoint using a Docker container (I followed this).
Everything is working perfectly but now I need to put it in production and define an auto scaling strategy.
I tried 2 things:

*

*AWS console but the auto scaling button is greyed
out.

*The method described here. My endpoint name
is EmbeddingEndpoint and my variant name is SimpleVariant. So my
final command is
aws application-autoscaling put-scaling-policy \
--policy-name scalable_policy_for_embedding \
--policy-type TargetTrackingScaling \
--resource-id endpoint/EmbeddingEndpoint/variant/SimpleVariant \
--service-namespace sagemaker \
--scalable-dimension sagemaker:variant:DesiredInstanceCount \
--target-tracking-scaling-policy-configuration file://policy_config.json

but I get this result :
An error occurred (ObjectNotFoundException) when calling the PutScalingPolicy operation:
No scalable target registered for service namespace: sagemaker, resource ID:
endpoint/EmbeddingEndpoint/variant/SimpleVariant, scalable dimension:
sagemaker:variant:DesiredInstanceCount

Does someone have another solution, or is it that I didn't set the variable well ?
Thank you in advance !

A: Your sagemaker service-namespace does not have any registered scaling targets. You need to first run register-scalable-target before running put-scaling-policy.
aws application-autoscaling register-scalable-target \
    --service-namespace sagemaker \
    --scalable-dimension sagemaker:variant:DesiredInstanceCount \
    --resource-id endpoint/EmbeddingEndpoint/variant/SimpleVariant


text:
Q: binary search tree by smart pointers I used row pointers to implement the binary search tree data structure and it worked perfectly, but when I replaced the row pointers with shared_ptr it compiles successfully but the program crashes due to unknown run-time error. Could you please help in this?
#include<iostream>
#include<memory>
class node{
public:
int data;
std::shared_ptr<node>left = std::make_shared<node>();
std::shared_ptr<node>right = std::make_shared<node>();
};

std::shared_ptr<node>CreateNode(int x);
void print_tree(const std::shared_ptr<node>&x);

int main(){
    auto root = std::make_shared<node>();
    root = CreateNode(12);
    root->left = CreateNode(9);
    root->right = CreateNode(14);
    root->left->right = CreateNode(10);
    root->left->right = CreateNode(11);
    print_tree(root);
    return 0;
}

std::shared_ptr<node>CreateNode(int x){
    std::shared_ptr<node>NewNode = std::make_shared<node>();
    NewNode->data = x;
    NewNode->left = NewNode->right = nullptr;
    return NewNode;
}

void print_tree(const std::shared_ptr<node>&x){
    if(x==nullptr) return;
    std::cout<<x->data<<std::endl;
    print_tree(x->left);
    print_tree(x->right);
}

A: #include<iostream>
#include<memory>

class node
{
public:
    int data;
    std::shared_ptr<node>left;
    std::shared_ptr<node>right;
};

std::shared_ptr<node>CreateNode(int x);
void print_tree(const std::shared_ptr<node>&x);

int main()
{
    auto root = CreateNode(12);
    root->left = CreateNode(9);
    root->right = CreateNode(14);
    root->left->right = CreateNode(10);
    root->left->right = CreateNode(11);
    print_tree(root);
    return 0;
}

std::shared_ptr<node>CreateNode(int x)
{
    std::shared_ptr<node>NewNode = std::make_shared<node>();
    NewNode->data = x;
    NewNode->left = NewNode->right = nullptr;
    return NewNode;
}

void print_tree(const std::shared_ptr<node>&x)
{
    if(x==nullptr) return;
    std::cout<<x->data<<std::endl;
    print_tree(x->left);
    print_tree(x->right);
}

This works on my machine. I made left and right pointers in node class initially equal to nullptr, instead of creating new node because you can't know is it going to be used. And root to be initialized by result of CreateNode function.


text:
Q: How to add inner border to bootstrap 3 nav-tabs with transparent background? I can't figure out how to hide .tab-pane's overlapping border. I tried clipping it but it still is visible.
Does anyone know of any jQuery plugins that can hide the bottom border?
Please see fiddle at the bottom.

HTML

                SIGN UP

SIGN
                IN

CSS
body {
  background: #155C91;
  -webkit-background-size: cover;
  -moz-background-size: cover;
  -o-background-size: cover;
  background-size: cover;
  padding-top: 88px;
  padding-bottom: 20px;
}
.tab-forms .nav-tabs {
  border-bottom: 0;
}
.tab-forms .nav-tabs li.active a {
  background: rgba(255, 255, 255, 0.2);
  border: 1px solid rgba(255, 255, 255, 0);
  border-bottom: 0;
  margin-bottom: 1px;
  -webkit-clip-path: polygon(0px 0px, 144px 0px, 144px 81px, 0px 81px);
  /*Chrome,Safari*/
  /*Firefox*/
}
.tab-forms .nav-tabs li.active a:before {
  content: "";
  width: 90%;
  height: 55px;
  top: 8px;
  left: 5%;
  position: absolute;
  border: 1px solid #fff;
}
.tab-forms .nav-tabs li.active a:after {
  border-bottom: 1px solid #fff;
  content: "";
  width: 127px;
  height: 55px;
  top: 8px;
  left: 7px;
  position: absolute;
}
.tab-forms .nav-tabs li a {
  margin-right: 0;
  -webkit-border-radius: 0;
  -moz-border-radius: 0;
  border-radius: 0;
  background: rgba(255, 255, 255, 0.1);
  width: 144px;
  text-align: center;
  font-size: 18pt;
}
.tab-forms .nav-tabs li a:before {
  content: "";
  width: 80%;
  height: 25px;
  top: 8px;
  left: 11%;
  position: absolute;
  border: 1px solid #fff;
}
.tab-forms .tab-content {
  padding: 8px;
  min-height: 100px;
  background: rgba(255, 255, 255, 0.2);
}
.tab-forms .tab-content .tab-pane {
  border: 1px solid #ffff00;
  min-height: 100px;
}
rect {
  fill: red;
}

http://jsfiddle.net/52VtD/12901/
https://jsfiddle.net/52VtD/12908/

A: Remove border-bottom property from .tab-forms .nav-tabs li.active a:after and set border-bottom:none; for .tab-forms .nav-tabs li.active a:before


text:
Q: Allow moderators to fine-tune the effects of a lock Current Situation
When a moderator locks a question or answer, they can choose between different types of post notices: content dispute, off-topic comments, historical significance, wiki answer, or no notice.
The notice in turn affects the effect of the lock, but that it works this way is not clear to moderators and it is also not clear what effect a given notice has.
The only way to find out for sure is to ask somebody who is not a moderator or use a sock.
(This is due to moderator powers possibly overriding the effect of locks.)
Feature Request
Store the effects of a lock separately independent of the post notice.
In the interface for locking a post, provide moderators with a checklist regarding the effects of the lock, for example:

This lock prevents:

*

*answers

*votes

*flags

*comments

*edits

For questions, also add an option to apply the same lock to all answers to the question.
For the canned lock reasons, automatically provide an appropriate choice as defaults.
At the very least make it clear in the dialogue what detailed effects a lock has.
Rationale
Post locks are used rarely, but when they are it is often for important reasons such as avoiding a divide of the community, an escalation of events, or similar.
Thus, locks are a tool which moderators have little experience with, but whose correct use (i.e., choosing the right type of effects and knowing what the effects are) may be crucial.
Moreover, many locks are used for special cases with individual needs, which in turn require individual locks.
In a specific example, there is a question on Academia, which lead answers and comments, whose appropriateness for the site is subject to a Meta discussion.
To avoid further potentially inappropriate comments, answers, etc., I wished to lock question for the remainder of the Meta discussion.
I chose content dispute as a lock reason, since it seemed most appropriate notice, however this only prevented edits to the question – which makes sense in other cases but not here.
After I noticed this, I chose a historical lock (which I knew to be affecting everything) and removed the post notice (because it was not appropriate).
The latter action lead to comments on answers being allowed (because that's what a lock without notice does for whatever reason), which was not the desired effect either.
Related Questions

*

*Make locking posts more granular – This seems to be partially addressed: The different locks already do have different effects. However, my request goes further than this.

*Allow moderators to choose a custom reason for locked posts – This is about customising the notice not the effect.

*Can we get a comments only lock? – This would be addressed with this.

A: I won't status-completed this because we've only done a small portion of your request so far, which is to make it clearer in the lock dialog what the lock is actually going to do:

Bit of a wall-o-text at the top, but hopefully it's helpful - and it links out to the help center in case more information is needed.
As for the other bits, we've kicked off some research about what breaking up the locking process might entail. Creating a lock buffet, if you will. No timeline on that but it's being explored; hopefully this helps allay some of the confusion in the meantime.


text:
Q: How to use scan() method from winwifi package I'm new to python development, I would like to scan nearby available networks using python (on windows machine). I found out that using winWifi is an easy way to do it. But winwifi.WinWiFi.scan() returns a list of objects, how can I return the list of available SSIDs from a python file?
thanks

A: If you look at the string output you can see the related class:
<winwifi.main.WiFiAp object at 0x0000016DBB11C5E0>
Which exists in source code here:
https://github.com/changyuheng/winwifi.py/blob/master/src/winwifi/main.py
So use:  obj.ssid  to access the ssid property.


text:
Q: windows phone WebClient doesn't work WebClient client = new WebClient();

When I try do to something like that I get an error

Error 2   The type or namespace name 'WebClient' does not exist in the namespace 'System.Net' (are you missing an assembly reference?)

What's wrong?

A: It is available in WP8 Silverlight projects. I prefer to use Windows.Web.Http.HttpClient instead.
public async Task<String> myFunction(){
    HttpClient httpClient = new HttpClient();
    String response = await httpClient.GetStringAsync(
        new Uri("http://www.example.com")
    );
    return response;
}

To use the function you will again use await.
String data= await myFunction()

and so on...
You might need to install Microsoft HTTP Client Libraries from nuget


text:
Q: Compare variables declared in Snowflake Stored procedure I got a stored procedure as below
CREATE OR REPLACE PROCEDURE SP12
(argument1 VARCHAR,argument2 VARCHAR
)
if (argument1 <> argument2) { return N1 } else { return N2}

The issue is iam getting error while comparing argument1 <> argument2 (need to compare not equal to).
Is this correct method.
Thanks

A: is the the complete code for your Stored Procedure or is it just a snippet? If it is the full code then I suggest that you read the documentation again: CREATE PROCEDURE

*

*You need a RETURNS statement in the header

*How are you declaring/assigning values to N1 and N2?

If these suggestions don't help then please provide the full SP Code (if this is just a snippet) and also the error message you are getting


text:
Q: How to implement AWS autoscaling policies using spinnaker? I am trying to play with spinneker with aws cloud-driver..
I have created a pipeline and can add capacity - Min: 1, Max: 7, Desired: 2
I am wondering how / where to specify autoscaling policies to scale up and scale down the instances based on the metrics..

A: In Spinnaker, scaling policies are configured on an ASG itself, but not in a pipeline. You can configure the scaling policies by clicking on the ASG in the "Clusters" tab, then look under "Scaling Policies" in the details panel on the right.
Once an ASG, e.g. myapp-v000 has some scaling policies, if a pipeline creates a new ASG in the same cluster, e.g. myapp-v001, Spinnaker will create copies of the scaling policies from myapp-v000 and apply them to myapp-v001.


text:
Q: MySQL weird rounding off results I spotted some rounding bug in MySQL. Here is my query:
SELECT /*debugz*/ ROUND((SUM(grade)/2),0) AS grade, SUM(grade) FROM entry.computed_grade a WHERE a.stud_id='7901159' AND a.sy='2014' AND a.term=01 AND a.terms=01 AND a.catalog_no='Christian Life Formation';

and the result is this:
grade  sum(grade)
------  ------------
    92           185

The grade result should be 93, not 92 because 185/2 = 92.5

A: Try to use ceil instead of round.
e.g ceil(1.45) = 2

A: Try this
SELECT CEIL((SUM(grade)/2),0) AS grade, SUM(grade) FROM entry.computed_grade a WHERE ((a.stud_id='7901159') AND (a.sy='2014') AND (a.term=01) AND (a.terms=01) AND (a.catalog_no='Christian Life Formation'));

A: You should check rounding behavior artickle for mysql. I believe here is the reason of your problem:

For approximate-value numbers, the result depends on the C library. On
  many systems, this means that ROUND() uses the "round to nearest even"
  rule: A value with any fractional part is rounded to the nearest even
  integer.

By the way it's IEEE standard for float point rounding, so you might want stay with it

A: Do not "patch" this problem by tweaking the query.  Actually fix your database.  If you are not storing the "grade" column as the DECIMAL data type, and are instead using FLOAT or DOUBLE, your design is inherently broken.

Because floating-point values are approximate and not stored as exact values, attempts to treat them as exact in comparisons may lead to problems.
http://dev.mysql.com/doc/refman/5.6/en/floating-point-types.html

This is not a bug in MySQL.  It is an inherent limitation in industry-standard floating point number storage.  Use DECIMAL columns to store meaningful, precise numbers, and the other two types only when low storage space or a wide range of allowable values are more important than precision.


text:
Q: Will Go compiled binaries run on Windows NT including the use of Ethernet ports? Yes, Windows NT is still a thing that some people have to deal with.
I wonder if it is possible to run a binary compiled with Go on NT and use the ethernet port for communication (MQTT). If so, what do I have to take care of?
I admit that I have not done a test in this case because I simply don't have Win NT in reach in my current environment.

A: I don't think it will work. I downloaded Caddy, which uses Go, and ran dumpbin on it. I got:
Microsoft (R) COFF/PE Dumper Version 14.00.24210.0
Copyright (C) Microsoft Corporation.  All rights reserved.

Dump of file caddy_windows_amd64.exe

PE signature found

File Type: EXECUTABLE IMAGE

FILE HEADER VALUES
            8664 machine (x64)
...
             223 characteristics
                   Relocations stripped
                   Executable
                   Application can handle large (>2GB) addresses
                   Debug information stripped

OPTIONAL HEADER VALUES
             20B magic # (PE32+)
            3.00 linker version
...
            6.01 operating system version

So the minimum supported version of Windows is NT6 which is Vista.
This seems to be supported by a ticket saying:

Go 1.10 is the last release to support Windows Vista or below

And:

We plan to announce that Go 1.10 will be the last release of Go to support Windows XP.

So old versions of Go supported Windows XP and above. New versions require Vista and above.


text:
Q: Android Studio Kotlin background activiy after app closed How can I do that background activity continue to work after the app closed?
I tried to startService and start Listener activity
MainActivity:
var ser = Intent(this@MainActivity, Listener::class.java)
startService(ser)

Listener.tk:
package com.example.chatapp

import android.app.IntentService
import android.content.Intent
import android.util.Log
import com.google.firebase.database.ChildEventListener
import com.google.firebase.database.DataSnapshot
import com.google.firebase.database.DatabaseError
import com.google.firebase.database.FirebaseDatabase
class Listener : IntentService("Listener") {
    val database = FirebaseDatabase.getInstance()
    var myRef = database.getReference("Messages")
    override fun onHandleIntent(intent: Intent?) {
        Log.d("scrpapa", "1")
        var reff = database.getReference("Messages")
        reff.addChildEventListener(object : ChildEventListener {
            override fun onChildAdded(p0: DataSnapshot, p1: String?) {
                val chattmes = p0.getValue(ChatC::class.java)
                if (chattmes != null) {
                    Log.d("asd", "1")
                }

            }

            override fun onCancelled(p0: DatabaseError) {
            }

            override fun onChildChanged(p0: DataSnapshot, p1: String?) {
            }

            override fun onChildMoved(p0: DataSnapshot, p1: String?) {
            }

            override fun onChildRemoved(p0: DataSnapshot) {
            }
        })
    }
}

A: *

*Service should be foreground or it will be killed

*Also u can use workers


text:
Q: A reproducible example of volatile usage I am look for a reproducible example that can demonstrate how volatile keyword works. I'm looking for something that works "wrong" without variable(s) marked as volatile and works "correctly" with it.
I mean some example that will demonstrate that order of write/read operations during the execution is different from expected when variable is not marked as volatile and is not different when variable is not marked as volatile.
I thought that I got an example but then with help from others I realized that it just was a piece of wrong multithreading code. Why volatile and MemoryBarrier do not prevent operations reordering?
I've also found a link that demonstrates an effect of volatile on the optimizer but it is different from what I'm looking for. It demonstrates that requests to variable marked as volatile will not be optimized out.How to illustrate usage of volatile keyword in C#
Here is where I got so far. This code does not show any signs of read/write operation reordering. I'm looking for one that will show.
    using System;
    using System.Threading;
    using System.Threading.Tasks;
    using System.Runtime.CompilerServices;

    namespace FlipFlop
    {
        class Program
        {
            //Declaring these variables
            static byte a;
            static byte b;

            //Track a number of iteration that it took to detect operation reordering.
            static long iterations = 0;

            static object locker = new object();

            //Indicates that operation reordering is not found yet.
            static volatile bool continueTrying = true;

            //Indicates that Check method should continue.
            static volatile bool continueChecking = true;

            static void Main(string[] args)
            {
                //Restarting test until able to catch reordering.
                while (continueTrying)
                {
                    iterations++;
                    a = 0;
                    b = 0;
                    var checker = new Task(Check);
                    var writter = new Task(Write);
                    lock (locker)
                    {
                        continueChecking = true;
                        checker.Start();

                    }
                    writter.Start();
                    checker.Wait();
                    writter.Wait();
                }
                Console.ReadKey();
            }

            static void Write()
            {
                //Writing is locked until Main will start Check() method.
                lock (locker)
                {
                    WriteInOneDirection();
                    WriteInOtherDirection();

                    //Stops spinning in the Check method.
                    continueChecking = false;
                }
            }

            [MethodImpl(MethodImplOptions.NoInlining)]
            static void WriteInOneDirection(){
                a = 1;
                b = 10;
            }

            [MethodImpl(MethodImplOptions.NoInlining)]
            static void WriteInOtherDirection()
            {
                b = 20;
                a = 2;
            }

            static void Check()
            {
                //Spins until finds operation reordering or stopped by Write method.
                while (continueChecking)
                {
                    int tempA = a;
                    int tempB = b;

                    if (tempB == 10 && tempA == 2)
                    {
                        continueTrying = false;
                        Console.WriteLine("Caught when a = {0} and b = {1}", tempA, tempB);
                        Console.WriteLine("In " + iterations + " iterations.");
                        break;
                    }
                }
            }
        }
    }

Edit:
As I understand an optimization that causes reordering can come from JITer or from hardware itself. I can rephrase my question. Does JITer or x86 CPUs reorder read/write operations AND is there a way to demonstrate it in C# if they do?

A: You can use this example to demonstrate the different behavior with and without volatile. This example must be compiled using a Release build and ran outside of the debugger1. Experiment by adding and removing the volatile keyword to the stop flag.
What happens here is that the read of stop in the while loop is reordered so that it occurs before the loop if volatile is omitted. This prevents the thread from ending even after the main thread set the stop flag to true.
class Program
{
    static bool stop = false;

    public static void Main(string[] args)
    {
        var t = new Thread(() =>
        {
            Console.WriteLine("thread begin");
            bool toggle = false;
            while (!stop)
            {
                toggle = !toggle;
            }
            Console.WriteLine("thread end");
        });
        t.Start();
        Thread.Sleep(1000);
        stop = true;
        Console.WriteLine("stop = true");
        Console.WriteLine("waiting...");

        // The Join call should return almost immediately.
        // With volatile it DOES.
        // Without volatile it does NOT.
        t.Join();
    }
}

It should also be noted that subtle changes to this example can reduce its probability of reproducibility. For example, adding Thread.Sleep (perhaps to simulate thread interleaving) will itself introduce a memory barrier and thus the similar semantics of the volatile keyword. I suspect Console.WriteLine introduces implicit memory barriers or otherwise prevents the jitter from using the instruction reordering operation. Just keep that in mind if you start messing with the example too much.

1I believe that framework version prior to 2.0 do not include this reordering optimization. That means you should be able to reproduce this behavior with version 2.0 and higher, but not the earlier versions.

A: The exact semantics of volatile is a jitter implementation detail.  The compiler emits the Opcodes.Volatile IL instruction where ever you access a variable that's declared volatile.  It does some checking to verify that the variable type is legal, you can't declare value types larger than 4 bytes volatile but that's where the buck stops.
The C# language specification defines the behavior of volatile, quoted here by Eric Lippert.  The 'release' and 'acquire' semantics is something that only makes sense on a processor core with a weak memory model.  Those kind of processors have not done well in the market, probably because they are such an enormous pain to program.  The odds that your code will ever run on a Titanium are slim to none.
What's especially bad about the C# language specification definition is that it doesn't mention at all what really happens.  Declaring a variable volatile prevents the jitter optimizer from optimizing the code to store the variable in a cpu register.  Which is why the code that Marc linked is hanging.  This will only happen with the current x86 jitter, another strong hint that volatile is really a jitter implementation detail.
The poor semantics of volatile has a rich history, it comes from the C language.  Whose code generators have lots of trouble getting it right as well.  Here's a interesting report about it (pdf). It dates from 2008, a good 30+ years of opportunity to get it right.  Or wrong, this goes belly-up when the code optimizer is forgetting about a variable being volatile.  Unoptimized code never has a problem with it.  Notable is that the jitter in the 'open source' version of .NET (SSLI20) completely ignores the IL instruction.  It can also be argued that the current behavior of the x86 jitter is a bug.  I think it is, it is not easy to bump it into the failure mode.  But nobody can argue that it actually is a bug.
The writing is on the wall, only ever declare a variable volatile if it is stored in a memory mapped register.  The original intention of the keyword.  The odds that you'll run into such a usage in the C# language should be vanishingly small, code like that belongs in a device driver.  And above all, never assume that it is useful in a multi-threading scenario.


text:
Q: Dynamic button names on jQuery dialogs I have a webpage that uses different languages stored in localStorage, and on the jQuery dialog I want the names of the buttons to be dynamically changed according to the language, for example :
var btn_hello_text = getLanguageBtnHelloText();

$('#dialog').dialog({
    autoOpen: false,
    buttons: {
        btn_hello_text: function() {
            doThings();
        }
    }
});

The problem here is that the dialog shows a button with the text "btn_hello_text" and not the value included in the variable itself. I can't figure a way to change the value of the button text dynamically, any hints? Thank you.

A: You can use bracket notation (instead of dot notation), like this:
var my_buttons = {};
my_buttons[getLanguageBtnHelloText()] = doThings;

$('#dialog').dialog({
    autoOpen: false,
    buttons: my_buttons
});

A: You cannot do that using inline object declaration. But it can be done by using the square bracket syntax instead:
var btn_hello_text = getLanguageBtnHelloText();

var buttonDefs = {};
buttonDefs[btn_hello_text] = function() { doThings(); };

$('#dialog').dialog({
    autoOpen: false,
    buttons: buttonDefs
});


text:
Q: Can't find sendNotifications option Google Calendar api v3 .NET I'm testing out the Google Calendar API v3 on .Net. I've managed to add an event to a calendar as follows:
Google.Apis.Calendar.v3.Data.EventAttendee attendee = new Google.Apis.Calendar.v3.Data.EventAttendee();
attendee.Email = "[email]@gmail.com";

List<Google.Apis.Calendar.v3.Data.EventAttendee> event_attendees = new List<Google.Apis.Calendar.v3.Data.EventAttendee>();
event_attendees.Add(attendee);

Google.Apis.Calendar.v3.Data.Event new_event = new Google.Apis.Calendar.v3.Data.Event();

new_event.Summary = "GoogleCalendarTest: Testing Event 4";
new_event.Description = "Testing .Net Google Calendar API";
new_event.Location = "Offices";

new_event.Start = new Google.Apis.Calendar.v3.Data.EventDateTime();
new_event.Start.DateTime = DateTime.Now;

new_event.End = new Google.Apis.Calendar.v3.Data.EventDateTime();
new_event.End.DateTime = new DateTime(2014, 12, 15, 12, 0, 0);

new_event.Attendees = event_attendees;

service.Events.Insert(new_event, "[email]@gmail.com").Execute();

I thought this would automatically send an invite email to the attendee but it seems that by default it is not sent as seen here in the documentation. The sendNotifications parameter is added is an optional parameter, this question shows how it's done on PHP but I can't figure how to add this on .Net.
UPDATE
Figured out a way to set sendNotifications on .Net:
Google.Apis.Calendar.v3.EventsResource.InsertRequest insert_event = new EventsResource.InsertRequest(service, new_event, "[email]@gmail.com");
insert_event.SendNotifications = true;
insert_event.Execute();

Still not sending an invitation email though, might still be doing something wrong.
UPDATE 2
Version issue?
I've found this question: Google Calendar API for .Net: Email notifications not sent when creating calendar event, which is very similar to the problem I have. Uninstalling and installing the API solved the problem...I tried this out but still have the same problem, currrent version: 1.9.0

A: This worked for me:
EventsResource.InsertRequest request = service.Events.Insert(newEvent, "primary");
request.SendNotifications = true;
Event createdEvent = request.Execute();


text:
Q: How to Create New Image From Array List Which Contains Binary Pixel Data Here I use the PIL Library to read and manipulate images. I am confused, how to create a new image from the list of arrays containing binary pixel data, after being converted to binary images.
I have tried it, but the resulting image is of type RGB, not a binary image. The following is the code that I wrote:
from PIL import Image
import numpy as np

img = Image.open('data_train/ga.jpeg')

pixels = img.load()

width, height = img.size

all_pixels = []

for x in range(width):

    for y in range(height):
        hpixel = pixels[x, y]
        img_gray = (0.2989 * hpixel[0]) + (0.5870 * hpixel[1]) + (0.1140 * hpixel[2])

        if img_gray >= 110:
            all_pixels.append('1')
        else:
            all_pixels.append('0')

data_isi = {'0': 0,

            '1': 255}

data = [data_isi[letter] for letter in all_pixels]

img_new = Image.fromarray(data)

img_new.save('data_train/gabiner.jpeg')

A: Updated Answer
As you are required to use a for loop, you could go with something more like this:
#!/usr/bin/env python3

from PIL import Image

# Load image and get dimensions
img = Image.open('start.jpg').convert('RGB')
width, height = img.size

# Actually load input pixels, else PIL is too lazy
imi = img.load()

# List of result pixels
imo = []

for y in range(height):
    for x in range(width):
        R, G, B = imi[x, y]
        gray = (0.2989 * R) + (0.5870 * G) + (0.1140 * B)

        if gray >= 110:
            imo.append(255)
        else:
            imo.append(0)

# Make output image and put output pixels into it
result = Image.new('L', (width,height))
result.putdata(imo)

# Save result
result.save('result.png')

Which turns this start image:

Into this result:

Original Answer
You appear to be converting the image to greyscale and thresholding at 110, which can be done much more simply, and faster, like this:
#!/usr/local/bin/python3

from PIL import Image

# Load image and make greyscale
im = Image.open('image.png').convert('L')

# Threshold to make black and white
thr = im.point(lambda p: p > 110 and 255)

# Save result
thr.save('result.png')


text:
Q: making an and assigning as Array/Object (really basic) Really basic question.
I have a single form and want to create an object (I think) and assign a value to it.
Dim Devs as Object

    For i = 0 To 3
        If (Devices And 2 ^ i) Then
            Devs(i) = True ' breaks here
        Else
            Devs(i) = False 'or here (depends on the if obviously)
        End If
    Next i

With this I get an error: Object variable or With block variable not set
I thought I could just make an Array or Object and assign a value, but I guess I'm wrong.
What is the proper way to do this?

A: Looks like you want an array of Booleans
Dim Devs(0 To 3) As Boolean

Your current code has an Object variable that is not pointing to any object.

A: Your Devs variable seems to be an array of type Boolean. Correct?
Dim Devs(0 To 3) As Boolean()

or
Dim Devs() As Boolean()

Furthermore, what is the purpose of 2 ^ i ? Do you intend to validate its value in order to enter the first code bracket.
Dim myCondition As Integer
myCondition = 2

If (Devices = True And 2 ^ i = myCondition)
  ...


text:
Q: Java Script. Как сделать, чтобы в цикле,если в промпт введено не число,он переспрашивал его,а не переходил на другой? let firstYear;
let secondYear;

while(isNaN(parseFloat (firstYear && secondYear) ) && !isFinite(firstYear && secondYear) || (firstYear && secondYear) == `` || (firstYear && secondYear) == ` `) {
    firstYear = +prompt(`Начальный год`) ;
    secondYear = +prompt(`Конечный год`) ;
}

A: Попробуйте сделать два отдельных цикла, в каждом по одному prompt
Upd. Если нужно иметь один цикл
Хорошо бы в переменных хранить уже числа.
В условии цикла while проверяйте, что обе переменных содержат значения.
Внутри цикла считывайте первое значение, сразу приводите его к числу. Второе значение считывайте только если первое значение считано верно, используйте if


text:
Q: How to send/receive SMS in Zoiper with a Twilio number? I have a Twilio mobile number that has both voice and SMS functionality. I am able to make and receive calls in Zoiper, but I don't know how to set it up so I can also send/receive SMS. There are no guides on how to do this. How do I set this up?

A: Twilio developer evangelist here.
Twilio doesn't support SMS over SIP, only via the REST API (outbound) and webhooks (inbound). Twilio doesn't support SMS via SIP SIMPLE (as the Zoiper docs mention) so you cannot directly set up sending and receiving SMS messages via Twilio through Zoiper.


text:
Q: Web Application Accessing Local Filesystem I have a web application (.NET, if it matters) where when one of the pages is loaded, a file on the users local machine needs to be copied (uploaded) to the webserver.  This upload needs to be without user intervention.  This web application will be running on a kiosk where I would be setting up the original permissions and then locked down from accessing the desktop/filesystem.
Conversely, on another page, I need the web application to copy something to the users local machine (download).  Again, this download needs to be invisible to the user.
Any help would be greatly appreciated.
Many thanks in advance.
Update:
Yeah, I know this could be used maliciously.  I was hoping there was a way of doing this, but really, it shouldn't be allowed.  Bah, thanks for confirming my suspicions.
Update 2:
See comment to Guy Starbuck.

A: Yeah, that's not possible. And that's a very good thing.
If you really need this sort of functionality you'll have to write a standard executable application, not a web one.

A: Unless Firefox has some configuration options which permit this behaviour, I think you're outta luck.  Browsers do not permit user-unauthorized automatic downloads, for obvious reasons.

A: This is not a good idea, there must be a better design for your requirements.
In any case, if you really wanted to do it, and you have full control of the client kiosks, you could install a windows service on them that can manage file uploads/downloads and be controlled via TCP/IP from the web server.

A: If I were you I'd clarify what you're trying to do here because 1) do you know of any website that does this? and 2) it sounds like you're trying to make something malicious. Just saying.

A: hard to say if this would be useful, but depending on what you're trying to do, you might be able to simulate this behaviour with cookies.
If you're willing to allow a little bit of user intervention, and you're willing to restrict their useage to Internet Explorer, you can use jscript to do exactly what you're looking for, but the user WILL be prompted to allow said action.


text:
Q: Spectrum of a product Let $A$ be a unital $C^{*}$-algebra. I am trying to show that if $a,b\in A$ are positive elements, then the spectrum of $ab$ is contained in the positive real numbers. I know that in the commutative case, $\sigma(ab)\subseteq\sigma(a)\sigma(b)$ for any elements $a,b$ but here there is no assumption of commutativity.

A: Use
$$ \sigma(ab) \cup \{0\} = \sigma(ba) \cup \{0\} .$$
See Do $X(X'X)^{-1}(X'X)^{-1}X'$ and $(X'X)^{-1}$ have the same non-zero eigenvalues? for the proof of this (although if $a$ or $b$ is invertible, as it would be if $a$ and $b$ are positive, then $\sigma(ab) = \sigma(ba)$ can be proved much more easily.)
Then $\sigma(ab) = \sigma(a^{1/2} a^{1/2} b) = \sigma(a^{1/2} b a^{1/2})$, and $a^{1/2} b a^{1/2}$ is positive.


text:
Q: Python iterating over a list to add items to another list? So I am getting a list of items from a MySQL database, working with Python, Flask, Flask-SQLAlchemy. I am already incrementing rows of this list like this:
for file in files:
        file.last_viewed_time = datetime.utcnow()
    db.session.commit()

But I want to extract one more thing from this list (files),  a list of another attribute.
How can I add these to a new list, something like:
mylist = []

for file in files:
        new = file.attribute
        add new to mylist

Or is this a convoluted way of doing it, can I copy these values in a better way?

A: Use list.append:
mylist = []

for f in files:
    new = f.attribute
    mylist.append(new)

Or using list comprehension:
mylist = [f.attribute for f in files]

A: mylist = [f.attribute for f in files] # don't use file, it's the name of a builtin-function

A: try this
mylist = []

for file in files:
        new = file.attribute
        mylist.append(new)


text:
Q: Why does $\sum\limits_{i=1}^n \frac{i-1}{n} = \frac{n-1}{2}$? I am trying to understand the accepted answer to this question: Find: The expected number of urns that are empty
And am stuck on the part I mentioned above. I understand that:
$\sum\limits_{i=1}^n \frac{i-1}{n}=\frac{0}{n}+\frac{1}{n}+...+\frac{n-1}{n}.$ But why does this equal $\frac{n\choose2}{n}$?
I have also seen this sum solved as follows:
$\sum\limits_{i=1}^n \frac{i-1}{n}=\frac{1}{n}\sum\limits_{i=1}^n i-1=\frac{1}{n}\sum\limits_{j=0}^{n-1}j=\frac{1}{n}\frac{n(n-1)}{2}=\frac{n-1}{2}$
With this method, I am having trouble seeing what exactly $j$ is and why we all of sudden entered it into the equation.
I'd appreciate if someone could shed light on either of these ways of computing the sum.
Thanks

A: The equation
$$\sum_{i=1}^n(i-1)=\sum_{j=0}^{n-1}j\tag{1}$$
is just a change of variable. Let $j=i-1$; then $i=j+1$, so the lefthand side of $(1)$ becomes
$$\sum_{j+1=1}^nj\;,\tag{2}$$
When $j+1=1$, clearly $j=0$, and when $j+1=n$, $j=n-1$. Thus, as $j+1$ runs from $1$ up through $n$, $j$ itself runs from $0$ up through $n-1$, and we can rewrite $(2)$ as the righthand side of $(1)$.
An alternative approach that does not involve changing the index variable is to decompose the sum:
$$\sum_{i=1}^n(i-1)=\sum_{i=1}^ni-\sum_{i=1}^n1=\frac{n(n+1)}2-n=\frac{n^2+n-2n}2=\frac{n^2-n}2=\frac{n(n-1)}2\;,$$
where the first summation uses the familiar formula for the sum of the first $n$ positive integers, and the second is just the sum of $n$ ones, or $n$.

A: Well, $\sum \frac{i-1}{n} = \frac{\sum (i-1)}{n} = \frac{\sum(i)-n}{n} = \frac{\frac{n\cdot(n+1)}{2}-n}{n}=\frac{\frac{n\cdot(n-1)}{2}}{n}=\frac{n-1}{2}$.
I hope this helps.


text:
Q: Is it possible to import the array type, in Java? Is it possible to import the "array type" in Java?
I know this will be a useless import, but we can explicitly import java.util.String (although java.lang is automatically imported) or even the class that is being defined in the current compilation unit...
Is it possible to make this absurd import?

A: No, you can't import the array type. Like you can't import int or double

A: Array is more of a primitive type which are defined by the language. When you write int[] a = new int[5]; what you're actually doing is setting aside 5 memory locations that can hold a primitive int type. Same thing occurs for any other array declaration. In other words you can't import it from java.

A: You can't and there's no single array type in Java anyway. Array types created from different element types will be different themselves.
It's easy to see this if you try to compile this code:
String [] stringArray = new String[4];
Object [] objectArray = new Object[4];
objectArray = stringArray; //This won't work even though individually every String can be cast to Object

A: it's unnecessary. Once type T is understood, T[], T[][], T[][][]... are automatically understood. This is true for both compiler and runtime. Effectively, once T is imported, all T[]... are imported; once T is loaded by a classloader, all T[]... are loaded by the same class loader.


text:
Q: Try Catch or Boolean check Let's say I have the following code:
void validate(File f) //or boolean?????
{
  ...
  try
  {
    //try to validate xml file
  }
  catch (Exception e)
  {
  }
}

...

try
{

  validate(xml_file); //validates XML file
  move(xml_file, valid_folder); //moves valid XML file to valid_folder
}
catch (Exception e)
{
  move(xml_file, error_folder); //moves invalid XML file to error_folder
}

...

Should my validate() function be boolean and I should check whether file is valid XML file or not or catching will do it for me?

A: Exceptions should not be used to control the normal flow of your program. They slow down execution considerably when they occur. Your program wants to sort valid XML files from invalid XML files. So you're expecting the occurrence of invalid XML files, which is why you're sorting them into different files. Therefore, you should return a boolean rather than throwing an exception.

A: One problem you might want to think about is the single responsibility principle: a method should do one thing well.
Your validate method is doing at least three things:

*

*Reading XML from a file

*Validating that XML in some unspecified way

*Moving the file to one folder or another, depending on outcome

Perhaps you'll have an easier time if you break these up.
What if someone wants to validate XML without moving the file?  Your method can't be called in that case.
Even validating is questionable.  If you check against a schema you'll throw an exception on the first issue.  Would users want to know ALL the problems at once?  If yes, you'll have to walk the tree and find all the errors yourself.

A: If it returns boolean, it would look cleaner and simpler:
if(validate(xml_file)) move(xml_file, valid_folder);
else move(xml_file, error_folder);

However, your solution (throwing the exception) could carry a lot of information about the thrown exception that you can pass to move() method. Or alternatively validate() method returns int in which each value indicates specific state.

A: You can put it as boolean. You can add boolean variable (initially true) at the start of the validate method and inside catch you can set it to false. At the end of the function, return the boolean variable value. So if your code inside the try block encounters an exception, you handle it by setting the boolean variable to false so that your method returns false if exception encountered, true otherwise.


text:
Q: Dynamic LINQ: Use .NET Contains method to generate a dynamic search method I have a class Item like
public class Item
{
   public int Id {get;set;}
   public string Name {get;set;}
   public string PartialDescription {get;set;}
   public string FullDescription {get;set;}
   public doulbe Price {get;set;}
}

I would like to have a dynamic custom query method SearchOverAnyFields() that can accept any number of Item object's properties like:
// key is an input string variable

// one query
var results = myItems.SearchOverAnyFields(x => x.Name.Contains(key) || x.PartialDescription.Contains(key) || x.Price.ToString().Contains(key));

// or another query
var results2 = myItems.SearchOverAnyFields(x => x.Name.Contains(key) || x.PartialDescription.Contains(key) || x.Price.ToString().Contains(key)
|| x.FullDescription.Contains(key));

// or another query
var results3 = myItems.SearchOverAnyFields(x => x.PartialDescription.Contains(key) ||  x.FullDescription.Contains(key));

Please help.

A: Something like this would probably do the job for you...
    public static IEnumerable<Item> SearchOverAnyFields(this IEnumerable<Item> items, string key, params Func<Item,string>[] fields)
    {
        return
            from item in items
            from field in fields.
            Where(field => field(item) != null && field(item).Contains(key))
            select item;
    }

    public static void ExampleUsage(object[] args)
    {
        var items = new List<Item> { new Item { Name = "badger" }, new Item { PartialDescription = "badger" }, new Item { } };

        // searches items for any item that has "badger" in it's name or PartialDescription
        var result = items.SearchOverAnyFields("badger", i => i.Name, i => i.PartialDescription);

        foreach (var res in result)
            Debug.WriteLine(res);
    }

Calling ExampleUsage() would print two statements to the debug console, to verify they're the correct Items you'd have to build a ToString method for them.

A: I'm not really sure what you're looking for here - the functionality you want can be easily achieved with the Where operator.
var results = myItems.Where(x => x.Name.Contains(key) ||
    x.PartialDescription.Contains(key) || x.Price.ToString().Contains(key));

// or another query
var results2 = myItems.Where(x => x.Name.Contains(key) ||
    x.PartialDescription.Contains(key) || x.Price.ToString().Contains(key)
    || x.FullDescription.Contains(key));

// or another query
var results3 = myItems.Where(x => x.PartialDescription.Contains(key) ||
    x.FullDescription.Contains(key));

Does this meet your requirement?


text:
Q: Use of "the" with nationalities that have plural forms Is the rule 7.8 here widely accepted in English?

Rule 7.8: Use the definite article when referring to nationalities that do not have a plural form.

If it is, does it sound off when one says "'the American' ARE famous for loving sugar" to refer to the American nation as a whole in a collective or generic sense whereas "Americans / American people / the Americans / the American people / the people of America are famous for loving sugar" is okay? We all know that Americans have a demonym, "an American", but French people doesn't, which is the reason we say "a French person or a Frenchman/woman instead of "a French" and "the French" instead of "*the Frenches" as a people. Some native English speakers say it's okay, others don't. And I'm confused.

A: I think part of the reason is that recently it has become more respectable to say "French people" vs. "The French". Similar to how it feels more respectful to say "A Jewish person" vs. "A Jew".
I think in general, people are moving to "[Natn'l Adj] + people" which may have "the" as its article or the zero article. Some people may have told you to say "The [nationality]" to refer to all people of a country because of this, but that doesn't mean it is grammatically wrong.

But besides that, I would generally agree with the rule that you provide:

Rule 7.8: Use the definite article when referring to nationalities that do not have a plural form. Nationalities that end in -ss, -ch, -ese, or -sh have no plural form.

is correct. But one must take into account the other rules listed as well.

The American are famous for loving sugar

does not sound correct.
Of the options you give for replacement, almost all of them work to refer to a general characteristic of people from America, except the bolded one.

Americans / American people / the Americans / the American people / the people of America are famous for loving sugar

The usage of "The Americans" is where the "Extra!" rule takes over:

Extra! Use the definite article when referring to a specific group of people who have the same nationality.

So this is more likely to be applied to a specific (usually small) subset of Americans as opposed to all Americans. The most common example is when teams are competing on an international stage and representing their countries (eg. Olympics).
If, for example, the American bobsled team was famous for their love of chocolates and gummy bears, then an announcer could say:

The Americans are famous for loving sugar, especially chocolates and gummy bears. In fact, Americans - in general - love sugar.

In this example the announcer is first referring to the few people on the US bobsled team, but then expanding the statement to all Americans.
Trying to say the same thing for "French" or "Japanese" wouldn't be as clear so the announcer might use "these" instead of "the". (which could also be done in the above example)

These French are famous for loving baguettes. In fact, The French - in general - love baguettes.


text:
Q: Trying to write to a CSV but some fields get excluded in scrapy for python I am trying to write to CSV but when I check the output, I see that some 'review' fields are left blank even though there when I see the output it prints it correctly. I believe this is a zip() limitation as I am using that to have it print column wise rather than 10 in a row. Again the Xpath output i print in spider outputs it correctly. Im wondering is it a limitaion of zip or my syntax? Or another guess it is maybe the delimeter=','.
Pipline.py
import csv
import itertools
from string import maketrans
class CSVPipeline(object):

   def __init__(self):
      self.csvwriter = csv.writer(open('Output.csv', 'wb'),delimiter=',')
      self.csvwriter.writerow(['names','date','location','starts','subjects','reviews'])

   def process_item(self, item, ampa):

      rows = zip(item['names'],item['date'],item['location'],item['stars'],item['subjects'],item['reviews'])

      for row in rows:
         self.csvwriter.writerow(row)

      return item

Sample output, some reviews get excluded
names,date,location,starts,subjects,reviews
Aastha2015,20 July 2015,"
Bengaluru (Bangalore), India
",5,Amazing Time in Ooty,"
Hi All, i visited Ooty on July 10th, choose to stay in Elk Hills hotel, i read reviews of almost all good hotels and decided to try Elk Hills. I must say the property is huge, very well maintained. Rooms are clean spacious & views are great. Food in the Cafe Blue was awesome. They forgot to give us the...
"
pushp2015,11 July 2015,"
Gurgaon, India
",3,Nice Hotel ...under going maintainance,"
"
REDDY84,25 June 2015,"
Chennai, India
",4,Good old property,"
Its an old property with a very good view. We booked a suite at a very reasonable price but they charged for an extra bed 1500 + txs which i feel was not required because the bed was already their in the suite room.Other then that everything was good. Breakfast was nice . The room they had given was neat...
"
arun606,20 June 2015,"
Mumbai, India
",5,Amazing Hospitality,"
"

A: I'm not sure but I think what you call a limitation is more the zip way of working.
Check out izip_longest which will not stop at the shortest list.
Example:
>>> zip('abc', '12345')
[('a', '1'), ('b', '2'), ('c', '3')]
>>> list(itertools.izip_longest('abc', '12345', fillvalue=0))
[('a', '1'), ('b', '2'), ('c', '3'), (0, '4'), (0, '5')]

A: Figured it out, As @Martin Evans stated I checked the lengths and found that There were many carriage returns that would simply put a blank space. i dont know why but it does. To fix it just add this code.
while "\n" in yourlist['key']: yourlist['key'].remove("\n")


text:
Q: Can I call a thread recurrently from within a thread? I'm trying to transfer samples from thread A ("Acquisition") to thread B ("P300") using queue but I can't read any data in thread B, although samples are being allocated in thread A. Judging by my output, I think my thread B is rushing and testing things before my thread A starts to put data in.
See an approximation of my code structure bellow:
import threading
import queue
from queue import Empty
import numpy as np
import warnings
warnings.filterwarnings("error")

class AcqThread(threading.Thread):
    def __init__(self, dataOutQ1, dataOutQ2, stopQ1, stopQ2, saveQ):
        threading.Thread.__init__(self)
        self.stopQ2 = stopQ2
        self.stopQ1 = stopQ1
        self.dataOutQ2 = dataOutQ2
        self.dataOutQ1 = dataOutQ1
        self.saveQ = saveQ

    def run(self):
        Acquisition(inlet, self.dataOutQ1, self.dataOutQ2, self.stopQ1, self.stopQ2, self.saveQ)

class P300Thread(threading.Thread):
    def __init__(self, dataInQ, featureQ, stopQ):
        threading.Thread.__init__(self)
        self.dataInQ = dataInQ
        self.featureQ = featureQ
        self.stopQ = stopQ

    def run(self):
        P300fun(self.dataInQ, self.featureQ, self.stopQ)

threadLock = threading.Lock()
SaveQ = queue.Queue()
DataOutQ1 = queue.Queue()
DataOutQ2 = queue.Queue()
StopQ1 = queue.Queue()
StopQ2 = queue.Queue()
FeatQ1 = queue.Queue()
StopQ1.put(0)
StopQ2.put(0)
#
AcqTh = AcqThread(DataOutQ1, DataOutQ2, StopQ1, StopQ2, SaveQ)
P300Th = P300Thread(DataOutQ1, FeatQ1, StopQ1)

def Acquisition(inlet, dataOutQ1, dataOutQ2, stopQ1, stopQ2, saveQ):
    i = 0
    print('Starting...')
    while i<1250: #i is the number of samples
        sample, timestamp = inlet.pull_sample() #samples coming in @ 250Hz
        ##Normalization, filtering##
        threadLock.acquire()
        dataOutQ1.put([filtsamples[:,-250:], rawtimestamps[-250:]]) #I only need the last 250 samples
        threadLock.release()
        i += 1

def P300fun(dataInQ, featureQ, stopQ):
    p300sample = []
    p300timestamp = []
    print(f"Is DataInQ size true? {DataOutQ1.qsize()}")
    print("Is dataInQ emtpy?", DataOutQ1.empty())
    while dataInQ.qsize(): #or while not dataqueue.empty():
        try:
            print("DataInQ has data")
            ss, ts = dataInQ.get(0)
            print('<>P300\n>>Samples [', ss, ']\nTimestamp [', ts, ']')
        except Empty:
            return
    print('Thread Finished')

if __name__ == '__main__':
    print('Looking for an EEG stream...')
    streams = resolve_stream('type', 'EEG')
    inlet = StreamInlet(streams[0])
    print('Connected!\n')

    AcqTh.start()
    P300Th.start()

    AcqTh.join()
    P300Th.join()

    print("\n\n>>>DONE<<<\n\n")

And output:
Looking for an EEG stream...
Connected!

Is DataInQ size true? 0
Starting...
Is dataInQ emtpy? True
Thread Finished

>>>DONE<<<

In my research, question 1 appeared to present a similar problem, but it seems that the problem was in the image processing part (and they use the multiprocessing package). Question 2 seems to have a concurrency problem, which might be my problem, but I'm not sure how to translate it to my problemlet me know if I'm wrong, tho). Question 3 had just a problem with the order of arguments, so not applicable here, I think.
How should I go about this? Should I recurrently call thread B from within thread A?? Do I need a loop or a delay on thread B? Is there some issue with the .join() part maybe? I'll need to add more threads in a near future, so it would be good to figure out how to work with only two first...
All help is appreaciated!

A: Being a noob can be tricky... So I'll answer my own question to help other beginners that may come across this issue too.
Well, first things first: no, it's not possible to call a thread from within a thread recurrently, because each thread can only be called once.
But there is a way to prevent the thread from ending, making them wait for triggers that will allow them to continue. After some more research, I came across this question that showed me there is a way to create events for threads. The documentation can be found here. And it's quite straight forward: the event objects behave like flags and can be set() (indicating True) or clear() (indicating False, which is the original value). To test an event, one can use the is_set() method for boolean problems or use the wait() method instead of a timer. In my case, it saved me some queues I was going to use:
import threading
import queue
from queue import Empty
import numpy as np

class AcqThread(threading.Thread):
    def __init__(self, dataOutQ1, dataOutQ2, saveQ):
        threading.Thread.__init__(self)
        self.dataOutQ2 = dataOutQ2
        self.dataOutQ1 = dataOutQ1
        self.saveQ = saveQ

    def run(self):
        Acquisition(inlet, self.dataOutQ1, self.dataOutQ2, self.saveQ)

class P300Thread(threading.Thread):
    def __init__(self, dataInQ, featureQ):
        threading.Thread.__init__(self)
        self.dataInQ = dataInQ
        self.featureQ = featureQ

    def run(self):
        P300fun(self.dataInQ, self.featureQ)

threadLock = threading.Lock()
SaveQ = queue.Queue()
DataOutQ1 = queue.Queue()
DataOutQ2 = queue.Queue()
FeatQ1 = queue.Queue()
FeatQ2 = queue.Queue()

#NEW:: initializes Events
E = threading.Event()
EP300 = threading.Event()
#
AcqTh = AcqThread(DataOutQ1, DataOutQ2, SaveQ)
P300Th = P300Thread(DataOutQ1, FeatQ1)

And it allows me to "call" thread B "recurrently", as it keeps my first while active (because of event E) and enters the processing part only when the event EP300 is set. Then, EP300 is cleared after the process is done:
def Acquisition(inlet, dataOutQ1, dataOutQ2 saveQ):
    i = 0
    print('Starting...')
    while i<1250:
        sample, timestamp = inlet.pull_sample()
        ##Normalization, filtering##
        if _condition_:
            threadLock.acquire()
            dataOutQ1.put([filtsamples[:,-250:], rawtimestamps[-250:]])
            threadLock.release()
            EP300.set() #NEW:: allows the P300 function to collect data from queue
        i += 1
    E.set() #NEW:: flaggs end data collection

def P300fun(dataInQ, featureQ):
    p300sample = []
    p300timestamp = []
    while not E.is_set(): #NEW:: loop until collection is ended
        if EP300.is_set(): #NEW:: activated when Event is triggered
            while dataInQ.qsize():
                try:
                    print("DataInQ has data")
                    ss, ts = dataInQ.get(0)
                    print('<>P300\n>>Samples [', ss, ']\nTimestamp [', ts, ']')
                except Empty:
                    return
        if not E.is_set(): #NEW:: Event is cleared in case data collection is not over, waiting for a new set()
            EP300.clear()
    print('Thread Finished')

if __name__ == '__main__':
    print('Looking for an EEG stream...')
    streams = resolve_stream('type', 'EEG')
    inlet = StreamInlet(streams[0])
    print('Connected!\n')

    AcqTh.start()
    P300Th.start()

    AcqTh.join()
    P300Th.join()

    print("\n\n>>>DONE<<<\n\n")